pilotswarm 0.5.49 → 0.5.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/ui/react/src/web-app.js +72 -3
- package/web/dist/assets/{abnfDiagram-VRR7QNED-CXF6f3n3.js → abnfDiagram-VRR7QNED-C_4vfIbv.js} +1 -1
- package/web/dist/assets/{arc-MlDVINID.js → arc-DOWqX-WF.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-Bdz1J9H-.js → architectureDiagram-ZJ3FMSHR-Cc38vIUp.js} +1 -1
- package/web/dist/assets/{blockDiagram-677ZJIJ3-tO706-rr.js → blockDiagram-677ZJIJ3-CJasxBgg.js} +1 -1
- package/web/dist/assets/{c4Diagram-LMCZKHZV-BuZrMrYZ.js → c4Diagram-LMCZKHZV-CSsFEvwn.js} +1 -1
- package/web/dist/assets/channel-CJecP6sr.js +1 -0
- package/web/dist/assets/{chunk-2Q5K7J3B-BWWIPnCk.js → chunk-2Q5K7J3B-Cdcmo5W3.js} +1 -1
- package/web/dist/assets/{chunk-32BRIVSS-TyL8x2Q5.js → chunk-32BRIVSS-CmCFzR3z.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-ZTwZyN5B.js → chunk-5VM5RSS4-gZUtbZIc.js} +1 -1
- package/web/dist/assets/{chunk-EX3LRPZG-CjWsKz70.js → chunk-EX3LRPZG-nF9v3PEA.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-BNQrzsa3.js → chunk-JWPE2WC7-BhwKbO0c.js} +1 -1
- package/web/dist/assets/{chunk-MOJQB5TN-B51xJi0l.js → chunk-MOJQB5TN-B8zfb4XG.js} +1 -1
- package/web/dist/assets/{chunk-RYQCIY6F-BCdsh9nc.js → chunk-RYQCIY6F-SM2kSUT1.js} +1 -1
- package/web/dist/assets/{chunk-V7JOEXUC-C7FFxC7C.js → chunk-V7JOEXUC-C7lbdZCo.js} +1 -1
- package/web/dist/assets/{chunk-VR4S4FIN-DWoFV0Pb.js → chunk-VR4S4FIN-BZR3_tbV.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-plM48yQb.js → chunk-XXDRQBXY-DU5shflv.js} +1 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-BqWAphrT.js +1 -0
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-BqWAphrT.js +1 -0
- package/web/dist/assets/{cose-bilkent-JH36ORCC-cPPsd8jq.js → cose-bilkent-JH36ORCC-O3mfbu3h.js} +1 -1
- package/web/dist/assets/{cynefin-VYW2F7L2-DLoMRcB-.js → cynefin-VYW2F7L2-kJrtGP23.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-TSTJHNR4-DbxB1EcR.js → cynefinDiagram-TSTJHNR4-DBJPD4ep.js} +1 -1
- package/web/dist/assets/{dagre-VKFMJZFB-Cl5J3v7U.js → dagre-VKFMJZFB-Dcs8wwU7.js} +1 -1
- package/web/dist/assets/{diagram-FQU43EPY-C_5l69HJ.js → diagram-FQU43EPY-DyfyZ0qG.js} +1 -1
- package/web/dist/assets/{diagram-G47NLZAW-B_nxM69x.js → diagram-G47NLZAW-Dd2HPM5s.js} +1 -1
- package/web/dist/assets/{diagram-NH7WQ7WH-BogLLCcM.js → diagram-NH7WQ7WH-DC03_BJp.js} +1 -1
- package/web/dist/assets/{diagram-OA4YK3LP-1HZ1DJgO.js → diagram-OA4YK3LP-CfPUNCYI.js} +1 -1
- package/web/dist/assets/{diagram-WEI45ONY-CZ9akwtz.js → diagram-WEI45ONY-O-K9BqwQ.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-CCIWWBDH-CCg2iaF2.js → ebnfDiagram-CCIWWBDH-Pu3yFM4q.js} +1 -1
- package/web/dist/assets/{erDiagram-Q63AITRT-BCYw6hLk.js → erDiagram-Q63AITRT-9oh4uutz.js} +1 -1
- package/web/dist/assets/{flowDiagram-23GEKE2U-B3O-UeAj.js → flowDiagram-23GEKE2U-D6sP81ck.js} +1 -1
- package/web/dist/assets/{ganttDiagram-NO4QXBWP-GJzz1tR4.js → ganttDiagram-NO4QXBWP-7aJ0dtGR.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-Ch1cfaOe.js → gitGraphDiagram-IHSO6WYX-bLa8NZvk.js} +1 -1
- package/web/dist/assets/{index-wYKm3Bnl.js → index-DT_gy82W.js} +2 -2
- package/web/dist/assets/{infoDiagram-FWYZ7A6U-Bjo2ImAx.js → infoDiagram-FWYZ7A6U-Bx2QUCNC.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-Cknf936W.js → ishikawaDiagram-FXEZZL3T-Z43QbfP4.js} +1 -1
- package/web/dist/assets/{journeyDiagram-5HDEW3XC-Chy2vDKP.js → journeyDiagram-5HDEW3XC-DDp4teSL.js} +1 -1
- package/web/dist/assets/{kanban-definition-HUTT4EX6-BL4WMBwi.js → kanban-definition-HUTT4EX6-CoNysaii.js} +1 -1
- package/web/dist/assets/{linear-B8XSGnZ8.js → linear-DiAWjM7P.js} +1 -1
- package/web/dist/assets/{mermaid.core-CFdkmvEY.js → mermaid.core-Pc4CQtPH.js} +4 -4
- package/web/dist/assets/{mindmap-definition-LN4V7U3C-CHOBIkSR.js → mindmap-definition-LN4V7U3C-BXkQ4eOw.js} +1 -1
- package/web/dist/assets/{papaparse.min-DnG1sqyK.js → papaparse.min-CzTZ22jn.js} +1 -1
- package/web/dist/assets/{pegDiagram-2B236MQR-VuMpZEdm.js → pegDiagram-2B236MQR-DLawXMJA.js} +1 -1
- package/web/dist/assets/{pieDiagram-ENE6RG2P-CkFTLWPp.js → pieDiagram-ENE6RG2P-Bqw6TCQf.js} +1 -1
- package/web/dist/assets/{pilotswarm-CLJw14xm.js → pilotswarm-CJ6SEIPj.js} +6 -6
- package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-B74MHjsI.js → quadrantDiagram-ABIIQ3AL-D4Nrodp1.js} +1 -1
- package/web/dist/assets/{railroadDiagram-RFXS5EU6-CwcT-BI1.js → railroadDiagram-RFXS5EU6-14ozmmna.js} +1 -1
- package/web/dist/assets/{requirementDiagram-TGXJPOKE-CfV8rmaQ.js → requirementDiagram-TGXJPOKE-g2jB_CR_.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-HTMAVEWB-BECA4LLx.js → sankeyDiagram-HTMAVEWB-UsWtjkg-.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-C80kbBkw.js → sequenceDiagram-DBY2YBRQ-DOCKalZQ.js} +1 -1
- package/web/dist/assets/{sizeCapture-X5ZJPWSS-BgdLZC94.js → sizeCapture-X5ZJPWSS-GOrSPHZX.js} +1 -1
- package/web/dist/assets/{stateDiagram-2N3HPSRC-DY_mnuOT.js → stateDiagram-2N3HPSRC-DcTBrPP0.js} +1 -1
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-DjyLnyGF.js +1 -0
- package/web/dist/assets/{swimlanes-5IMT3BWC-9m8kjDvw.js → swimlanes-5IMT3BWC-DXlohBs3.js} +2 -2
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-B8GZDsc2.js +8 -0
- package/web/dist/assets/{timeline-definition-FHXFAJF6-CRDqu4Os.js → timeline-definition-FHXFAJF6-CLAJChwQ.js} +1 -1
- package/web/dist/assets/{vennDiagram-L72KCM5P-B2KNeFvN.js → vennDiagram-L72KCM5P-DapjeRd3.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-EHGQE667-DC0vN3Ub.js → wardleyDiagram-EHGQE667-eYWaR7BL.js} +1 -1
- package/web/dist/assets/{xychartDiagram-FW5EYKEG-DOY6Rwu4.js → xychartDiagram-FW5EYKEG-DcJXUeUI.js} +1 -1
- package/web/dist/index.html +2 -2
- package/web/dist/assets/channel-moQWQGwr.js +0 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-33Sv-tmv.js +0 -1
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-33Sv-tmv.js +0 -1
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-Dw3VhZ5V.js +0 -1
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-DoOI0AiK.js +0 -8
|
@@ -22,7 +22,7 @@ Request body:
|
|
|
22
22
|
${l}`,...i?{mobileText:`${i}
|
|
23
23
|
|
|
24
24
|
${l}`}:{},time:"",splash:!0}]}const Tl=.7,Pu=30,ao=36,jn=18,Ks=18,Gn=0,Pl=3,as=6,xn=10,Mu=.25,_u=.5,es=6,nn=10,Ml=.336,Wn=es,zn=nn,qn=as,Kn=xn;function zt(t,e,s){return Math.max(e,Math.min(s,t))}function Ru(t){return[$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY].includes(t)?t:null}function $u(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function ts(t=""){const e=String(t||"").split(`
|
|
25
|
-
`).length;return zt(e,1,Pl)}function _l(t){return Math.max(as,Math.floor(t*Mu))}function Rl(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*_u),n=Math.max(as,e-xn);return Math.max(as,Math.min(n,s))}function lo(t,e){const s=Math.max(0,Number(t)||0),n=zt(Math.max(0,Number(e)||0),0,s),r=-(s/2);return{minAdjust:r,maxAdjust:Math.max(r,s/2-n)}}function Cs(t,e=0,s=1,n=0,r=0,i=null){const a=$u(t),l=a.width,c=a.height,d=zt(Number(s)||1,1,Pl),u=Ru(i),p=5+d,m=Math.max(18,c-p),h=Math.floor(l*Tl)+(Number(e)||0),g=l-h-Gn;let b=!1,y=!1;h<=jn&&g>Ks?b=!0:g<=Ks&&h>jn?y=!0:h<=jn&&g<=Ks&&(y=e>=0,b=!y);let S,w;b?(S=0,w=l):y?(S=l,w=0):(S=zt(h,Pu,l-ao-Gn),w=Math.max(ao,l-S-Gn));const E=_l(m)+(Number(n)||0),x=m-E;let v=!1,P=!1;x<=Kn&&E>qn?P=!0:E<=qn&&x>Kn?v=!0:x<=Kn&&E<=qn&&(P=(Number(n)||0)>=0,v=!P);let N,_;if(v)N=0,_=m;else if(P)N=m,_=0;else{const ce=Rl(c,m);N=zt(E,as,ce),_=Math.max(xn,m-N)}const L=Math.max(es,Math.floor(m*Ml))+(Number(r)||0),I=m-L;let C=!1,U=!1;I<=zn&&L>Wn?C=!0:L<=Wn&&I>zn?U=!0:I<=zn&&L<=Wn&&(C=(Number(r)||0)>=0,U=!C);let B,V;return C?(B=m,V=0):U?(V=m,B=0):(B=zt(L,es,Math.max(es,m-nn)),V=Math.max(nn,m-B)),{viewport:a,totalWidth:l,totalHeight:c,reservedRows:p,bodyHeight:m,promptRows:d,fullscreenPane:u,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(r)||0,leftHidden:b,rightHidden:y,inspectorHidden:C,activityHidden:U,sessionHidden:v,chatHidden:P,leftWidth:S,rightWidth:w,sessionPaneHeight:N,chatPaneHeight:_,activityPaneHeight:B,inspectorPaneHeight:V}}function kr(t){if(t?.fullscreenPane)return[t.fullscreenPane,$.PROMPT];if(t?.leftHidden)return[$.INSPECTOR,$.ACTIVITY,$.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[$.CHAT]:t?.chatHidden?[$.SESSIONS]:[$.SESSIONS,$.CHAT],$.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[$.ACTIVITY]:t?.activityHidden?[$.INSPECTOR]:[$.INSPECTOR,$.ACTIVITY];return[$.CHAT,...e,$.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[$.ACTIVITY]:t?.activityHidden?[$.INSPECTOR]:[$.INSPECTOR,$.ACTIVITY];return[$.SESSIONS,...e,$.PROMPT]}return t?.inspectorHidden?[$.SESSIONS,$.CHAT,$.ACTIVITY,$.PROMPT]:t?.activityHidden?[$.SESSIONS,$.CHAT,$.INSPECTOR,$.PROMPT]:[$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY,$.PROMPT]}function it(t,e){const s=kr(e);return s.includes(t)?t:s[0]||$.PROMPT}function Lu(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[$.PROMPT]:$.PROMPT,[$.ACTIVITY]:$.INSPECTOR,[$.INSPECTOR]:$.INSPECTOR}[t]||$.INSPECTOR:e?.rightHidden?{[$.PROMPT]:$.PROMPT,[$.CHAT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.SESSIONS]:$.SESSIONS}[t]||(e?.sessionHidden?$.CHAT:$.SESSIONS):{[$.PROMPT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.ACTIVITY]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.INSPECTOR]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.CHAT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.SESSIONS]:$.SESSIONS}[t]||(e?.sessionHidden?$.CHAT:$.SESSIONS)}function Ou(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[$.PROMPT]:$.PROMPT,[$.INSPECTOR]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.INSPECTOR:e?.rightHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.CHAT]:$.CHAT}[t]||(e?.chatHidden?$.SESSIONS:$.CHAT):e?.inspectorHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.CHAT:e?.activityHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.INSPECTOR,[$.INSPECTOR]:$.INSPECTOR}[t]||$.CHAT:{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.INSPECTOR,[$.INSPECTOR]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.CHAT}function $l(t){const e=String(t||"").trim();if(!e)return{error:"Paste a link to plugin.json or the folder that contains it."};let s;try{s=new URL(e)}catch{return{error:"That does not look like a URL — paste the browser link to plugin.json or its folder."}}const n=s.hostname.toLowerCase();if(n==="github.com"||n==="www.github.com"){const i=s.pathname.split("/").filter(Boolean);if(i.length<2)return{error:"GitHub links need at least github.com/org/repo."};const[a,l,c,d,...u]=i,p=l.replace(/\.git$/u,""),m=`https://github.com/${a}/${p}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:d?{kind:"github",repoUrl:m,ref:d,path:u.length?`/${u.join("/")}`:null}:{error:"That GitHub link is missing the branch segment."}:{kind:"github",repoUrl:m,ref:null,path:null}}if(n==="dev.azure.com"||n.endsWith(".visualstudio.com")){if(!s.pathname.includes("/_git/"))return{error:"Azure DevOps links must point at a repo (…/_git/<repo>…)."};const i=`${s.origin}${s.pathname.split("?")[0]}`.replace(/\/$/u,""),a=s.searchParams.get("path"),l=s.searchParams.get("version"),c=l&&/^G[BT]/u.test(l)?l.slice(2):l||null;return{kind:"ado",repoUrl:i,ref:c,path:a||null}}return{error:"Only GitHub and Azure DevOps links are recognized here — for a tarball use the URL tab."}}const rn=2*1024*1024,Fu=new Set(["node_modules",".git"]);function xr(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s="";const n=32768;for(let r=0;r<e.length;r+=n)s+=String.fromCharCode.apply(null,e.subarray(r,r+n));return btoa(s)}function Ll(t){const e=String(t||"").replace(/\s+/gu,"");if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const s=atob(e),n=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)n[r]=s.charCodeAt(r);return n}function Ol(t){return t.split("/").some(e=>Fu.has(e))}function Fl(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function Du(t,e){return t?`${t}/${e}`:e}function Dl(t,e){const s=String(e?.message||e||"");return new Error(`could not reach ${t} from the browser (${s||"network error"}) — the host may block cross-origin reads from this portal; use Upload folder instead`)}async function on(t,e,s,n){let r;try{r=await t(e,{headers:{accept:"application/json",...s}})}catch(i){throw Dl(n,i)}if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`${n} returned HTTP ${r.status}${i?`: ${i.slice(0,200)}`:""}`)}return r.json()}async function Bl(t,e,s,n){let r;try{r=await t(e,{headers:s})}catch(a){throw Dl(n,a)}if(!r.ok)throw new Error(`${n} returned HTTP ${r.status} for ${e}`);const i=await r.arrayBuffer();return new Uint8Array(i)}function Bu(t){const e=new URL(t).pathname.split("/").filter(Boolean);if(e.length<2)throw new Error(`not a GitHub repository URL: ${t}`);return{owner:e[0],repo:e[1].replace(/\.git$/u,"")}}async function Hu({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,onProgress:i}){const{owner:a,repo:l}=Bu(t),c="https://api.github.com",d={"x-github-api-version":"2022-11-28",...r?{authorization:`Bearer ${r}`}:{}};let u=e;u||(i("resolving the default branch…"),u=(await on(n,`${c}/repos/${a}/${l}`,d,"api.github.com"))?.default_branch||"main"),i(`reading the file tree of ${a}/${l}@${u}…`);const p=await on(n,`${c}/repos/${a}/${l}/git/trees/${encodeURIComponent(u)}?recursive=1`,d,"api.github.com");if(p?.truncated)throw new Error("this repository's file tree is too large for the API listing — point the link at the package folder");const m=Array.isArray(p?.tree)?p.tree:[],f=Fl(s),h=Du(f,"plugin.json");if(!m.some(k=>k.type==="blob"&&k.path===h))throw new Error(`no plugin.json at ${h||"the repository root"} on ${u} — link to the folder that contains the manifest`);const g=f?`${f}/`:"",b=m.filter(k=>k.type==="blob"&&(!g||k.path.startsWith(g))&&!Ol(k.path.slice(g.length))),y=[];let S=0,w=0;for(const k of b){w+=1;const E=k.path.slice(g.length);i(`fetching ${w}/${b.length}: ${E}`);const x=r?await Uu(n,c,a,l,k.sha,d):await Bl(n,`https://raw.githubusercontent.com/${a}/${l}/${encodeURIComponent(u)}/${k.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(S+=x.length,S>rn)throw new Error(`package exceeds the ${Math.round(rn/1024)} KB upload limit at ${E}`);y.push({path:E,contentBase64:xr(x)})}return y}async function Uu(t,e,s,n,r,i){const a=await on(t,`${e}/repos/${s}/${n}/git/blobs/${r}`,i,"api.github.com"),l=String(a?.content||"").replace(/\s+/gu,"");if(a?.encoding&&a.encoding!=="base64")throw new Error(`unexpected blob encoding "${a.encoding}" from api.github.com`);return Ll(l)}function ju(t){const e=new URL(t),s=e.pathname.split("/").filter(Boolean),n=s.indexOf("_git");if(n<0||n===s.length-1)throw new Error(`not an Azure DevOps repository URL: ${t}`);const r=decodeURIComponent(s[n+1]),i=s.slice(0,n).map(decodeURIComponent),a=e.hostname.toLowerCase(),l=a.endsWith(".visualstudio.com")?a.split(".")[0]:i[0],c=a.endsWith(".visualstudio.com")?i[0]:i[1];if(!l||!c)throw new Error(`could not read org/project from ${t}`);return{org:l,project:c,repo:r}}async function Gu({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,tokenKind:i,onProgress:a}){if(!r)throw new Error("Azure DevOps needs a credential — sign-in did not yield a token; paste a PAT with Code (read)");const{org:l,project:c,repo:d}=ju(t),u=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(d)}`,m={authorization:i==="pat"?`Basic ${xr(new TextEncoder().encode(`:${r}`))}`:`Bearer ${r}`},f=Fl(s),h=`/${f}`,g=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";a(`reading ${d}${f?`/${f}`:""}…`);const b=await on(n,`${u}/items?scopePath=${encodeURIComponent(h)}&recursionLevel=Full${g}&api-version=7.1`,m,"dev.azure.com"),S=(Array.isArray(b?.value)?b.value:[]).filter(P=>P?.gitObjectType==="blob"&&!P?.isFolder),w=f?`/${f}/`:"/";if(!S.find(P=>P.path===`${w}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${h} — link to the folder that contains the manifest`);const E=[];let x=0,v=0;for(const P of S){const N=String(P.path||"").slice(w.length);if(!N||Ol(N))continue;v+=1,a(`fetching ${v}/${S.length}: ${N}`);const _=await Bl(n,`${u}/blobs/${encodeURIComponent(P.objectId)}?api-version=7.1&$format=octetStream`,{...m,accept:"application/octet-stream"},"dev.azure.com");if(x+=_.length,x>rn)throw new Error(`package exceeds the ${Math.round(rn/1024)} KB upload limit at ${N}`);E.push({path:N,contentBase64:xr(_)})}return E}async function Wu(t,{fetchImpl:e=typeof fetch=="function"?fetch:null,token:s=null,tokenKind:n="bearer",onProgress:r=()=>{}}={}){if(typeof e!="function")throw new Error("no fetch implementation available");const i=$l(t);if(i.error)throw new Error(i.error);const a={fetchImpl:e,token:s,tokenKind:n,onProgress:r},l=i.kind==="github"?await Hu(i,a):await Gu(i,a);if(l.length===0)throw new Error("the package folder is empty");return{kind:i.kind,files:l}}function zu(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=Ll(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function co(t){return t?.isSystem?yl(t):Number.MAX_SAFE_INTEGER}function qu(t=[]){const e=new Map;for(let s=0;s<t.length;s+=1){const n=t[s]?.sessionId;!n||e.has(n)||e.set(n,s)}return e}function Ku(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return qu(t);const e=new Map;for(const[s,n]of Object.entries(t||{}))!s||typeof n!="number"||Number.isNaN(n)||e.set(s,n);return e}function Vu(t){if(t instanceof Map)return t;const e=new Map;if(!Array.isArray(t))return e;for(let s=0;s<t.length;s+=1){const n=t[s];typeof n!="string"||!n||e.has(n)||e.set(n,s)}return e}function ls(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function Yu(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function uo(t,e){return!!(Yu(t)&&e&&e.has(t.sessionId))}function po(t,e){return t.isSystem?0:t.isGroup&&uo(t,e)?1:uo(t,e)?2:t.isGroup?3:4}function mo(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function fo(t,e,s,n,r){const i=po(t,n),a=po(e,n);if(i!==a)return i-a;const l=co(t),c=co(e);if(l!==c)return l-c;if(r&&r.size>0&&ls(t)&&ls(e)){const y=r.has(t.sessionId)?r.get(t.sessionId):1/0,S=r.has(e.sessionId)?r.get(e.sessionId):1/0;if(y!==S)return y-S}const d=s.get(t.sessionId),u=s.get(e.sessionId);if(typeof d=="number"&&typeof u=="number"&&d!==u)return d-u;const p=mo(t),m=mo(e);if(p>0&&m>0&&p!==m)return p-m;const f=(t.createdAt||0)-(e.createdAt||0);if(f!==0)return f;const h=String(t.title||""),g=String(e.title||""),b=h.localeCompare(g);return b!==0?b:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function ot(t=[],e=new Set,s=[],n=null,r=null){const i=new Map,a=new Map,l=Ku(s),c=Vu(r),d=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of t)i.set(g.sessionId,g);const u=[];for(const g of t){if(g.isGroup||!g.groupId||g.parentSessionId)continue;const b=`group:${g.groupId}`;if(i.has(b))continue;const y={sessionId:b,groupId:g.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};i.set(b,y),u.push(y)}const p=new Set(u.map(g=>g.sessionId));u.length>0&&(t=[...t,...u]);for(const g of t){const b=!g.isGroup&&g.groupId&&!g.parentSessionId&&i.has(`group:${g.groupId}`)?`group:${g.groupId}`:null,y=g.parentSessionId||b;!y||!i.has(y)||(a.has(y)||a.set(y,[]),a.get(y).push(g))}for(const g of a.values())g.sort((b,y)=>fo(b,y,l,d,c));const m=t.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,b)=>fo(g,b,l,d,c)),f=[];function h(g,b){const y=a.get(g.sessionId)||[];if(f.push({sessionId:g.sessionId,depth:b,hasChildren:y.length>0,collapsed:e.has(g.sessionId),...p.has(g.sessionId)?{standIn:g}:{}}),!e.has(g.sessionId))for(const S of y)h(S,b+1)}for(const g of m)h(g,0);return f}const ct="VS Code",ms="Retro",Bt="Others",ho=Object.freeze([ct,ms,Bt]);function Xu(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function Vn(t){return Number.parseInt(t,16)/255}function Qu(t){const e=String(t||"").trim();return/^#[0-9a-f]{3}$/iu.test(e)?`#${e.slice(1).split("").map(s=>s+s).join("")}`:/^#[0-9a-f]{6}$/iu.test(e)?e:null}function Yn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Zu(t){const e=Qu(t);if(!e)return 0;const s=Yn(Vn(e.slice(1,3))),n=Yn(Vn(e.slice(3,5))),r=Yn(Vn(e.slice(5,7)));return .2126*s+.7152*n+.0722*r}function Ju(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return Zu(e)>=.5}function Me({id:t,label:e,description:s,group:n=Bt,page:r,terminal:i,tui:a={},icon:l=null}){const c={background:r?.background||i?.background||"#000000",surface:i?.background||r?.background||"#000000",foreground:i?.foreground||r?.foreground||"#ffffff",white:i?.foreground||r?.foreground||"#ffffff",gray:r?.hintColor||i?.brightBlack||i?.white||"#999999",black:i?.black||"#000000",red:i?.red||"#ff5555",green:i?.green||"#55ff55",yellow:i?.yellow||"#ffff55",blue:i?.blue||"#5555ff",magenta:i?.magenta||"#ff55ff",cyan:i?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",otherUserChatLabel:i?.brightMagenta||i?.magenta||"#c9a3ff",activeHighlightBackground:i?.blue||"#5555ff",activeHighlightForeground:i?.background||"#000000",selectionBackground:i?.cursor||i?.blue||"#5555ff",selectionForeground:i?.cursorAccent||i?.background||"#000000",promptCursorBackground:i?.cursor||i?.green||"#55ff55",promptCursorForeground:i?.cursorAccent||i?.background||"#000000"};return Xu({id:t,label:e,description:s,group:n,icon:l||null,page:r,terminal:i,tui:{...c,...a}})}const ep=Me({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:ct,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#30363d",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#0d1117",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),tp=Me({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:ct,page:{background:"#f6f8fa",foreground:"#1f2328",overlayBackground:"#ffffff",overlayForeground:"#1f2328",hintColor:"#57606a",modalBackdrop:"rgba(31, 35, 40, 0.34)",modalBackground:"#ffffff",modalBorder:"#d0d7de",modalForeground:"#1f2328",modalMuted:"#57606a",modalSelectedBackground:"#ddf4ff",modalSelectedBorder:"#0969da",modalSelectedForeground:"#0550ae"},terminal:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"#ddf4ff",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#0f6f78",brightWhite:"#1f2328"},tui:{surface:"#ffffff",border:"#d0d7de",userChat:"#0969da",userChatLabel:"#0550ae",activeHighlightBackground:"#ddf4ff",activeHighlightForeground:"#0550ae",selectionBackground:"#0969da",selectionForeground:"#ffffff",promptCursorBackground:"#0969da",promptCursorForeground:"#ffffff"}}),Hl=Me({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:Bt,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),sp=Me({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:ct,page:{background:"#193549",foreground:"#ffffff",overlayBackground:"#193549",overlayForeground:"#ffffff",hintColor:"#a8c5e6",modalBackdrop:"rgba(7, 17, 28, 0.68)",modalBackground:"#224b68",modalBorder:"#2e6c99",modalForeground:"#ffffff",modalMuted:"#a8c5e6",modalSelectedBackground:"#ffc600",modalSelectedBorder:"#ffc600",modalSelectedForeground:"#193549"},terminal:{background:"#193549",foreground:"#ffffff",cursor:"#ffc600",cursorAccent:"#193549",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#ff628c",green:"#3ad900",yellow:"#ff9d00",blue:"#0088ff",magenta:"#ff628c",cyan:"#80ffbb",white:"#ffffff",brightBlack:"#666666",brightRed:"#ff628c",brightGreen:"#3ad900",brightYellow:"#ff9d00",brightBlue:"#0088ff",brightMagenta:"#ff9d00",brightCyan:"#80ffbb",brightWhite:"#ffffff"},tui:{surface:"#193549",activeHighlightBackground:"#0f5f91",activeHighlightForeground:"#ffffff",selectionBackground:"#ffc600",selectionForeground:"#193549",promptCursorBackground:"#ffc600",promptCursorForeground:"#193549"}}),np=Me({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:ct,page:{background:"#282a36",foreground:"#f8f8f2",overlayBackground:"#282a36",overlayForeground:"#f8f8f2",hintColor:"#bd93f9",modalBackdrop:"rgba(24, 25, 33, 0.72)",modalBackground:"#313442",modalBorder:"#6272a4",modalForeground:"#f8f8f2",modalMuted:"#bd93f9",modalSelectedBackground:"#44475a",modalSelectedBorder:"#bd93f9",modalSelectedForeground:"#f8f8f2"},terminal:{background:"#282a36",foreground:"#f8f8f2",cursor:"#f8f8f2",cursorAccent:"#282a36",selectionBackground:"rgba(189, 147, 249, 0.24)",black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff6e6e",brightGreen:"#69ff94",brightYellow:"#ffffa5",brightBlue:"#d6acff",brightMagenta:"#ff92df",brightCyan:"#a4ffff",brightWhite:"#ffffff"},tui:{surface:"#282a36",activeHighlightBackground:"#44475a",activeHighlightForeground:"#f8f8f2",selectionBackground:"#bd93f9",selectionForeground:"#282a36",promptCursorBackground:"#f8f8f2",promptCursorForeground:"#282a36"}}),rp=Me({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:ct,page:{background:"#1e1e2e",foreground:"#cdd6f4",overlayBackground:"#1e1e2e",overlayForeground:"#cdd6f4",hintColor:"#bac2de",modalBackdrop:"rgba(17, 17, 27, 0.74)",modalBackground:"#313244",modalBorder:"#585b70",modalForeground:"#cdd6f4",modalMuted:"#bac2de",modalSelectedBackground:"#45475a",modalSelectedBorder:"#89b4fa",modalSelectedForeground:"#cdd6f4"},terminal:{background:"#1e1e2e",foreground:"#cdd6f4",cursor:"#f5e0dc",cursorAccent:"#1e1e2e",selectionBackground:"rgba(137, 180, 250, 0.22)",black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#585b70",brightRed:"#f38ba8",brightGreen:"#a6e3a1",brightYellow:"#f9e2af",brightBlue:"#89b4fa",brightMagenta:"#f5c2e7",brightCyan:"#94e2d5",brightWhite:"#f5e0dc"},tui:{surface:"#1e1e2e",activeHighlightBackground:"#45475a",activeHighlightForeground:"#cdd6f4",selectionBackground:"#89b4fa",selectionForeground:"#1e1e2e",promptCursorBackground:"#f5e0dc",promptCursorForeground:"#1e1e2e"}}),ip=Me({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:ct,page:{background:"#030603",foreground:"#c8ffc8",overlayBackground:"#030603",overlayForeground:"#c8ffc8",hintColor:"#59a659",modalBackdrop:"rgba(0, 6, 0, 0.82)",modalBackground:"#081208",modalBorder:"#1f5f1f",modalForeground:"#d6ffd6",modalMuted:"#6dbb6d",modalSelectedBackground:"#0f240f",modalSelectedBorder:"#39ff14",modalSelectedForeground:"#dfffdf"},terminal:{background:"#000000",foreground:"#c8ffc8",cursor:"#39ff14",cursorAccent:"#000000",selectionBackground:"rgba(57, 255, 20, 0.2)",black:"#031003",red:"#39ff14",green:"#2a7a22",yellow:"#4a8a30",blue:"#1a6a4a",magenta:"#2a7a3a",cyan:"#2a8a5a",white:"#b7f7b7",brightBlack:"#59a659",brightRed:"#9aff86",brightGreen:"#7dff66",brightYellow:"#e0ff8a",brightBlue:"#61ffc2",brightMagenta:"#b4ffb4",brightCyan:"#98ffe0",brightWhite:"#e8ffe8"},tui:{surface:"#030603",activeHighlightBackground:"#1a3a1a",activeHighlightForeground:"#e8ffe8",selectionBackground:"#39ff14",selectionForeground:"#000000",promptCursorBackground:"#39ff14",promptCursorForeground:"#000000"}}),op=Me({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:ct,page:{background:"#0a0f1e",foreground:"#e8f2ff",overlayBackground:"#0a0f1e",overlayForeground:"#e8f2ff",hintColor:"#7e90b5",modalBackdrop:"rgba(6, 10, 24, 0.76)",modalBackground:"#121a30",modalBorder:"#2d4a73",modalForeground:"#edf5ff",modalMuted:"#93a7cc",modalSelectedBackground:"#19365f",modalSelectedBorder:"#55c2ff",modalSelectedForeground:"#f3fbff"},terminal:{background:"#0a0f1e",foreground:"#e8f2ff",cursor:"#55c2ff",cursorAccent:"#0a0f1e",selectionBackground:"rgba(85, 194, 255, 0.22)",black:"#10182b",red:"#ff6b88",green:"#67f5c2",yellow:"#ffd36b",blue:"#55c2ff",magenta:"#c79bff",cyan:"#7ceeff",white:"#c3d4ef",brightBlack:"#7e90b5",brightRed:"#ff8aa2",brightGreen:"#8cffd8",brightYellow:"#ffe28f",brightBlue:"#8fdcff",brightMagenta:"#d8b6ff",brightCyan:"#a2f5ff",brightWhite:"#ffffff"},tui:{surface:"#0c1325",activeHighlightBackground:"#173052",activeHighlightForeground:"#f3fbff",selectionBackground:"#55c2ff",selectionForeground:"#0a0f1e",promptCursorBackground:"#55c2ff",promptCursorForeground:"#0a0f1e"}}),ap=Me({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:ct,page:{background:"#282828",foreground:"#ebdbb2",overlayBackground:"#282828",overlayForeground:"#ebdbb2",hintColor:"#a89984",modalBackdrop:"rgba(40, 40, 40, 0.74)",modalBackground:"#3c3836",modalBorder:"#504945",modalForeground:"#ebdbb2",modalMuted:"#a89984",modalSelectedBackground:"#504945",modalSelectedBorder:"#fabd2f",modalSelectedForeground:"#fbf1c7"},terminal:{background:"#282828",foreground:"#ebdbb2",cursor:"#ebdbb2",cursorAccent:"#282828",selectionBackground:"rgba(250, 189, 47, 0.22)",black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},tui:{surface:"#282828",activeHighlightBackground:"#504945",activeHighlightForeground:"#fbf1c7",selectionBackground:"#fabd2f",selectionForeground:"#282828",promptCursorBackground:"#ebdbb2",promptCursorForeground:"#282828"}}),lp=Me({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:ct,page:{background:"#052529",foreground:"#b2cacd",overlayBackground:"#052529",overlayForeground:"#b2cacd",hintColor:"#40d4e7",modalBackdrop:"rgba(3, 25, 27, 0.72)",modalBackground:"#073940",modalBorder:"#0e6671",modalForeground:"#b2cacd",modalMuted:"#87a7ab",modalSelectedBackground:"#0b515b",modalSelectedBorder:"#40d4e7",modalSelectedForeground:"#ebfdff"},terminal:{background:"#03191b",foreground:"#b2cacd",cursor:"#85efff",cursorAccent:"#03191b",selectionBackground:"rgba(22, 159, 177, 0.27)",black:"#324a4d",red:"#e66533",green:"#49e9a6",yellow:"#e4b781",blue:"#49ace9",magenta:"#df769b",cyan:"#49d6e9",white:"#b2cacd",brightBlack:"#5e878c",brightRed:"#e97749",brightGreen:"#60ebb1",brightYellow:"#e69533",brightBlue:"#60b6eb",brightMagenta:"#e798b3",brightCyan:"#60dbeb",brightWhite:"#c1d4d7"},tui:{surface:"#03191b",activeHighlightBackground:"#083d44",activeHighlightForeground:"#ebfdff",selectionBackground:"#169fb1",selectionForeground:"#052529",promptCursorBackground:"#85efff",promptCursorForeground:"#03191b"}}),cp=Me({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:ct,page:{background:"#0b1117",foreground:"#c7d1da",overlayBackground:"#0b1117",overlayForeground:"#c7d1da",hintColor:"#7cc6ff",modalBackdrop:"rgba(5, 9, 13, 0.74)",modalBackground:"#121a23",modalBorder:"#28455b",modalForeground:"#d7e2eb",modalMuted:"#8f9dab",modalSelectedBackground:"#173041",modalSelectedBorder:"#7cc6ff",modalSelectedForeground:"#eef6ff"},terminal:{background:"#060b10",foreground:"#c7d1da",cursor:"#9fd4ff",cursorAccent:"#060b10",selectionBackground:"rgba(72, 125, 170, 0.30)",black:"#2a3138",red:"#ef6b73",green:"#7ddc8f",yellow:"#d9b36c",blue:"#68aee8",magenta:"#b28cff",cyan:"#58c9d4",white:"#c7d1da",brightBlack:"#6e7a86",brightRed:"#f28a92",brightGreen:"#97e5a6",brightYellow:"#e4c28b",brightBlue:"#86c1f1",brightMagenta:"#c6a7ff",brightCyan:"#7ad7df",brightWhite:"#e5edf5"},tui:{surface:"#060b10",activeHighlightBackground:"#123142",activeHighlightForeground:"#eef6ff",selectionBackground:"#4a7baa",selectionForeground:"#0b1117",promptCursorBackground:"#9fd4ff",promptCursorForeground:"#060b10"}}),dp=Me({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:ms,page:{background:"#020503",foreground:"#c9f7d3",overlayBackground:"#020503",overlayForeground:"#d9ffe0",hintColor:"#7ee787",modalBackdrop:"rgba(0, 6, 2, 0.82)",modalBackground:"#061109",modalBorder:"#245c33",modalForeground:"#d9ffe0",modalMuted:"#83a98c",modalSelectedBackground:"#0b2a14",modalSelectedBorder:"#63e27a",modalSelectedForeground:"#ecfff0"},terminal:{background:"#020503",foreground:"#c9f7d3",cursor:"#8cff9f",cursorAccent:"#020503",selectionBackground:"#174923",black:"#061109",red:"#ff5f5f",green:"#63e27a",yellow:"#d6b95f",blue:"#5aa7ff",magenta:"#c586ff",cyan:"#5ce1d8",white:"#c9f7d3",brightBlack:"#5b7a61",brightRed:"#ff7f7f",brightGreen:"#8cff9f",brightYellow:"#f0d982",brightBlue:"#82bdff",brightMagenta:"#d9a8ff",brightCyan:"#89f4ee",brightWhite:"#effff1"},tui:{surface:"#020503",border:"#245c33",userChat:"#f0d982",userChatLabel:"#fff0a8",activeHighlightBackground:"#0b2a14",activeHighlightForeground:"#ecfff0",selectionBackground:"#63e27a",selectionForeground:"#020503",promptCursorBackground:"#8cff9f",promptCursorForeground:"#020503"}}),up=Me({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:Bt,page:{background:"#000000",foreground:"#f8f8f2",overlayBackground:"#050505",overlayForeground:"#ffffff",hintColor:"#b8b8b8",modalBackdrop:"rgba(0, 0, 0, 0.88)",modalBackground:"#050505",modalBorder:"#d8d8d8",modalForeground:"#ffffff",modalMuted:"#b8b8b8",modalSelectedBackground:"#003f88",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#f8f8f2",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"#003f88",black:"#000000",red:"#ff4d4d",green:"#00d084",yellow:"#ffd84d",blue:"#4da3ff",magenta:"#d8d8d8",cyan:"#ffffff",white:"#f8f8f2",brightBlack:"#8a8a8a",brightRed:"#ff6b6b",brightGreen:"#28e29a",brightYellow:"#ffe173",brightBlue:"#73b8ff",brightMagenta:"#ffffff",brightCyan:"#ffffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#d8d8d8",userChat:"#ffffff",userChatLabel:"#d8d8d8",activeHighlightBackground:"#003f88",activeHighlightForeground:"#ffffff",selectionBackground:"#ffffff",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),pp=Me({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:ms,page:{background:"#008080",foreground:"#000000",overlayBackground:"#c0c0c0",overlayForeground:"#000000",hintColor:"#4a4a4a",modalBackdrop:"rgba(0, 0, 0, 0.45)",modalBackground:"#c0c0c0",modalBorder:"#808080",modalForeground:"#000000",modalMuted:"#5a5a5a",modalSelectedBackground:"#000080",modalSelectedBorder:"#000080",modalSelectedForeground:"#ffffff"},terminal:{background:"#c0c0c0",foreground:"#000000",cursor:"#000080",cursorAccent:"#c0c0c0",selectionBackground:"#000080",black:"#000000",red:"#800000",green:"#008000",yellow:"#808000",blue:"#000080",magenta:"#800080",cyan:"#008080",white:"#c0c0c0",brightBlack:"#5a5a5a",brightRed:"#c00000",brightGreen:"#006000",brightYellow:"#7a5c00",brightBlue:"#0000c0",brightMagenta:"#a000a0",brightCyan:"#006a6a",brightWhite:"#000000"},tui:{surface:"#c0c0c0",border:"#808080",userChat:"#000080",userChatLabel:"#000080",activeHighlightBackground:"#000080",activeHighlightForeground:"#ffffff",selectionBackground:"#000080",selectionForeground:"#ffffff",promptCursorBackground:"#000080",promptCursorForeground:"#ffffff"}}),mp=Me({id:"ms-dos",label:"MS-DOS 2.0",description:"CGA light-grey on black, the 16-colour CGA palette with brown, and CP437 box framing.",group:ms,page:{background:"#000000",foreground:"#aaaaaa",overlayBackground:"#000000",overlayForeground:"#aaaaaa",hintColor:"#8f8f8f",modalBackdrop:"rgba(0, 0, 0, 0.78)",modalBackground:"#000000",modalBorder:"#aaaaaa",modalForeground:"#aaaaaa",modalMuted:"#8f8f8f",modalSelectedBackground:"#aaaaaa",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#000000"},terminal:{background:"#000000",foreground:"#aaaaaa",cursor:"#aaaaaa",cursorAccent:"#000000",selectionBackground:"#aaaaaa",black:"#000000",red:"#aa0000",green:"#00aa00",yellow:"#aa5500",blue:"#0000aa",magenta:"#aa00aa",cyan:"#00aaaa",white:"#aaaaaa",brightBlack:"#8f8f8f",brightRed:"#ff5555",brightGreen:"#55ff55",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#aaaaaa",userChat:"#ffffff",userChatLabel:"#ffffff",activeHighlightBackground:"#aaaaaa",activeHighlightForeground:"#000000",selectionBackground:"#aaaaaa",selectionForeground:"#000000",promptCursorBackground:"#aaaaaa",promptCursorForeground:"#000000"}}),fp=Me({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:ms,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#2a1d14"},{d:"M6 7h20v20H6z",fill:"#c89a6a"},{d:"M5 6h22v6H5z",fill:"#4a2f1a"},{d:"M9 15h5v3.4H9z",fill:"#1a1008"},{d:"M18 15h5v3.4h-5z",fill:"#1a1008"},{d:"M8.6 13.6l6 1 -.3 1.7-6-1z",fill:"#3a2412"},{d:"M23.4 13.6l-6 1 .3 1.7 6-1z",fill:"#3a2412"},{d:"M14.5 18.5h3v2.4h-3z",fill:"#a8734a"},{d:"M11 22h10v1.8H11z",fill:"#7a3a2a"}]},page:{background:"#100b09",foreground:"#d9cba8",overlayBackground:"#1c1310",overlayForeground:"#d9cba8",hintColor:"#a08d68",modalBackdrop:"rgba(16, 11, 9, 0.82)",modalBackground:"#1c1310",modalBorder:"#6f5432",modalForeground:"#d9cba8",modalMuted:"#a08d68",modalSelectedBackground:"#6f5432",modalSelectedBorder:"#a4885c",modalSelectedForeground:"#fff4d6"},terminal:{background:"#100b09",foreground:"#d9cba8",cursor:"#b81c1c",cursorAccent:"#100b09",selectionBackground:"#6f5432",black:"#100b09",red:"#c42222",green:"#3f9e3f",yellow:"#e8c020",blue:"#3a5ce0",magenta:"#a0446a",cyan:"#4a8f8f",white:"#d9cba8",brightBlack:"#a08d68",brightRed:"#ff3a1e",brightGreen:"#5fc45f",brightYellow:"#ffd84a",brightBlue:"#5a7ae8",brightMagenta:"#c46a94",brightCyan:"#6fb5b5",brightWhite:"#fff4d6"},tui:{border:"#6f5432",userChat:"#e8c020",userChatLabel:"#ffd84a",selectionBackground:"#6f5432",selectionForeground:"#fff4d6",activeHighlightBackground:"#6f5432",activeHighlightForeground:"#fff4d6",promptCursorBackground:"#b81c1c",promptCursorForeground:"#fff4d6"}}),hp=Me({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:ms,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#000000"},{d:"M3 17h4v11H3z",fill:"#00e337"},{d:"M9 11h4v17H9z",fill:"#7ad91e"},{d:"M15 6h4v22h-4z",fill:"#b6e000"},{d:"M21 13h4v15h-4z",fill:"#ffb400"},{d:"M27 20h3v8h-3z",fill:"#ff3b00"},{d:"M3 15h4v1.6H3z",fill:"#d6d6cc"},{d:"M9 9h4v1.6H9z",fill:"#d6d6cc"},{d:"M15 4h4v1.6h-4z",fill:"#d6d6cc"},{d:"M21 11h4v1.6h-4z",fill:"#d6d6cc"},{d:"M27 18h3v1.6h-3z",fill:"#d6d6cc"}]},page:{background:"#000000",foreground:"#00e337",overlayBackground:"#1c1c1c",overlayForeground:"#00e337",hintColor:"#949494",modalBackdrop:"rgba(0, 0, 0, 0.82)",modalBackground:"#1c1c1c",modalBorder:"#5e5e5e",modalForeground:"#00e337",modalMuted:"#a0a0a0",modalSelectedBackground:"#0000c6",modalSelectedBorder:"#5e5e5e",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#00e337",cursor:"#ffb400",cursorAccent:"#000000",selectionBackground:"#0000c6",black:"#000000",red:"#ff3b00",green:"#00e337",yellow:"#ffb400",blue:"#4a7cf0",magenta:"#cc66cc",cyan:"#29c8c8",white:"#d6d6cc",brightBlack:"#949494",brightRed:"#ff6a3d",brightGreen:"#5cff7a",brightYellow:"#ffd24a",brightBlue:"#7fa5ff",brightMagenta:"#e08ae0",brightCyan:"#6fe0e0",brightWhite:"#ffffff"},tui:{border:"#5e5e5e",gray:"#949494",userChat:"#ffb400",userChatLabel:"#ffd24a",selectionBackground:"#0000c6",selectionForeground:"#ffffff",activeHighlightBackground:"#0000c6",activeHighlightForeground:"#ffffff",promptCursorBackground:"#ffb400",promptCursorForeground:"#000000"}}),gp=Me({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:Bt,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#241f1c"},{d:"M11.5 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M19 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M10.5 6h3.5v3.5h-3.5z",fill:"#ffe9dd"},{d:"M18 6h3.5v3.5H18z",fill:"#ffe9dd"},{d:"M11.5 7h1.5v1.5h-1.5z",fill:"#1a1210"},{d:"M19 7h1.5v1.5H19z",fill:"#1a1210"},{d:"M10 11.5h12v2H10z",fill:"#ff7a3d"},{d:"M7 13.5h18v3H7z",fill:"#f74c00"},{d:"M5 16.5h22v4H5z",fill:"#f74c00"},{d:"M7 20.5h18v1.8H7z",fill:"#f74c00"},{d:"M14.5 18h3v1.4h-3z",fill:"#c23c00"},{d:"M0 11h4.5v6.5H0z",fill:"#d63a00"},{d:"M0 13.2h3v2H0z",fill:"#241f1c"},{d:"M27.5 11h4.5v6.5h-4.5z",fill:"#d63a00"},{d:"M29 13.2h3v2h-3z",fill:"#241f1c"},{d:"M8.5 22.3h2.5v2.4H8.5z",fill:"#d63a00"},{d:"M14.75 22.3h2.5v2.4h-2.5z",fill:"#d63a00"},{d:"M21 22.3h2.5v2.4H21z",fill:"#d63a00"}]},page:{background:"#1c1917",foreground:"#e7e0d8",overlayBackground:"#262220",overlayForeground:"#e7e0d8",hintColor:"#a39a8f",modalBackdrop:"rgba(28, 25, 23, 0.82)",modalBackground:"#262220",modalBorder:"#4a4038",modalForeground:"#e7e0d8",modalMuted:"#a9a096",modalSelectedBackground:"#7c2d12",modalSelectedBorder:"#ce422b",modalSelectedForeground:"#ffeadf"},terminal:{background:"#1c1917",foreground:"#e7e0d8",cursor:"#f74c00",cursorAccent:"#1c1917",selectionBackground:"#7c2d12",black:"#1c1917",red:"#f3554a",green:"#6cc24a",yellow:"#e5b02b",blue:"#58a6ff",magenta:"#c98bdf",cyan:"#f74c00",white:"#e7e0d8",brightBlack:"#a39a8f",brightRed:"#ff7b70",brightGreen:"#8fdd6e",brightYellow:"#ffcc55",brightBlue:"#83c0ff",brightMagenta:"#dcaaef",brightCyan:"#ff7a3d",brightWhite:"#fdf6ee"},tui:{border:"#4a4038",userChat:"#ffb454",userChatLabel:"#ffd08a",selectionBackground:"#7c2d12",selectionForeground:"#ffeadf",activeHighlightBackground:"#7c2d12",activeHighlightForeground:"#ffeadf",promptCursorBackground:"#f74c00",promptCursorForeground:"#1c1917"}}),yp="#a35838",bp="M4.14 33.09L4.14 18.89L5.7 15.77L30.05 1.4L33.95 1.4L43.32 6.56L57.99 15.3L59.08 16.7L59.71 18.58L59.71 45.27L59.08 47.14L56.9 49.64L41.44 58.38L38.32 60.57L33.64 62.91L30.52 62.91L27.71 61.66L14.6 53.7L6.79 49.48L5.54 48.23L4.45 46.2L4.14 44.49L4.14 33.09ZM55.8 26.07L55.8 19.36L55.02 18.42L33.8 6.09L31.45 5.78L30.05 6.24L8.51 18.89L8.51 45.11L10.22 46.67L18.03 50.89L30.05 58.22L31.77 58.85L33.17 58.69L53.93 46.67L55.65 44.96L55.8 26.07ZM17.09 34.81L16.78 33.56L13.19 32.62L13.19 27.0L17.09 26.54L18.97 23.26L16.94 19.67L21.0 15.61L24.43 17.95L27.86 16.86L29.11 12.8L34.58 12.8L35.51 16.86L38.63 17.95L39.57 17.8L42.69 15.61L46.6 19.67L46.28 20.92L44.88 22.95L44.88 23.73L46.28 26.38L50.65 27.16L50.65 32.47L47.69 33.4L47.06 34.03L42.54 32.0L42.54 29.97L41.91 27.63L40.82 25.6L38.63 23.26L34.73 21.39L32.55 21.07L29.11 21.39L26.3 22.48L23.96 24.35L22.4 26.54L21.31 29.97L21.31 33.25L22.87 37.46L24.12 39.18L27.4 41.83L24.59 42.77L19.9 42.93L16.0 41.68L15.22 40.12L17.72 37.31L17.09 34.81ZM36.76 35.59L35.51 32.62L35.82 32.0L50.19 39.34L49.25 41.99L43.32 51.2L42.54 51.04L41.6 46.2L35.51 49.64L31.3 50.58L28.49 50.58L21.93 49.01L18.97 47.3L16.47 45.11L16.78 44.8L19.12 45.58L22.09 45.74L25.21 45.42L28.18 44.33L29.74 44.49L33.48 42.46L37.39 39.18L37.85 37.93L36.76 35.59Z",Sp=Me({id:"duroxide",label:"Duroxide",description:"Iron oxide pressed into black felt - the durable-execution runtime's own mark, traced from the banner.",group:Bt,icon:{viewBox:"0 0 64 64",paths:[{d:bp,fill:yp}]},page:{background:"#201e1f",foreground:"#e5e0dc",overlayBackground:"#2e2c2d",overlayForeground:"#e5e0dc",hintColor:"#a89f99",modalBackdrop:"rgba(23, 21, 23, 0.86)",modalBackground:"#2e2c2d",modalBorder:"#4d4643",modalForeground:"#e5e0dc",modalMuted:"#a89f99",modalSelectedBackground:"#7c3f26",modalSelectedBorder:"#a35838",modalSelectedForeground:"#ffeee4"},terminal:{background:"#282627",foreground:"#e5e0dc",cursor:"#d2764a",cursorAccent:"#201e1f",selectionBackground:"#7c3f26",black:"#201e1f",red:"#e86a5f",green:"#7fb069",yellow:"#d9a441",blue:"#6a9fd4",magenta:"#b98bc4",cyan:"#d2764a",white:"#e5e0dc",brightBlack:"#a89f99",brightRed:"#f4897f",brightGreen:"#9bc888",brightYellow:"#efc069",brightBlue:"#8fbce4",brightMagenta:"#d0a8d9",brightCyan:"#ba714c",brightWhite:"#fdf7f2"},tui:{border:"#6a615b",userChat:"#e0b070",userChatLabel:"#f0cf9a",selectionBackground:"#7c3f26",selectionForeground:"#ffeee4",activeHighlightBackground:"#7c3f26",activeHighlightForeground:"#ffeee4",promptCursorBackground:"#d2764a",promptCursorForeground:"#201e1f"}}),vp=Me({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:Bt,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#1a7fa8"},{d:"M7 2h18a3 3 0 0 1 3 3v15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V5a3 3 0 0 1 3-3z",fill:"#ffe01b"},{d:"M6.2 6.4a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0z",fill:"#e3c00c"},{d:"M23.4 4.8a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0z",fill:"#e3c00c"},{d:"M5.4 18.2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0z",fill:"#e3c00c"},{d:"M24 19a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0z",fill:"#e3c00c"},{d:"M7.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M16.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M9.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M18.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M10.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M19.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M10 16.6c2 3.6 10 3.6 12 0c-1.2 5-10.8 5-12 0z",fill:"#6b4e00"},{d:"M14 17.6h1.9v2.1H14z",fill:"#ffffff"},{d:"M16.1 17.6H18v2.1h-1.9z",fill:"#ffffff"},{d:"M6 23h20v3H6z",fill:"#ffffff"},{d:"M14.4 24.6h3.2v2h-3.2z",fill:"#d2232a"},{d:"M13 26.4h6l-3 5.2z",fill:"#d2232a"}]},page:{background:"#07293c",foreground:"#e6f4fb",overlayBackground:"#0e3852",overlayForeground:"#e6f4fb",hintColor:"#8fb9cf",modalBackdrop:"rgba(7, 41, 60, 0.84)",modalBackground:"#0e3852",modalBorder:"#1d6a8c",modalForeground:"#e6f4fb",modalMuted:"#95bed3",modalSelectedBackground:"#ffe01b",modalSelectedBorder:"#fff08a",modalSelectedForeground:"#07293c"},terminal:{background:"#07293c",foreground:"#e6f4fb",cursor:"#ffe01b",cursorAccent:"#07293c",selectionBackground:"#ffe01b",black:"#07293c",red:"#ff6152",green:"#7ed957",yellow:"#ffa62b",blue:"#7fd4c1",magenta:"#ff9bd2",cyan:"#ffe01b",white:"#e6f4fb",brightBlack:"#8fb9cf",brightRed:"#ff9084",brightGreen:"#a5e888",brightYellow:"#ffc46b",brightBlue:"#a8e5d8",brightMagenta:"#ffbde1",brightCyan:"#fff08a",brightWhite:"#ffffff"},tui:{border:"#1d6a8c",userChat:"#ffa62b",userChatLabel:"#ffc46b",selectionBackground:"#ffe01b",selectionForeground:"#07293c",activeHighlightBackground:"#ffe01b",activeHighlightForeground:"#07293c",promptCursorBackground:"#ffe01b",promptCursorForeground:"#07293c"}});function wp(t,e){const s=ho.indexOf(t.group),n=ho.indexOf(e.group),r=s===-1?Number.MAX_SAFE_INTEGER:s,i=n===-1?Number.MAX_SAFE_INTEGER:n;return r!==i?r-i:t.label.localeCompare(e.label,void 0,{sensitivity:"base"})}const Ul=Object.freeze([Hl,np,ep,tp,sp,op,ip,rp,ap,lp,cp,dp,up,pp,mp,fp,hp,gp,Sp,vp].sort(wp)),Ep=new Map(Ul.map(t=>[t.id,t])),kp=Hl.id;function xp(){return Ul}function ft(t){return t?Ep.get(t)??null:null}const Ip=new Set(["agent","user","system"]);function an(t){const e=Array.isArray(t?.ownerKeys)?[...new Set(t.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:t&&typeof t=="object"?t?.all===!0:!0,includeSystem:t?.includeSystem===!0,includeUnowned:t?.includeUnowned===!0,includeMe:t?.includeMe===!0,includeShared:t?.includeShared===!0,ownerKeys:e}}function Ap(t){if(typeof t=="string"){const r=t.trim();return r?{filename:r,sizeBytes:null,contentType:"",isBinary:!1,uploadedAt:"",source:"agent"}:null}if(!t||typeof t!="object")return null;const e=String(t.filename||"").trim();if(!e)return null;const s=Number(t.sizeBytes),n=typeof t.contentType=="string"?t.contentType:"";return{filename:e,sizeBytes:Number.isFinite(s)&&s>=0?s:null,contentType:n,isBinary:t.isBinary===!0,uploadedAt:typeof t.uploadedAt=="string"?t.uploadedAt:"",source:Ip.has(t.source)?t.source:"agent"}}function ln(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const r of e){const i=Ap(r);!i||n.has(i.filename)||(n.add(i.filename),s.push(i))}return s}function Np(t,e){const s=String(e||"").trim();return s&&ln(t).find(n=>n.filename===s)||null}function ei(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),r=Number(e.portalSessionColumnAdjust),i=Number(e.activityPaneAdjust),a=Number(e.canvasPaneAdjust),l=Number(e.diagnosticsPaneAdjust),c=Number(e.diagnosticsSplitAdjust);return{paneAdjust:Number.isFinite(s)?Math.trunc(s):0,sessionPaneAdjust:Number.isFinite(n)?Math.trunc(n):0,portalSessionColumnAdjust:Number.isFinite(r)?Math.trunc(r):0,activityPaneAdjust:Number.isFinite(i)?Math.trunc(i):0,canvasPaneAdjust:Number.isFinite(a)?Math.trunc(a):0,diagnosticsPaneAdjust:Number.isFinite(l)?Math.trunc(l):0,diagnosticsSplitAdjust:Number.isFinite(c)?Math.trunc(c):0}}function cn(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s}function ti(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s}function Ir(t){if(!Array.isArray(t))return new Set;const e=new Set;for(const s of t){const n=String(s||"").trim();n&&e.add(n)}return e}function Cp(t){return t==="canvas"?"canvas":"panes"}function jl(t,e){const s=t&&typeof t=="object"?t:null;return s&&(typeof s.canvasOpen=="boolean"||typeof s.diagnosticsOpen=="boolean")?{canvasOpen:s.canvasOpen===!0,diagnosticsOpen:s.diagnosticsOpen===!0,zen:s.zen===!0&&s.canvasOpen===!0}:{canvasOpen:e==="canvas",diagnosticsOpen:!1,zen:!1}}function Ze(t,e){const s=String(t||""),n=Number(e);return Number.isInteger(n)&&n>=2&&n<=5?`${s}#${n}`:s}function Tp(t){const e=/^(.*)#([2-5])$/.exec(String(t||""));return e?{sessionId:e[1],slot:Number(e[2])}:{sessionId:String(t||""),slot:1}}function si(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[s,n]of Object.entries(t)){const r=String(s||"").trim();if(!r||!n||typeof n!="object")continue;const i=Number(n.lastViewedRev),a=Number(n.lastViewedDataRev),l=Number(n.zenRailPx);e[r]={optedOut:n.optedOut===!0,lastViewedRev:Number.isFinite(i)&&i>0?Math.floor(i):0,lastViewedDataRev:Number.isFinite(a)&&a>0?Math.floor(a):0,...Number.isFinite(l)&&l>0?{zenRailPx:Math.floor(l)}:{}}}return e}function Gl(t){if(t==null)return null;const e=String(t).trim();return e||null}const Pp=Object.freeze(["limit","allowance","hold","no_provider"]);function cs(t){const e=t?.pauseState;if(!e||typeof e!="object")return null;const s=String(e.kind||"");if(!Pp.includes(s))return null;const n=i=>{const a=String(i??"").trim();return a||null},r=i=>Number.isFinite(Number(i))?Number(i):null;return{kind:s,provider:n(e.provider),period:["day","week","month"].includes(String(e.period))?String(e.period):null,modelQualified:n(e.modelQualified),limitTokens:r(e.limitTokens),usedTokens:r(e.usedTokens),ceilingTokens:r(e.ceilingTokens),yourUsedTokens:r(e.yourUsedTokens),resetsAtUtc:n(e.resetsAtUtc)}}const Mp=Object.freeze(["day","week","month"]),dn=Object.freeze([14,30,90]),Ie=14;function Ar({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,sessionOwnerFilter:r=null,layoutAdjustments:i=null,pinnedSessionIds:a=null,collapsedSessionIds:l=null,activeSessionId:c=null,sessionOrder:d=null,rightPaneMode:u=null,desktopPanes:p=null,canvasPrefs:m=null}={}){const f=jl(p,Cp(u)),h=r!=null,g=l!=null,b=ei(i);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},docs:{agentPackageGuideUrl:s?.agentPackageGuideUrl||"https://github.com/affandar/PilotSwarm/blob/main/docs/building-agent-packages.md"},auth:{principal:null,authorization:null},ui:{focusRegion:$.SESSIONS,budgetOpen:!1,inspectorTab:lt[0],nodeMapSelectedNode:null,sequenceExpandedTurns:[],sequenceSelectedTurn:null,rightPaneMode:f.canvasOpen?"canvas":"panes",canvasOpen:f.canvasOpen,diagnosticsOpen:f.diagnosticsOpen,canvasZen:f.zen,canvasMaximized:!1,statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:ft(n)?.id||kp,touchScale:!1,sessionDetailCollapsed:!0,agentPickerUsage:{},modal:null,fullscreenPane:null,layout:{...b,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},groupRows:[],flat:[],activeSessionId:Gl(c),collapsedIds:Ir(l),collapsedIdsExplicit:g,pinnedIds:cn(a),manualOrder:ti(d),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:h,ownerFilter:an(r),navigationIntent:null,filterExceptionId:null},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,markedIds:[],previewOrigin:null,restoreArtifactId:null,paneOpen:!1,paneRestoresToHidden:!1,htmlViewMode:"rendered",htmlZoom:1,htmlFitWidth:!1,filter:{scope:"selectedSession",query:""}},canvas:{bySessionId:{},prefs:si(m),flipSeq:0},logs:{available:!1,availabilityReason:"Log tailing disabled: no K8S_CONTEXT configured in the env file.",tailing:!1,entries:[],filter:{source:"allNodes",level:"all",format:"pretty"}},sessionStats:{bySessionId:{}},fleetStats:{loading:!1,data:null,userStats:null,fetchedAt:0},budget:{tab:"providers",summary:{loading:!1,error:null,fetchedAt:0,days:14,preset:"all",providers:[],data:null},loading:!1,refreshing:!1,loaded:!1,error:null,fetchedAt:0,grid:[],overall:!1,rangeDays:Ie,selectedProvider:null,selectedScope:"*",missingProvider:null,series:{provider:null,scope:"*",rangeDays:Ie,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:Ie,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0},paused:[],pausedError:null},admin:{visible:!1,loading:!1,loadError:null,profile:null,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:0,storeAsSystem:!1},systemGhcpKey:{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},modelProviders:{loading:!1,error:null,page:"mine",providers:[],models:[],defaults:null,fetchedAt:0,mutation:{pending:null,error:null},selection:{focus:"providers",providerName:null,agentId:null},create:{editing:!1,stage:"name",name:"",typeId:"",shared:!1,draft:"",cursorIndex:0,saving:!1,error:null}},section:"providers",packages:{loading:!1,error:null,list:[],workerState:[],fetchedAt:0,selectedName:null,detail:null,detailLoading:!1,detailError:null,changelog:null,workspace:{tree:null,treeLoading:!1,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null},action:{pending:null,error:null},addDialog:{open:!1,kind:"repo",scope:"user",updateName:null,repoUrl:"",ref:"",path:"",url:"",authToken:"",submitting:!1,progress:null,error:null}},workers:{loading:!1,error:null,list:[],fetchedAt:0,attempts:0,lastAttemptAt:0,lastSkip:null}}}}function Wl(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function _p(t,e){return!(!Wl(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const zl="activeHighlightBackground",ni="activeHighlightForeground";function Rp(t){return t==="anthropic-wif"}const Xn="userChat",$p="userChatLabel",Lp="otherUserChatLabel",go=new WeakMap,yo=new WeakMap;function Op(t){return t||ni}function ql(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Op(s?.color):ni,backgroundColor:zl,bold:s?.bold??!0}))}function dt(t,{color:e=ni,bold:s=!0}={}){return{text:t,color:e,backgroundColor:zl,bold:s}}function at(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Fp=72;function Kl(t){const e=Number(t)||0;return e>0&&e<=Fp}function Vl(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return s&&cs(t)?"budget_paused":t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}const bo={day:"daily",week:"weekly",month:"monthly"};function Yl(t){if(!t)return"paused";switch(t.kind){case"no_provider":return"no provider";case"hold":return"paused · hold";case"allowance":return"paused · allowance";default:return"paused · limit"}}function Dp(t,e=Date.now()){const s=t?.provider||"this session's provider",n=t?.resetsAtUtc?vi(t.resetsAtUtc,e):null,r=n?` Resets ${n}.`:"";switch(t?.kind){case"no_provider":return t?.provider?`No provider named ${t.provider}. This session waits until that name exists again, or until it is switched to another provider and model.`:"This session's model does not name a provider, so nothing can pay for it. Switch it to a provider and model.";case"hold":return t?.resetsAtUtc?`${s} is on hold.${r}`:`${s} is on hold until an administrator releases it.`;case"allowance":{const i=bo[t?.period];return`Your ${i?`${i} `:""}allowance on ${s} is used up. The provider has room; your share of it does not.${r}`}default:{const i=bo[t?.period],a=t?.modelQualified?` for ${t.modelQualified}`:"";return`${s} has reached its ${i?`${i} `:""}limit${a}.${r}`}}}function Bp(t,e){const s=cs(t);if(s)return s;const n=t?.sessionId;if(!n)return null;const i=(Array.isArray(e?.budget?.paused)?e.budget.paused:[]).find(a=>a?.sessionId===n);return i?cs({pauseState:i.pause}):null}function Hp(t,e=null){const s=Bp(t,e);return s?{kind:s.kind,provider:s.provider,period:s.period,resetsAtUtc:s.kind==="no_provider"?null:s.resetsAtUtc,label:Yl(s),reason:Dp(s),clears:df(s),color:"red"}:null}function Up(t,e){if(e==="budget_paused")return Yl(cs(t));if(e==="cron_waiting")return"waiting";if(e==="awaiting_children"){const s=Number(t?.activeChildCount)||0;return s>0?`waiting on ${s}`:"waiting on children"}return e}function jp(t){if(!t)return null;const e=t.updatedAt||t.summaryUpdatedAt||t.latestSummaryUpdatedAt||t.createdAt||0;return{status:Xl(t)||"unknown",timestampMs:e||null,relative:e?xi(e):"—"}}function Xl(t){const e=Ql(t);return!e||e==="unknown"?"":Up(t,e)}function Ql(t){return t?.rowVisualStatus||Vl(t)}function Zl(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function ri(t){const e=Vl(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&Wl(t?.error)&&!Zl(t?.orchestrationStatus)?"warning":null}function ii(t,e="local"){const s=ri(t);if(s)return s;const n=Ql(t);if(e==="remote"&&Zl(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="awaiting_children"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function ss(t,e="local"){switch(ii(t,e)){case"running":return"green";case"budget_paused":return"red";case"cron_waiting":return"yellow";case"awaiting_children":return"magenta";case"waiting":return"yellow";case"input_required":return"cyan";case"cancelled":return"gray";case"warning":return"yellow";case"failed":return"red";case"terminated":return"gray";case"completed":return"gray";case"idle":return"white";default:return"white"}}function Jl(t,e="local"){switch(ii(t,e)){case"running":return"*";case"budget_paused":return"‖";case"cron_waiting":return"~";case"awaiting_children":return">";case"waiting":return"~";case"input_required":return"?";case"cancelled":return"x";case"warning":return"!";case"failed":case"terminated":return"x";case"idle":return"";default:return""}}function Ne(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function In(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const oi=Ne({provider:"system",subject:"system"});function So(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(r=>r.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toUpperCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toUpperCase()}function Nr(t){return So(t?.displayName)||So(t?.email)||"?"}function Gp(t,e=!1){return ls(t)?e?t.isGroup?"pinned:folders":"pinned:sessions":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function ec(t,{isMine:e=!1}={}){if(!t)return null;const s=In(t,t?.email||"");return{initials:Nr(t),hue:Kp(Vp(t,t?.email)),name:s||"unknown user",isMine:!!e}}function Wp(t){const e=new Map;for(const s of Object.values(t||{})){const n=s?.owner;if(!n?.subject||!n.displayName&&!n.email)continue;const r=Ne(n);r&&!e.has(r)&&e.set(r,n)}return e}function zp(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(Ne(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const qp=8;function Kp(t){const e=String(t||"").trim().toLowerCase();if(!e)return 0;let s=2166136261;for(let n=0;n<e.length;n+=1)s^=e.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s%qp}function Vp(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function Yp(t,e=1/0){const s=t?.sessions?.byId,n=t?.sessions?.ownerFilter||{all:!0},r=t?.auth||{},i=new Set;for(const a of Object.values(s||{})){if(!a||a.isSystem||a.isGroup)continue;const l=Ne(a.owner);if(!(!l||l===oi)&&Tr(a,n,r)&&(i.add(l),i.size>=e))break}return i.size}function Cr(t){return Yp(t,2)>1}function tc(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function qt(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of tc(t,e)){const r=Ne(n?.owner);r&&!s.has(r)&&s.set(r,n.owner)}return s.size===1?s.values().next().value:null}function vo(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function wo(t,e){const s=vo(t),n=vo(e?.agentId);return!!(s&&n&&s===n)}function Xp(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const a=e.slice(0,n).trim(),l=e.slice(n+s.length).trim();if(a&&wo(l,t))return{displayTitle:a,agentTitle:l}}const r=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(r){const a=r[1].trim(),l=r[2].trim();if(a&&l)return{displayTitle:l,agentTitle:a}}const i=e.indexOf(": ");if(i>0){const a=e.slice(0,i).trim(),l=e.slice(i+2).trim();if(l&&wo(a,t))return{displayTitle:l,agentTitle:a}}return null}function Qp(t){const e=String(t||""),s=e.indexOf(": ");if(s<=0)return null;const n=e.slice(0,s).trim(),r=e.slice(s+2).trim();return!n||!r?null:{userTitle:r,typeTitle:n}}const Zp=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function Jp(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Zp)e=e.replace(s,n);return e}function ai(t){return Jp(em(t))}function em(t){const e=String(t?.title||"").trim(),s=Xp(t);if(!s)return e;const n=Qp(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function sc(t,e){const s=ke(t?.sessionId);if(t?.isSystem)return`${Dt(t,e)} (${s})`;const n=ai(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Tr(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const r=Ne(n!==void 0?n:t?.owner);if(!r)return e.includeUnowned===!0;if(r===oi)return e.includeSystem===!0;const i=Ne(s?.principal);return e.includeMe&&i&&r===i||e.includeShared===!0&&r!==i?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(r)}function nc(t,e={},s={},n=null){const r=qt(t,n||{});if(Tr(t,e,s,r))return!0;if(!n)return!1;if(t?.isGroup)return tc(t,n).some(l=>nc(l,e,s,n));let i=t,a=0;for(;i?.parentSessionId&&a<16;){const l=n[i.parentSessionId];if(!l)return!1;if(Tr(l,e,s))return!0;i=l,a+=1}return!1}function tm(t){return(t||[]).map(e=>e?.text||"").join("")}function li(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const r=n?.parentSessionId;r&&(s.set(n.sessionId,r),e.has(r)||e.set(r,[]),e.get(r).push(n.sessionId))}return{childMap:e,parentMap:s}}function Eo(t){const{childMap:e}=li(t),s=new Map,n=new Set;function r(i){if(s.has(i))return s.get(i);if(n.has(i))return 0;n.add(i);const l=(e.get(i)||[]).reduce((c,d)=>c+1+r(d),0);return n.delete(i),s.set(i,l),l}for(const i of Object.keys(t||{}))r(i);return s}function ko(t=[],e={}){const{parentMap:s}=li(e),n=new Map;for(const r of t){let i=s.get(r.sessionId);for(;i;)n.set(i,(n.get(i)||0)+1),i=s.get(i)}return n}function ci(t={}){if(!t||typeof t!="object")return Eo(t);const e=go.get(t);if(e)return e;const s=Eo(t);return go.set(t,s),s}function di(t=[],e={}){if(!Array.isArray(t))return ko(t,e);const s=yo.get(t);if(s)return s;const n=ko(t,e);return yo.set(t,n),n}function rc(t,e,s,n){const r=s.get(t)||0,i=n.get(t)||0,a=Math.max(0,r-i),l=e?.collapsed?r:a;return l?{text:`[+${l}]`,color:"cyan"}:null}function un(t){if(!t)return"scheduled";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"scheduled";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}function sm(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${un(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Vt(t.cronInterval)}]`,color:"magenta"}:null}function ic(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function nm(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Xl(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:ss(t,e)}));const r=yi(t?.model,t?.reasoningEffort);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r,color:"cyan"}));const i=$d(t?.contextUsage);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i.text,color:i.color}));const a=Ld(t?.contextUsage);return a&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:a.text,color:a.color})),s}function rm(t,e,s,n,r){const i=[],a=s.connection?.mode||"local",l=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";l&&i.push({text:l,color:"gray",role:"depth"});const c=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),d=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),u=!!s.sessions?.selectMode,p=d.has(t.sessionId),m=c.has(t.sessionId);if(p&&i.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),t.depth===0&&ic(e)&&c.size>0&&(m&&!e?.isSystem?i.push({text:"📌 ",color:"yellow"}):i.push({text:" ",color:"gray"})),e?.isGroup)i.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)i.push({text:"⚙ ",color:"yellow",bold:!0});else if(e?.serviceKind)i.push({text:"⚗ ",color:"magenta",bold:!0});else{const B=Jl(e,a);i.push({text:B?`${B} `:" ",color:ss(e,a),role:"status"})}const f=e?.isGroup?"cyan":e?.isSystem?"yellow":ss(e,a),h=qt(e,s.sessions?.byId||{}),g=ke(e?.sessionId),b=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=b?nh(b):"",S=yi(e?.model,e?.reasoningEffort),w=e?.isSystem?Dt(e,s.branding?.title||"PilotSwarm"):ai(e),k=!!(e?.isSystem||e?.isGroup||w&&w.trim()),E=[...i];if(Cr(s)&&!e?.isSystem&&!e?.isGroup){const B=Ne(s?.auth?.principal),V=!!(B&&Ne(h)===B),ce=h?Nr(h):"?";E.push({text:`[${ce}] `,color:V?"green":"cyan",bold:!0,ownerChip:!0})}k?E.push({text:w,color:f,bold:!!(e?.isSystem||e?.isGroup)}):(E.push({text:g,color:f}),y&&(E.push({text:" · ",color:"gray"}),E.push({text:y,color:"gray"})),S&&(E.push({text:" · ",color:"gray"}),E.push({text:S,color:"green"})));const x=rc(e?.sessionId,t,n,r);x&&E.push({text:` ${x.text}`,color:x.color,bold:x.bold});const v=ii(e,a)==="budget_paused"||e?.status==="waiting"?Hp(e,s):null;v&&E.push({text:` ${v.label}`,color:v.color});const P=sm(e);P&&E.push({text:" ⏱",color:"magenta"});const N=[],_=e?.contextUsage?.compaction?.state,D=zr(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&N.push({text:`${e.memberCount}`,color:"gray"}):_==="running"?N.push({text:"⇊",color:"magenta"}):_==="failed"?N.push({text:"!",color:"red"}):D!=null?N.push({text:`${D}%`,color:D>=85?"red":D>=70?"yellow":"green"}):N.push({text:"—",color:"gray"});const L=[];e?.isGroup&&e?.memberCount!=null&&(L.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(L.push({text:" · ",color:"gray"}),L.push({text:y,color:"gray"})));const I=[],C=()=>{I.length&&I.push({text:" · ",color:"gray"})};if(e?.isGroup)I.push(...L);else{k&&(I.push({text:g,color:"cyan"}),y&&(C(),I.push({text:y,color:"gray"})),S&&(C(),I.push({text:S,color:"green"})));const B=e?.contextUsage;B&&Number.isFinite(B.currentTokens)&&Number.isFinite(B.tokenLimit)&&B.tokenLimit>0&&(C(),I.push({text:`ctx ${J(B.currentTokens)}/${J(B.tokenLimit)}`,color:"gray"}));const V=n?.[e?.sessionId];V&&(C(),I.push({text:`${V} child${V===1?"":"ren"}`,color:"gray"})),P&&(C(),I.push({text:P.text,color:P.color})),v&&(C(),I.push({text:v.reason,color:v.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(C(),I.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...E,...k&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...N.length&&!e?.isGroup?[{text:" · ",color:"gray"},...N]:[],...e?.isGroup&&L.length?[{text:" ",color:"gray"},...L]:[]],titleRuns:E,ctxRuns:N,metaRuns:L,badgeRuns:[],selectedMetaRuns:I,detailRuns:I,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:k?w:g,untitled:!k,statusColor:ss(e,a),accentColor:f,pinned:m,selectMode:u,checked:p,owner:Cr(s)&&!e?.isSystem&&!e?.isGroup?{initials:h?Nr(h):"?",isMine:!!(Ne(s?.auth?.principal)&&Ne(h)===Ne(s?.auth?.principal))}:null,childBadge:x?{text:x.text,color:x.color}:null,pause:v,cron:!!P,age:y||null,model:S||null,shortId:g,ctx:N.length>0?{text:N[0].text,color:N[0].color}:null}}}function oc(t){return String(t||"").trim().toLowerCase()}function _t(t,e){const s=oc(e);return s?String(t||"").toLowerCase().includes(s):!0}function im(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let r=s[e],i=0;for(;r&&i<16;){let a=null;if(r.parentSessionId&&s[r.parentSessionId]?a=r.parentSessionId:!r.isGroup&&r.groupId&&s[`group:${r.groupId}`]&&(a=`group:${r.groupId}`),!a||n.has(a))break;n.add(a),r=s[a],i+=1}return n}const xo=new WeakMap;function om(t,e){if(!t||t.length!==e.length)return!1;for(let s=0;s<t.length;s+=1)if(t[s]!==e[s])return!1;return!0}function ds(t){const e=ci(t.sessions.byId),s=di(t.sessions.flat,t.sessions.byId),n=oc(t.sessions?.filterQuery||""),r=t.sessions?.ownerFilter||{all:!0},i=t.auth||{},a=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),l=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),c=im(t.sessions);let d=xo.get(t.sessions.flat);return d||(d=new Map,xo.set(t.sessions.flat,d)),t.sessions.flat.filter(u=>!!(t.sessions.byId[u.sessionId]||u.standIn)).map(u=>{const p=t.sessions.byId[u.sessionId]||u.standIn,m=u.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,f=a.has(u.sessionId),h=l.has(u.sessionId),g=[u,p,m,f,h,n,r,i,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title,t.canvas?.bySessionId?.[u.sessionId],t.canvas?.prefs?.[u.sessionId],p?.pauseState,t.budget?.paused],b=d.get(u.sessionId);if(b&&om(b.deps,g))return b.row;const y=rm(u,p,t,e,s),S={sessionId:u.sessionId,text:tm(y.runs),...y,depth:u.depth,status:p?.status,statusColor:ss(p,t.connection?.mode||"local"),active:m,groupId:p?.groupId||u?.groupId||null,isSystem:!!p?.isSystem,isGroup:!!p?.isGroup,hasChildren:u.hasChildren,collapsed:u.collapsed,pinned:f,selected:h,canPin:ic(p),ownerBadge:Cr(t)&&!p?.isSystem&&!p?.isGroup&&qt(p,t.sessions.byId)?ec(qt(p,t.sessions.byId),{isMine:!!(Ne(t?.auth?.principal)&&Ne(qt(p,t.sessions.byId))===Ne(t?.auth?.principal))}):null,orderable:ls(p),orderContainer:Gp(p,f),canvasMark:Fm(t,u.sessionId),pause:y.chrome?.pause||null};return d.set(u.sessionId,{deps:g,row:S}),S}).filter(u=>{if(c?.has(u.sessionId))return!0;const p=t.sessions.byId[u.sessionId];if(!nc(p,r,i,t.sessions.byId))return!1;const m=qt(p,t.sessions.byId),f=m?`${In(m,"")} ${m.email||""}`:"";return _t(u.text,n)||_t(u.sessionId,n)||_t(f,n)||_t("",n)})}function Pr(t,e=8){const s=ds(t);if(s.length===0)return[];const n=new Set(s.map(p=>p.sessionId)),r=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(p=>n.has(p.sessionId)),i=r.findIndex(p=>p.sessionId===t.sessions.activeSessionId),a=Math.max(0,i);if(r.length<=e)return s;const l=Math.floor(e/2);let c=Math.max(0,a-l),d=Math.min(r.length,c+e);d>r.length&&(d=r.length,c=Math.max(0,d-e));const u=r.slice(c,d);return ci(t.sessions.byId),di(r,t.sessions.byId),s.filter(p=>u.some(m=>m.sessionId===p.sessionId))}function et(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function am(t){const e=t.sessions?.navigationIntent;if(!e||e.status!=="failed")return null;const s=e.errorKind==="not_found"?"not_found":"network";return{sessionId:e.sessionId,errorKind:s,retryable:s==="network",message:s==="not_found"?"This session was not found or has not been shared with you.":"Could not load the linked session. Check your connection and try again."}}function Iv(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function ac(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function lm(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(r=>typeof r=="string"&&r.trim()):[];if(n.length>0){s.push("","Choices:");for(const r of n)s.push(`- ${r}`)}return n.length>0&&e.allowFreeform===!1?s.push("","Reply with one of the choices above in the prompt below."):n.length>0?s.push("","Reply with one of the choices above, or type a free-form answer below."):s.push("","Type your answer in the prompt below and press Enter."),{id:`pending-question:${t.sessionId}:${e.question}`,role:"system",text:s.join(`
|
|
25
|
+
`).length;return zt(e,1,Pl)}function _l(t){return Math.max(as,Math.floor(t*Mu))}function Rl(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*_u),n=Math.max(as,e-xn);return Math.max(as,Math.min(n,s))}function lo(t,e){const s=Math.max(0,Number(t)||0),n=zt(Math.max(0,Number(e)||0),0,s),r=-(s/2);return{minAdjust:r,maxAdjust:Math.max(r,s/2-n)}}function Cs(t,e=0,s=1,n=0,r=0,i=null){const a=$u(t),l=a.width,c=a.height,d=zt(Number(s)||1,1,Pl),u=Ru(i),p=5+d,m=Math.max(18,c-p),h=Math.floor(l*Tl)+(Number(e)||0),g=l-h-Gn;let b=!1,y=!1;h<=jn&&g>Ks?b=!0:g<=Ks&&h>jn?y=!0:h<=jn&&g<=Ks&&(y=e>=0,b=!y);let S,w;b?(S=0,w=l):y?(S=l,w=0):(S=zt(h,Pu,l-ao-Gn),w=Math.max(ao,l-S-Gn));const E=_l(m)+(Number(n)||0),x=m-E;let v=!1,P=!1;x<=Kn&&E>qn?P=!0:E<=qn&&x>Kn?v=!0:x<=Kn&&E<=qn&&(P=(Number(n)||0)>=0,v=!P);let N,_;if(v)N=0,_=m;else if(P)N=m,_=0;else{const ce=Rl(c,m);N=zt(E,as,ce),_=Math.max(xn,m-N)}const L=Math.max(es,Math.floor(m*Ml))+(Number(r)||0),I=m-L;let C=!1,U=!1;I<=zn&&L>Wn?C=!0:L<=Wn&&I>zn?U=!0:I<=zn&&L<=Wn&&(C=(Number(r)||0)>=0,U=!C);let B,V;return C?(B=m,V=0):U?(V=m,B=0):(B=zt(L,es,Math.max(es,m-nn)),V=Math.max(nn,m-B)),{viewport:a,totalWidth:l,totalHeight:c,reservedRows:p,bodyHeight:m,promptRows:d,fullscreenPane:u,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(r)||0,leftHidden:b,rightHidden:y,inspectorHidden:C,activityHidden:U,sessionHidden:v,chatHidden:P,leftWidth:S,rightWidth:w,sessionPaneHeight:N,chatPaneHeight:_,activityPaneHeight:B,inspectorPaneHeight:V}}function kr(t){if(t?.fullscreenPane)return[t.fullscreenPane,$.PROMPT];if(t?.leftHidden)return[$.INSPECTOR,$.ACTIVITY,$.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[$.CHAT]:t?.chatHidden?[$.SESSIONS]:[$.SESSIONS,$.CHAT],$.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[$.ACTIVITY]:t?.activityHidden?[$.INSPECTOR]:[$.INSPECTOR,$.ACTIVITY];return[$.CHAT,...e,$.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[$.ACTIVITY]:t?.activityHidden?[$.INSPECTOR]:[$.INSPECTOR,$.ACTIVITY];return[$.SESSIONS,...e,$.PROMPT]}return t?.inspectorHidden?[$.SESSIONS,$.CHAT,$.ACTIVITY,$.PROMPT]:t?.activityHidden?[$.SESSIONS,$.CHAT,$.INSPECTOR,$.PROMPT]:[$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY,$.PROMPT]}function it(t,e){const s=kr(e);return s.includes(t)?t:s[0]||$.PROMPT}function Lu(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[$.PROMPT]:$.PROMPT,[$.ACTIVITY]:$.INSPECTOR,[$.INSPECTOR]:$.INSPECTOR}[t]||$.INSPECTOR:e?.rightHidden?{[$.PROMPT]:$.PROMPT,[$.CHAT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.SESSIONS]:$.SESSIONS}[t]||(e?.sessionHidden?$.CHAT:$.SESSIONS):{[$.PROMPT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.ACTIVITY]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.INSPECTOR]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.CHAT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.SESSIONS]:$.SESSIONS}[t]||(e?.sessionHidden?$.CHAT:$.SESSIONS)}function Ou(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[$.PROMPT]:$.PROMPT,[$.INSPECTOR]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.INSPECTOR:e?.rightHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.CHAT]:$.CHAT}[t]||(e?.chatHidden?$.SESSIONS:$.CHAT):e?.inspectorHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.CHAT:e?.activityHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.INSPECTOR,[$.INSPECTOR]:$.INSPECTOR}[t]||$.CHAT:{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.INSPECTOR,[$.INSPECTOR]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.CHAT}function $l(t){const e=String(t||"").trim();if(!e)return{error:"Paste a link to plugin.json or the folder that contains it."};let s;try{s=new URL(e)}catch{return{error:"That does not look like a URL — paste the browser link to plugin.json or its folder."}}const n=s.hostname.toLowerCase();if(n==="github.com"||n==="www.github.com"){const i=s.pathname.split("/").filter(Boolean);if(i.length<2)return{error:"GitHub links need at least github.com/org/repo."};const[a,l,c,d,...u]=i,p=l.replace(/\.git$/u,""),m=`https://github.com/${a}/${p}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:d?{kind:"github",repoUrl:m,ref:d,path:u.length?`/${u.join("/")}`:null}:{error:"That GitHub link is missing the branch segment."}:{kind:"github",repoUrl:m,ref:null,path:null}}if(n==="dev.azure.com"||n.endsWith(".visualstudio.com")){if(!s.pathname.includes("/_git/"))return{error:"Azure DevOps links must point at a repo (…/_git/<repo>…)."};const i=`${s.origin}${s.pathname.split("?")[0]}`.replace(/\/$/u,""),a=s.searchParams.get("path"),l=s.searchParams.get("version"),c=l&&/^G[BT]/u.test(l)?l.slice(2):l||null;return{kind:"ado",repoUrl:i,ref:c,path:a||null}}return{error:"Only GitHub and Azure DevOps links are recognized here — for a tarball use the URL tab."}}const rn=2*1024*1024,Fu=new Set(["node_modules",".git"]);function xr(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s="";const n=32768;for(let r=0;r<e.length;r+=n)s+=String.fromCharCode.apply(null,e.subarray(r,r+n));return btoa(s)}function Ll(t){const e=String(t||"").replace(/\s+/gu,"");if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const s=atob(e),n=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)n[r]=s.charCodeAt(r);return n}function Ol(t){return t.split("/").some(e=>Fu.has(e))}function Fl(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function Du(t,e){return t?`${t}/${e}`:e}function Dl(t,e){const s=String(e?.message||e||"");return new Error(`could not reach ${t} from the browser (${s||"network error"}) — the host may block cross-origin reads from this portal; use Upload folder instead`)}async function on(t,e,s,n){let r;try{r=await t(e,{headers:{accept:"application/json",...s}})}catch(i){throw Dl(n,i)}if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`${n} returned HTTP ${r.status}${i?`: ${i.slice(0,200)}`:""}`)}return r.json()}async function Bl(t,e,s,n){let r;try{r=await t(e,{headers:s})}catch(a){throw Dl(n,a)}if(!r.ok)throw new Error(`${n} returned HTTP ${r.status} for ${e}`);const i=await r.arrayBuffer();return new Uint8Array(i)}function Bu(t){const e=new URL(t).pathname.split("/").filter(Boolean);if(e.length<2)throw new Error(`not a GitHub repository URL: ${t}`);return{owner:e[0],repo:e[1].replace(/\.git$/u,"")}}async function Hu({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,onProgress:i}){const{owner:a,repo:l}=Bu(t),c="https://api.github.com",d={"x-github-api-version":"2022-11-28",...r?{authorization:`Bearer ${r}`}:{}};let u=e;u||(i("resolving the default branch…"),u=(await on(n,`${c}/repos/${a}/${l}`,d,"api.github.com"))?.default_branch||"main"),i(`reading the file tree of ${a}/${l}@${u}…`);const p=await on(n,`${c}/repos/${a}/${l}/git/trees/${encodeURIComponent(u)}?recursive=1`,d,"api.github.com");if(p?.truncated)throw new Error("this repository's file tree is too large for the API listing — point the link at the package folder");const m=Array.isArray(p?.tree)?p.tree:[],f=Fl(s),h=Du(f,"plugin.json");if(!m.some(k=>k.type==="blob"&&k.path===h))throw new Error(`no plugin.json at ${h||"the repository root"} on ${u} — link to the folder that contains the manifest`);const g=f?`${f}/`:"",b=m.filter(k=>k.type==="blob"&&(!g||k.path.startsWith(g))&&!Ol(k.path.slice(g.length))),y=[];let S=0,w=0;for(const k of b){w+=1;const E=k.path.slice(g.length);i(`fetching ${w}/${b.length}: ${E}`);const x=r?await Uu(n,c,a,l,k.sha,d):await Bl(n,`https://raw.githubusercontent.com/${a}/${l}/${encodeURIComponent(u)}/${k.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(S+=x.length,S>rn)throw new Error(`package exceeds the ${Math.round(rn/1024)} KB upload limit at ${E}`);y.push({path:E,contentBase64:xr(x)})}return y}async function Uu(t,e,s,n,r,i){const a=await on(t,`${e}/repos/${s}/${n}/git/blobs/${r}`,i,"api.github.com"),l=String(a?.content||"").replace(/\s+/gu,"");if(a?.encoding&&a.encoding!=="base64")throw new Error(`unexpected blob encoding "${a.encoding}" from api.github.com`);return Ll(l)}function ju(t){const e=new URL(t),s=e.pathname.split("/").filter(Boolean),n=s.indexOf("_git");if(n<0||n===s.length-1)throw new Error(`not an Azure DevOps repository URL: ${t}`);const r=decodeURIComponent(s[n+1]),i=s.slice(0,n).map(decodeURIComponent),a=e.hostname.toLowerCase(),l=a.endsWith(".visualstudio.com")?a.split(".")[0]:i[0],c=a.endsWith(".visualstudio.com")?i[0]:i[1];if(!l||!c)throw new Error(`could not read org/project from ${t}`);return{org:l,project:c,repo:r}}async function Gu({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,tokenKind:i,onProgress:a}){if(!r)throw new Error("Azure DevOps needs a credential — sign-in did not yield a token; paste a PAT with Code (read)");const{org:l,project:c,repo:d}=ju(t),u=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(d)}`,m={authorization:i==="pat"?`Basic ${xr(new TextEncoder().encode(`:${r}`))}`:`Bearer ${r}`},f=Fl(s),h=`/${f}`,g=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";a(`reading ${d}${f?`/${f}`:""}…`);const b=await on(n,`${u}/items?scopePath=${encodeURIComponent(h)}&recursionLevel=Full${g}&api-version=7.1`,m,"dev.azure.com"),S=(Array.isArray(b?.value)?b.value:[]).filter(P=>P?.gitObjectType==="blob"&&!P?.isFolder),w=f?`/${f}/`:"/";if(!S.find(P=>P.path===`${w}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${h} — link to the folder that contains the manifest`);const E=[];let x=0,v=0;for(const P of S){const N=String(P.path||"").slice(w.length);if(!N||Ol(N))continue;v+=1,a(`fetching ${v}/${S.length}: ${N}`);const _=await Bl(n,`${u}/blobs/${encodeURIComponent(P.objectId)}?api-version=7.1&$format=octetStream`,{...m,accept:"application/octet-stream"},"dev.azure.com");if(x+=_.length,x>rn)throw new Error(`package exceeds the ${Math.round(rn/1024)} KB upload limit at ${N}`);E.push({path:N,contentBase64:xr(_)})}return E}async function Wu(t,{fetchImpl:e=typeof fetch=="function"?fetch:null,token:s=null,tokenKind:n="bearer",onProgress:r=()=>{}}={}){if(typeof e!="function")throw new Error("no fetch implementation available");const i=$l(t);if(i.error)throw new Error(i.error);const a={fetchImpl:e,token:s,tokenKind:n,onProgress:r},l=i.kind==="github"?await Hu(i,a):await Gu(i,a);if(l.length===0)throw new Error("the package folder is empty");return{kind:i.kind,files:l}}function zu(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=Ll(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function co(t){return t?.isSystem?yl(t):Number.MAX_SAFE_INTEGER}function qu(t=[]){const e=new Map;for(let s=0;s<t.length;s+=1){const n=t[s]?.sessionId;!n||e.has(n)||e.set(n,s)}return e}function Ku(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return qu(t);const e=new Map;for(const[s,n]of Object.entries(t||{}))!s||typeof n!="number"||Number.isNaN(n)||e.set(s,n);return e}function Vu(t){if(t instanceof Map)return t;const e=new Map;if(!Array.isArray(t))return e;for(let s=0;s<t.length;s+=1){const n=t[s];typeof n!="string"||!n||e.has(n)||e.set(n,s)}return e}function ls(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function Yu(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function uo(t,e){return!!(Yu(t)&&e&&e.has(t.sessionId))}function po(t,e){return t.isSystem?0:t.isGroup&&uo(t,e)?1:uo(t,e)?2:t.isGroup?3:4}function mo(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function fo(t,e,s,n,r){const i=po(t,n),a=po(e,n);if(i!==a)return i-a;const l=co(t),c=co(e);if(l!==c)return l-c;if(r&&r.size>0&&ls(t)&&ls(e)){const y=r.has(t.sessionId)?r.get(t.sessionId):1/0,S=r.has(e.sessionId)?r.get(e.sessionId):1/0;if(y!==S)return y-S}const d=s.get(t.sessionId),u=s.get(e.sessionId);if(typeof d=="number"&&typeof u=="number"&&d!==u)return d-u;const p=mo(t),m=mo(e);if(p>0&&m>0&&p!==m)return p-m;const f=(t.createdAt||0)-(e.createdAt||0);if(f!==0)return f;const h=String(t.title||""),g=String(e.title||""),b=h.localeCompare(g);return b!==0?b:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function ot(t=[],e=new Set,s=[],n=null,r=null){const i=new Map,a=new Map,l=Ku(s),c=Vu(r),d=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of t)i.set(g.sessionId,g);const u=[];for(const g of t){if(g.isGroup||!g.groupId||g.parentSessionId)continue;const b=`group:${g.groupId}`;if(i.has(b))continue;const y={sessionId:b,groupId:g.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};i.set(b,y),u.push(y)}const p=new Set(u.map(g=>g.sessionId));u.length>0&&(t=[...t,...u]);for(const g of t){const b=!g.isGroup&&g.groupId&&!g.parentSessionId&&i.has(`group:${g.groupId}`)?`group:${g.groupId}`:null,y=g.parentSessionId||b;!y||!i.has(y)||(a.has(y)||a.set(y,[]),a.get(y).push(g))}for(const g of a.values())g.sort((b,y)=>fo(b,y,l,d,c));const m=t.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,b)=>fo(g,b,l,d,c)),f=[];function h(g,b){const y=a.get(g.sessionId)||[];if(f.push({sessionId:g.sessionId,depth:b,hasChildren:y.length>0,collapsed:e.has(g.sessionId),...p.has(g.sessionId)?{standIn:g}:{}}),!e.has(g.sessionId))for(const S of y)h(S,b+1)}for(const g of m)h(g,0);return f}const ct="VS Code",ms="Retro",Bt="Others",ho=Object.freeze([ct,ms,Bt]);function Xu(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function Vn(t){return Number.parseInt(t,16)/255}function Qu(t){const e=String(t||"").trim();return/^#[0-9a-f]{3}$/iu.test(e)?`#${e.slice(1).split("").map(s=>s+s).join("")}`:/^#[0-9a-f]{6}$/iu.test(e)?e:null}function Yn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Zu(t){const e=Qu(t);if(!e)return 0;const s=Yn(Vn(e.slice(1,3))),n=Yn(Vn(e.slice(3,5))),r=Yn(Vn(e.slice(5,7)));return .2126*s+.7152*n+.0722*r}function Ju(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return Zu(e)>=.5}function Me({id:t,label:e,description:s,group:n=Bt,page:r,terminal:i,tui:a={},icon:l=null}){const c={background:r?.background||i?.background||"#000000",surface:i?.background||r?.background||"#000000",foreground:i?.foreground||r?.foreground||"#ffffff",white:i?.foreground||r?.foreground||"#ffffff",gray:r?.hintColor||i?.brightBlack||i?.white||"#999999",black:i?.black||"#000000",red:i?.red||"#ff5555",green:i?.green||"#55ff55",yellow:i?.yellow||"#ffff55",blue:i?.blue||"#5555ff",magenta:i?.magenta||"#ff55ff",cyan:i?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",otherUserChatLabel:i?.brightMagenta||i?.magenta||"#c9a3ff",activeHighlightBackground:i?.blue||"#5555ff",activeHighlightForeground:i?.background||"#000000",selectionBackground:i?.cursor||i?.blue||"#5555ff",selectionForeground:i?.cursorAccent||i?.background||"#000000",promptCursorBackground:i?.cursor||i?.green||"#55ff55",promptCursorForeground:i?.cursorAccent||i?.background||"#000000"};return Xu({id:t,label:e,description:s,group:n,icon:l||null,page:r,terminal:i,tui:{...c,...a}})}const ep=Me({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:ct,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#30363d",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#0d1117",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),tp=Me({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:ct,page:{background:"#f6f8fa",foreground:"#1f2328",overlayBackground:"#ffffff",overlayForeground:"#1f2328",hintColor:"#57606a",modalBackdrop:"rgba(31, 35, 40, 0.34)",modalBackground:"#ffffff",modalBorder:"#d0d7de",modalForeground:"#1f2328",modalMuted:"#57606a",modalSelectedBackground:"#ddf4ff",modalSelectedBorder:"#0969da",modalSelectedForeground:"#0550ae"},terminal:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"#ddf4ff",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#0f6f78",brightWhite:"#1f2328"},tui:{surface:"#ffffff",border:"#d0d7de",userChat:"#0969da",userChatLabel:"#0550ae",activeHighlightBackground:"#ddf4ff",activeHighlightForeground:"#0550ae",selectionBackground:"#0969da",selectionForeground:"#ffffff",promptCursorBackground:"#0969da",promptCursorForeground:"#ffffff"}}),Hl=Me({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:Bt,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),sp=Me({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:ct,page:{background:"#193549",foreground:"#ffffff",overlayBackground:"#193549",overlayForeground:"#ffffff",hintColor:"#a8c5e6",modalBackdrop:"rgba(7, 17, 28, 0.68)",modalBackground:"#224b68",modalBorder:"#2e6c99",modalForeground:"#ffffff",modalMuted:"#a8c5e6",modalSelectedBackground:"#ffc600",modalSelectedBorder:"#ffc600",modalSelectedForeground:"#193549"},terminal:{background:"#193549",foreground:"#ffffff",cursor:"#ffc600",cursorAccent:"#193549",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#ff628c",green:"#3ad900",yellow:"#ff9d00",blue:"#0088ff",magenta:"#ff628c",cyan:"#80ffbb",white:"#ffffff",brightBlack:"#666666",brightRed:"#ff628c",brightGreen:"#3ad900",brightYellow:"#ff9d00",brightBlue:"#0088ff",brightMagenta:"#ff9d00",brightCyan:"#80ffbb",brightWhite:"#ffffff"},tui:{surface:"#193549",activeHighlightBackground:"#0f5f91",activeHighlightForeground:"#ffffff",selectionBackground:"#ffc600",selectionForeground:"#193549",promptCursorBackground:"#ffc600",promptCursorForeground:"#193549"}}),np=Me({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:ct,page:{background:"#282a36",foreground:"#f8f8f2",overlayBackground:"#282a36",overlayForeground:"#f8f8f2",hintColor:"#bd93f9",modalBackdrop:"rgba(24, 25, 33, 0.72)",modalBackground:"#313442",modalBorder:"#6272a4",modalForeground:"#f8f8f2",modalMuted:"#bd93f9",modalSelectedBackground:"#44475a",modalSelectedBorder:"#bd93f9",modalSelectedForeground:"#f8f8f2"},terminal:{background:"#282a36",foreground:"#f8f8f2",cursor:"#f8f8f2",cursorAccent:"#282a36",selectionBackground:"rgba(189, 147, 249, 0.24)",black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff6e6e",brightGreen:"#69ff94",brightYellow:"#ffffa5",brightBlue:"#d6acff",brightMagenta:"#ff92df",brightCyan:"#a4ffff",brightWhite:"#ffffff"},tui:{surface:"#282a36",activeHighlightBackground:"#44475a",activeHighlightForeground:"#f8f8f2",selectionBackground:"#bd93f9",selectionForeground:"#282a36",promptCursorBackground:"#f8f8f2",promptCursorForeground:"#282a36"}}),rp=Me({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:ct,page:{background:"#1e1e2e",foreground:"#cdd6f4",overlayBackground:"#1e1e2e",overlayForeground:"#cdd6f4",hintColor:"#bac2de",modalBackdrop:"rgba(17, 17, 27, 0.74)",modalBackground:"#313244",modalBorder:"#585b70",modalForeground:"#cdd6f4",modalMuted:"#bac2de",modalSelectedBackground:"#45475a",modalSelectedBorder:"#89b4fa",modalSelectedForeground:"#cdd6f4"},terminal:{background:"#1e1e2e",foreground:"#cdd6f4",cursor:"#f5e0dc",cursorAccent:"#1e1e2e",selectionBackground:"rgba(137, 180, 250, 0.22)",black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#585b70",brightRed:"#f38ba8",brightGreen:"#a6e3a1",brightYellow:"#f9e2af",brightBlue:"#89b4fa",brightMagenta:"#f5c2e7",brightCyan:"#94e2d5",brightWhite:"#f5e0dc"},tui:{surface:"#1e1e2e",activeHighlightBackground:"#45475a",activeHighlightForeground:"#cdd6f4",selectionBackground:"#89b4fa",selectionForeground:"#1e1e2e",promptCursorBackground:"#f5e0dc",promptCursorForeground:"#1e1e2e"}}),ip=Me({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:ct,page:{background:"#030603",foreground:"#c8ffc8",overlayBackground:"#030603",overlayForeground:"#c8ffc8",hintColor:"#59a659",modalBackdrop:"rgba(0, 6, 0, 0.82)",modalBackground:"#081208",modalBorder:"#1f5f1f",modalForeground:"#d6ffd6",modalMuted:"#6dbb6d",modalSelectedBackground:"#0f240f",modalSelectedBorder:"#39ff14",modalSelectedForeground:"#dfffdf"},terminal:{background:"#000000",foreground:"#c8ffc8",cursor:"#39ff14",cursorAccent:"#000000",selectionBackground:"rgba(57, 255, 20, 0.2)",black:"#031003",red:"#39ff14",green:"#2a7a22",yellow:"#4a8a30",blue:"#1a6a4a",magenta:"#2a7a3a",cyan:"#2a8a5a",white:"#b7f7b7",brightBlack:"#59a659",brightRed:"#9aff86",brightGreen:"#7dff66",brightYellow:"#e0ff8a",brightBlue:"#61ffc2",brightMagenta:"#b4ffb4",brightCyan:"#98ffe0",brightWhite:"#e8ffe8"},tui:{surface:"#030603",activeHighlightBackground:"#1a3a1a",activeHighlightForeground:"#e8ffe8",selectionBackground:"#39ff14",selectionForeground:"#000000",promptCursorBackground:"#39ff14",promptCursorForeground:"#000000"}}),op=Me({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:ct,page:{background:"#0a0f1e",foreground:"#e8f2ff",overlayBackground:"#0a0f1e",overlayForeground:"#e8f2ff",hintColor:"#7e90b5",modalBackdrop:"rgba(6, 10, 24, 0.76)",modalBackground:"#121a30",modalBorder:"#2d4a73",modalForeground:"#edf5ff",modalMuted:"#93a7cc",modalSelectedBackground:"#19365f",modalSelectedBorder:"#55c2ff",modalSelectedForeground:"#f3fbff"},terminal:{background:"#0a0f1e",foreground:"#e8f2ff",cursor:"#55c2ff",cursorAccent:"#0a0f1e",selectionBackground:"rgba(85, 194, 255, 0.22)",black:"#10182b",red:"#ff6b88",green:"#67f5c2",yellow:"#ffd36b",blue:"#55c2ff",magenta:"#c79bff",cyan:"#7ceeff",white:"#c3d4ef",brightBlack:"#7e90b5",brightRed:"#ff8aa2",brightGreen:"#8cffd8",brightYellow:"#ffe28f",brightBlue:"#8fdcff",brightMagenta:"#d8b6ff",brightCyan:"#a2f5ff",brightWhite:"#ffffff"},tui:{surface:"#0c1325",activeHighlightBackground:"#173052",activeHighlightForeground:"#f3fbff",selectionBackground:"#55c2ff",selectionForeground:"#0a0f1e",promptCursorBackground:"#55c2ff",promptCursorForeground:"#0a0f1e"}}),ap=Me({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:ct,page:{background:"#282828",foreground:"#ebdbb2",overlayBackground:"#282828",overlayForeground:"#ebdbb2",hintColor:"#a89984",modalBackdrop:"rgba(40, 40, 40, 0.74)",modalBackground:"#3c3836",modalBorder:"#504945",modalForeground:"#ebdbb2",modalMuted:"#a89984",modalSelectedBackground:"#504945",modalSelectedBorder:"#fabd2f",modalSelectedForeground:"#fbf1c7"},terminal:{background:"#282828",foreground:"#ebdbb2",cursor:"#ebdbb2",cursorAccent:"#282828",selectionBackground:"rgba(250, 189, 47, 0.22)",black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},tui:{surface:"#282828",activeHighlightBackground:"#504945",activeHighlightForeground:"#fbf1c7",selectionBackground:"#fabd2f",selectionForeground:"#282828",promptCursorBackground:"#ebdbb2",promptCursorForeground:"#282828"}}),lp=Me({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:ct,page:{background:"#052529",foreground:"#b2cacd",overlayBackground:"#052529",overlayForeground:"#b2cacd",hintColor:"#40d4e7",modalBackdrop:"rgba(3, 25, 27, 0.72)",modalBackground:"#073940",modalBorder:"#0e6671",modalForeground:"#b2cacd",modalMuted:"#87a7ab",modalSelectedBackground:"#0b515b",modalSelectedBorder:"#40d4e7",modalSelectedForeground:"#ebfdff"},terminal:{background:"#03191b",foreground:"#b2cacd",cursor:"#85efff",cursorAccent:"#03191b",selectionBackground:"rgba(22, 159, 177, 0.27)",black:"#324a4d",red:"#e66533",green:"#49e9a6",yellow:"#e4b781",blue:"#49ace9",magenta:"#df769b",cyan:"#49d6e9",white:"#b2cacd",brightBlack:"#5e878c",brightRed:"#e97749",brightGreen:"#60ebb1",brightYellow:"#e69533",brightBlue:"#60b6eb",brightMagenta:"#e798b3",brightCyan:"#60dbeb",brightWhite:"#c1d4d7"},tui:{surface:"#03191b",activeHighlightBackground:"#083d44",activeHighlightForeground:"#ebfdff",selectionBackground:"#169fb1",selectionForeground:"#052529",promptCursorBackground:"#85efff",promptCursorForeground:"#03191b"}}),cp=Me({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:ct,page:{background:"#0b1117",foreground:"#c7d1da",overlayBackground:"#0b1117",overlayForeground:"#c7d1da",hintColor:"#7cc6ff",modalBackdrop:"rgba(5, 9, 13, 0.74)",modalBackground:"#121a23",modalBorder:"#28455b",modalForeground:"#d7e2eb",modalMuted:"#8f9dab",modalSelectedBackground:"#173041",modalSelectedBorder:"#7cc6ff",modalSelectedForeground:"#eef6ff"},terminal:{background:"#060b10",foreground:"#c7d1da",cursor:"#9fd4ff",cursorAccent:"#060b10",selectionBackground:"rgba(72, 125, 170, 0.30)",black:"#2a3138",red:"#ef6b73",green:"#7ddc8f",yellow:"#d9b36c",blue:"#68aee8",magenta:"#b28cff",cyan:"#58c9d4",white:"#c7d1da",brightBlack:"#6e7a86",brightRed:"#f28a92",brightGreen:"#97e5a6",brightYellow:"#e4c28b",brightBlue:"#86c1f1",brightMagenta:"#c6a7ff",brightCyan:"#7ad7df",brightWhite:"#e5edf5"},tui:{surface:"#060b10",activeHighlightBackground:"#123142",activeHighlightForeground:"#eef6ff",selectionBackground:"#4a7baa",selectionForeground:"#0b1117",promptCursorBackground:"#9fd4ff",promptCursorForeground:"#060b10"}}),dp=Me({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:ms,page:{background:"#020503",foreground:"#c9f7d3",overlayBackground:"#020503",overlayForeground:"#d9ffe0",hintColor:"#7ee787",modalBackdrop:"rgba(0, 6, 2, 0.82)",modalBackground:"#061109",modalBorder:"#245c33",modalForeground:"#d9ffe0",modalMuted:"#83a98c",modalSelectedBackground:"#0b2a14",modalSelectedBorder:"#63e27a",modalSelectedForeground:"#ecfff0"},terminal:{background:"#020503",foreground:"#c9f7d3",cursor:"#8cff9f",cursorAccent:"#020503",selectionBackground:"#174923",black:"#061109",red:"#ff5f5f",green:"#63e27a",yellow:"#d6b95f",blue:"#5aa7ff",magenta:"#c586ff",cyan:"#5ce1d8",white:"#c9f7d3",brightBlack:"#5b7a61",brightRed:"#ff7f7f",brightGreen:"#8cff9f",brightYellow:"#f0d982",brightBlue:"#82bdff",brightMagenta:"#d9a8ff",brightCyan:"#89f4ee",brightWhite:"#effff1"},tui:{surface:"#020503",border:"#245c33",userChat:"#f0d982",userChatLabel:"#fff0a8",activeHighlightBackground:"#0b2a14",activeHighlightForeground:"#ecfff0",selectionBackground:"#63e27a",selectionForeground:"#020503",promptCursorBackground:"#8cff9f",promptCursorForeground:"#020503"}}),up=Me({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:Bt,page:{background:"#000000",foreground:"#f8f8f2",overlayBackground:"#050505",overlayForeground:"#ffffff",hintColor:"#b8b8b8",modalBackdrop:"rgba(0, 0, 0, 0.88)",modalBackground:"#050505",modalBorder:"#d8d8d8",modalForeground:"#ffffff",modalMuted:"#b8b8b8",modalSelectedBackground:"#003f88",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#f8f8f2",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"#003f88",black:"#000000",red:"#ff4d4d",green:"#00d084",yellow:"#ffd84d",blue:"#4da3ff",magenta:"#d8d8d8",cyan:"#ffffff",white:"#f8f8f2",brightBlack:"#8a8a8a",brightRed:"#ff6b6b",brightGreen:"#28e29a",brightYellow:"#ffe173",brightBlue:"#73b8ff",brightMagenta:"#ffffff",brightCyan:"#ffffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#d8d8d8",userChat:"#ffffff",userChatLabel:"#d8d8d8",activeHighlightBackground:"#003f88",activeHighlightForeground:"#ffffff",selectionBackground:"#ffffff",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),pp=Me({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:ms,page:{background:"#008080",foreground:"#000000",overlayBackground:"#c0c0c0",overlayForeground:"#000000",hintColor:"#4a4a4a",modalBackdrop:"rgba(0, 0, 0, 0.45)",modalBackground:"#c0c0c0",modalBorder:"#808080",modalForeground:"#000000",modalMuted:"#5a5a5a",modalSelectedBackground:"#000080",modalSelectedBorder:"#000080",modalSelectedForeground:"#ffffff"},terminal:{background:"#c0c0c0",foreground:"#000000",cursor:"#000080",cursorAccent:"#c0c0c0",selectionBackground:"#000080",black:"#000000",red:"#800000",green:"#008000",yellow:"#808000",blue:"#000080",magenta:"#800080",cyan:"#008080",white:"#c0c0c0",brightBlack:"#5a5a5a",brightRed:"#c00000",brightGreen:"#006000",brightYellow:"#7a5c00",brightBlue:"#0000c0",brightMagenta:"#a000a0",brightCyan:"#006a6a",brightWhite:"#000000"},tui:{surface:"#c0c0c0",border:"#808080",userChat:"#000080",userChatLabel:"#000080",activeHighlightBackground:"#000080",activeHighlightForeground:"#ffffff",selectionBackground:"#000080",selectionForeground:"#ffffff",promptCursorBackground:"#000080",promptCursorForeground:"#ffffff"}}),mp=Me({id:"ms-dos",label:"MS-DOS 2.0",description:"CGA light-grey on black, the 16-colour CGA palette with brown, and CP437 box framing.",group:ms,page:{background:"#000000",foreground:"#aaaaaa",overlayBackground:"#000000",overlayForeground:"#aaaaaa",hintColor:"#8f8f8f",modalBackdrop:"rgba(0, 0, 0, 0.78)",modalBackground:"#000000",modalBorder:"#aaaaaa",modalForeground:"#aaaaaa",modalMuted:"#8f8f8f",modalSelectedBackground:"#aaaaaa",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#000000"},terminal:{background:"#000000",foreground:"#aaaaaa",cursor:"#aaaaaa",cursorAccent:"#000000",selectionBackground:"#aaaaaa",black:"#000000",red:"#aa0000",green:"#00aa00",yellow:"#aa5500",blue:"#0000aa",magenta:"#aa00aa",cyan:"#00aaaa",white:"#aaaaaa",brightBlack:"#8f8f8f",brightRed:"#ff5555",brightGreen:"#55ff55",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#aaaaaa",userChat:"#ffffff",userChatLabel:"#ffffff",activeHighlightBackground:"#aaaaaa",activeHighlightForeground:"#000000",selectionBackground:"#aaaaaa",selectionForeground:"#000000",promptCursorBackground:"#aaaaaa",promptCursorForeground:"#000000"}}),fp=Me({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:ms,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#2a1d14"},{d:"M6 7h20v20H6z",fill:"#c89a6a"},{d:"M5 6h22v6H5z",fill:"#4a2f1a"},{d:"M9 15h5v3.4H9z",fill:"#1a1008"},{d:"M18 15h5v3.4h-5z",fill:"#1a1008"},{d:"M8.6 13.6l6 1 -.3 1.7-6-1z",fill:"#3a2412"},{d:"M23.4 13.6l-6 1 .3 1.7 6-1z",fill:"#3a2412"},{d:"M14.5 18.5h3v2.4h-3z",fill:"#a8734a"},{d:"M11 22h10v1.8H11z",fill:"#7a3a2a"}]},page:{background:"#100b09",foreground:"#d9cba8",overlayBackground:"#1c1310",overlayForeground:"#d9cba8",hintColor:"#a08d68",modalBackdrop:"rgba(16, 11, 9, 0.82)",modalBackground:"#1c1310",modalBorder:"#6f5432",modalForeground:"#d9cba8",modalMuted:"#a08d68",modalSelectedBackground:"#6f5432",modalSelectedBorder:"#a4885c",modalSelectedForeground:"#fff4d6"},terminal:{background:"#100b09",foreground:"#d9cba8",cursor:"#b81c1c",cursorAccent:"#100b09",selectionBackground:"#6f5432",black:"#100b09",red:"#c42222",green:"#3f9e3f",yellow:"#e8c020",blue:"#3a5ce0",magenta:"#a0446a",cyan:"#4a8f8f",white:"#d9cba8",brightBlack:"#a08d68",brightRed:"#ff3a1e",brightGreen:"#5fc45f",brightYellow:"#ffd84a",brightBlue:"#5a7ae8",brightMagenta:"#c46a94",brightCyan:"#6fb5b5",brightWhite:"#fff4d6"},tui:{border:"#6f5432",userChat:"#e8c020",userChatLabel:"#ffd84a",selectionBackground:"#6f5432",selectionForeground:"#fff4d6",activeHighlightBackground:"#6f5432",activeHighlightForeground:"#fff4d6",promptCursorBackground:"#b81c1c",promptCursorForeground:"#fff4d6"}}),hp=Me({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:ms,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#000000"},{d:"M3 17h4v11H3z",fill:"#00e337"},{d:"M9 11h4v17H9z",fill:"#7ad91e"},{d:"M15 6h4v22h-4z",fill:"#b6e000"},{d:"M21 13h4v15h-4z",fill:"#ffb400"},{d:"M27 20h3v8h-3z",fill:"#ff3b00"},{d:"M3 15h4v1.6H3z",fill:"#d6d6cc"},{d:"M9 9h4v1.6H9z",fill:"#d6d6cc"},{d:"M15 4h4v1.6h-4z",fill:"#d6d6cc"},{d:"M21 11h4v1.6h-4z",fill:"#d6d6cc"},{d:"M27 18h3v1.6h-3z",fill:"#d6d6cc"}]},page:{background:"#000000",foreground:"#00e337",overlayBackground:"#1c1c1c",overlayForeground:"#00e337",hintColor:"#949494",modalBackdrop:"rgba(0, 0, 0, 0.82)",modalBackground:"#1c1c1c",modalBorder:"#5e5e5e",modalForeground:"#00e337",modalMuted:"#a0a0a0",modalSelectedBackground:"#0000c6",modalSelectedBorder:"#5e5e5e",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#00e337",cursor:"#ffb400",cursorAccent:"#000000",selectionBackground:"#0000c6",black:"#000000",red:"#ff3b00",green:"#00e337",yellow:"#ffb400",blue:"#4a7cf0",magenta:"#cc66cc",cyan:"#29c8c8",white:"#d6d6cc",brightBlack:"#949494",brightRed:"#ff6a3d",brightGreen:"#5cff7a",brightYellow:"#ffd24a",brightBlue:"#7fa5ff",brightMagenta:"#e08ae0",brightCyan:"#6fe0e0",brightWhite:"#ffffff"},tui:{border:"#5e5e5e",gray:"#949494",userChat:"#ffb400",userChatLabel:"#ffd24a",selectionBackground:"#0000c6",selectionForeground:"#ffffff",activeHighlightBackground:"#0000c6",activeHighlightForeground:"#ffffff",promptCursorBackground:"#ffb400",promptCursorForeground:"#000000"}}),gp=Me({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:Bt,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#241f1c"},{d:"M11.5 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M19 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M10.5 6h3.5v3.5h-3.5z",fill:"#ffe9dd"},{d:"M18 6h3.5v3.5H18z",fill:"#ffe9dd"},{d:"M11.5 7h1.5v1.5h-1.5z",fill:"#1a1210"},{d:"M19 7h1.5v1.5H19z",fill:"#1a1210"},{d:"M10 11.5h12v2H10z",fill:"#ff7a3d"},{d:"M7 13.5h18v3H7z",fill:"#f74c00"},{d:"M5 16.5h22v4H5z",fill:"#f74c00"},{d:"M7 20.5h18v1.8H7z",fill:"#f74c00"},{d:"M14.5 18h3v1.4h-3z",fill:"#c23c00"},{d:"M0 11h4.5v6.5H0z",fill:"#d63a00"},{d:"M0 13.2h3v2H0z",fill:"#241f1c"},{d:"M27.5 11h4.5v6.5h-4.5z",fill:"#d63a00"},{d:"M29 13.2h3v2h-3z",fill:"#241f1c"},{d:"M8.5 22.3h2.5v2.4H8.5z",fill:"#d63a00"},{d:"M14.75 22.3h2.5v2.4h-2.5z",fill:"#d63a00"},{d:"M21 22.3h2.5v2.4H21z",fill:"#d63a00"}]},page:{background:"#1c1917",foreground:"#e7e0d8",overlayBackground:"#262220",overlayForeground:"#e7e0d8",hintColor:"#a39a8f",modalBackdrop:"rgba(28, 25, 23, 0.82)",modalBackground:"#262220",modalBorder:"#4a4038",modalForeground:"#e7e0d8",modalMuted:"#a9a096",modalSelectedBackground:"#7c2d12",modalSelectedBorder:"#ce422b",modalSelectedForeground:"#ffeadf"},terminal:{background:"#1c1917",foreground:"#e7e0d8",cursor:"#f74c00",cursorAccent:"#1c1917",selectionBackground:"#7c2d12",black:"#1c1917",red:"#f3554a",green:"#6cc24a",yellow:"#e5b02b",blue:"#58a6ff",magenta:"#c98bdf",cyan:"#f74c00",white:"#e7e0d8",brightBlack:"#a39a8f",brightRed:"#ff7b70",brightGreen:"#8fdd6e",brightYellow:"#ffcc55",brightBlue:"#83c0ff",brightMagenta:"#dcaaef",brightCyan:"#ff7a3d",brightWhite:"#fdf6ee"},tui:{border:"#4a4038",userChat:"#ffb454",userChatLabel:"#ffd08a",selectionBackground:"#7c2d12",selectionForeground:"#ffeadf",activeHighlightBackground:"#7c2d12",activeHighlightForeground:"#ffeadf",promptCursorBackground:"#f74c00",promptCursorForeground:"#1c1917"}}),yp="#a35838",bp="M4.14 33.09L4.14 18.89L5.7 15.77L30.05 1.4L33.95 1.4L43.32 6.56L57.99 15.3L59.08 16.7L59.71 18.58L59.71 45.27L59.08 47.14L56.9 49.64L41.44 58.38L38.32 60.57L33.64 62.91L30.52 62.91L27.71 61.66L14.6 53.7L6.79 49.48L5.54 48.23L4.45 46.2L4.14 44.49L4.14 33.09ZM55.8 26.07L55.8 19.36L55.02 18.42L33.8 6.09L31.45 5.78L30.05 6.24L8.51 18.89L8.51 45.11L10.22 46.67L18.03 50.89L30.05 58.22L31.77 58.85L33.17 58.69L53.93 46.67L55.65 44.96L55.8 26.07ZM17.09 34.81L16.78 33.56L13.19 32.62L13.19 27.0L17.09 26.54L18.97 23.26L16.94 19.67L21.0 15.61L24.43 17.95L27.86 16.86L29.11 12.8L34.58 12.8L35.51 16.86L38.63 17.95L39.57 17.8L42.69 15.61L46.6 19.67L46.28 20.92L44.88 22.95L44.88 23.73L46.28 26.38L50.65 27.16L50.65 32.47L47.69 33.4L47.06 34.03L42.54 32.0L42.54 29.97L41.91 27.63L40.82 25.6L38.63 23.26L34.73 21.39L32.55 21.07L29.11 21.39L26.3 22.48L23.96 24.35L22.4 26.54L21.31 29.97L21.31 33.25L22.87 37.46L24.12 39.18L27.4 41.83L24.59 42.77L19.9 42.93L16.0 41.68L15.22 40.12L17.72 37.31L17.09 34.81ZM36.76 35.59L35.51 32.62L35.82 32.0L50.19 39.34L49.25 41.99L43.32 51.2L42.54 51.04L41.6 46.2L35.51 49.64L31.3 50.58L28.49 50.58L21.93 49.01L18.97 47.3L16.47 45.11L16.78 44.8L19.12 45.58L22.09 45.74L25.21 45.42L28.18 44.33L29.74 44.49L33.48 42.46L37.39 39.18L37.85 37.93L36.76 35.59Z",Sp=Me({id:"duroxide",label:"Duroxide",description:"Iron oxide pressed into black felt - the durable-execution runtime's own mark, traced from the banner.",group:Bt,icon:{viewBox:"0 0 64 64",paths:[{d:bp,fill:yp}]},page:{background:"#201e1f",foreground:"#e5e0dc",overlayBackground:"#2e2c2d",overlayForeground:"#e5e0dc",hintColor:"#a89f99",modalBackdrop:"rgba(23, 21, 23, 0.86)",modalBackground:"#2e2c2d",modalBorder:"#4d4643",modalForeground:"#e5e0dc",modalMuted:"#a89f99",modalSelectedBackground:"#7c3f26",modalSelectedBorder:"#a35838",modalSelectedForeground:"#ffeee4"},terminal:{background:"#282627",foreground:"#e5e0dc",cursor:"#d2764a",cursorAccent:"#201e1f",selectionBackground:"#7c3f26",black:"#201e1f",red:"#e86a5f",green:"#7fb069",yellow:"#d9a441",blue:"#6a9fd4",magenta:"#b98bc4",cyan:"#d2764a",white:"#e5e0dc",brightBlack:"#a89f99",brightRed:"#f4897f",brightGreen:"#9bc888",brightYellow:"#efc069",brightBlue:"#8fbce4",brightMagenta:"#d0a8d9",brightCyan:"#ba714c",brightWhite:"#fdf7f2"},tui:{border:"#6a615b",userChat:"#e0b070",userChatLabel:"#f0cf9a",selectionBackground:"#7c3f26",selectionForeground:"#ffeee4",activeHighlightBackground:"#7c3f26",activeHighlightForeground:"#ffeee4",promptCursorBackground:"#d2764a",promptCursorForeground:"#201e1f"}}),vp=Me({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:Bt,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#1a7fa8"},{d:"M7 2h18a3 3 0 0 1 3 3v15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V5a3 3 0 0 1 3-3z",fill:"#ffe01b"},{d:"M6.2 6.4a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0z",fill:"#e3c00c"},{d:"M23.4 4.8a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0z",fill:"#e3c00c"},{d:"M5.4 18.2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0z",fill:"#e3c00c"},{d:"M24 19a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0z",fill:"#e3c00c"},{d:"M7.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M16.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M9.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M18.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M10.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M19.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M10 16.6c2 3.6 10 3.6 12 0c-1.2 5-10.8 5-12 0z",fill:"#6b4e00"},{d:"M14 17.6h1.9v2.1H14z",fill:"#ffffff"},{d:"M16.1 17.6H18v2.1h-1.9z",fill:"#ffffff"},{d:"M6 23h20v3H6z",fill:"#ffffff"},{d:"M14.4 24.6h3.2v2h-3.2z",fill:"#d2232a"},{d:"M13 26.4h6l-3 5.2z",fill:"#d2232a"}]},page:{background:"#07293c",foreground:"#e6f4fb",overlayBackground:"#0e3852",overlayForeground:"#e6f4fb",hintColor:"#8fb9cf",modalBackdrop:"rgba(7, 41, 60, 0.84)",modalBackground:"#0e3852",modalBorder:"#1d6a8c",modalForeground:"#e6f4fb",modalMuted:"#95bed3",modalSelectedBackground:"#ffe01b",modalSelectedBorder:"#fff08a",modalSelectedForeground:"#07293c"},terminal:{background:"#07293c",foreground:"#e6f4fb",cursor:"#ffe01b",cursorAccent:"#07293c",selectionBackground:"#ffe01b",black:"#07293c",red:"#ff6152",green:"#7ed957",yellow:"#ffa62b",blue:"#7fd4c1",magenta:"#ff9bd2",cyan:"#ffe01b",white:"#e6f4fb",brightBlack:"#8fb9cf",brightRed:"#ff9084",brightGreen:"#a5e888",brightYellow:"#ffc46b",brightBlue:"#a8e5d8",brightMagenta:"#ffbde1",brightCyan:"#fff08a",brightWhite:"#ffffff"},tui:{border:"#1d6a8c",userChat:"#ffa62b",userChatLabel:"#ffc46b",selectionBackground:"#ffe01b",selectionForeground:"#07293c",activeHighlightBackground:"#ffe01b",activeHighlightForeground:"#07293c",promptCursorBackground:"#ffe01b",promptCursorForeground:"#07293c"}});function wp(t,e){const s=ho.indexOf(t.group),n=ho.indexOf(e.group),r=s===-1?Number.MAX_SAFE_INTEGER:s,i=n===-1?Number.MAX_SAFE_INTEGER:n;return r!==i?r-i:t.label.localeCompare(e.label,void 0,{sensitivity:"base"})}const Ul=Object.freeze([Hl,np,ep,tp,sp,op,ip,rp,ap,lp,cp,dp,up,pp,mp,fp,hp,gp,Sp,vp].sort(wp)),Ep=new Map(Ul.map(t=>[t.id,t])),kp=Hl.id;function xp(){return Ul}function ft(t){return t?Ep.get(t)??null:null}const Ip=new Set(["agent","user","system"]);function an(t){const e=Array.isArray(t?.ownerKeys)?[...new Set(t.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:t&&typeof t=="object"?t?.all===!0:!0,includeSystem:t?.includeSystem===!0,includeUnowned:t?.includeUnowned===!0,includeMe:t?.includeMe===!0,includeShared:t?.includeShared===!0,ownerKeys:e}}function Ap(t){if(typeof t=="string"){const r=t.trim();return r?{filename:r,sizeBytes:null,contentType:"",isBinary:!1,uploadedAt:"",source:"agent"}:null}if(!t||typeof t!="object")return null;const e=String(t.filename||"").trim();if(!e)return null;const s=Number(t.sizeBytes),n=typeof t.contentType=="string"?t.contentType:"";return{filename:e,sizeBytes:Number.isFinite(s)&&s>=0?s:null,contentType:n,isBinary:t.isBinary===!0,uploadedAt:typeof t.uploadedAt=="string"?t.uploadedAt:"",source:Ip.has(t.source)?t.source:"agent"}}function ln(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const r of e){const i=Ap(r);!i||n.has(i.filename)||(n.add(i.filename),s.push(i))}return s}function Np(t,e){const s=String(e||"").trim();return s&&ln(t).find(n=>n.filename===s)||null}function ei(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),r=Number(e.portalSessionColumnAdjust),i=Number(e.activityPaneAdjust),a=Number(e.canvasPaneAdjust),l=Number(e.diagnosticsPaneAdjust),c=Number(e.diagnosticsSplitAdjust);return{paneAdjust:Number.isFinite(s)?Math.trunc(s):0,sessionPaneAdjust:Number.isFinite(n)?Math.trunc(n):0,portalSessionColumnAdjust:Number.isFinite(r)?Math.trunc(r):0,activityPaneAdjust:Number.isFinite(i)?Math.trunc(i):0,canvasPaneAdjust:Number.isFinite(a)?Math.trunc(a):0,diagnosticsPaneAdjust:Number.isFinite(l)?Math.trunc(l):0,diagnosticsSplitAdjust:Number.isFinite(c)?Math.trunc(c):0}}function cn(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s}function ti(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s}function Ir(t){if(!Array.isArray(t))return new Set;const e=new Set;for(const s of t){const n=String(s||"").trim();n&&e.add(n)}return e}function Cp(t){return t==="canvas"?"canvas":"panes"}function jl(t,e){const s=t&&typeof t=="object"?t:null;return s&&(typeof s.canvasOpen=="boolean"||typeof s.diagnosticsOpen=="boolean")?{canvasOpen:s.canvasOpen===!0,diagnosticsOpen:s.diagnosticsOpen===!0,zen:s.zen===!0&&s.canvasOpen===!0}:{canvasOpen:e==="canvas",diagnosticsOpen:!1,zen:!1}}function Ze(t,e){const s=String(t||""),n=Number(e);return Number.isInteger(n)&&n>=2&&n<=5?`${s}#${n}`:s}function Tp(t){const e=/^(.*)#([2-5])$/.exec(String(t||""));return e?{sessionId:e[1],slot:Number(e[2])}:{sessionId:String(t||""),slot:1}}function si(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[s,n]of Object.entries(t)){const r=String(s||"").trim();if(!r||!n||typeof n!="object")continue;const i=Number(n.lastViewedRev),a=Number(n.lastViewedDataRev),l=Number(n.zenRailPx);e[r]={optedOut:n.optedOut===!0,lastViewedRev:Number.isFinite(i)&&i>0?Math.floor(i):0,lastViewedDataRev:Number.isFinite(a)&&a>0?Math.floor(a):0,...Number.isFinite(l)&&l>0?{zenRailPx:Math.floor(l)}:{}}}return e}function Gl(t){if(t==null)return null;const e=String(t).trim();return e||null}const Pp=Object.freeze(["limit","allowance","hold","no_provider"]);function cs(t){const e=t?.pauseState;if(!e||typeof e!="object")return null;const s=String(e.kind||"");if(!Pp.includes(s))return null;const n=i=>{const a=String(i??"").trim();return a||null},r=i=>Number.isFinite(Number(i))?Number(i):null;return{kind:s,provider:n(e.provider),period:["day","week","month"].includes(String(e.period))?String(e.period):null,modelQualified:n(e.modelQualified),limitTokens:r(e.limitTokens),usedTokens:r(e.usedTokens),ceilingTokens:r(e.ceilingTokens),yourUsedTokens:r(e.yourUsedTokens),resetsAtUtc:n(e.resetsAtUtc)}}const Mp=Object.freeze(["day","week","month"]),dn=Object.freeze([14,30,90]),Ie=14;function Ar({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,sessionOwnerFilter:r=null,layoutAdjustments:i=null,pinnedSessionIds:a=null,collapsedSessionIds:l=null,activeSessionId:c=null,sessionOrder:d=null,rightPaneMode:u=null,desktopPanes:p=null,canvasPrefs:m=null}={}){const f=jl(p,Cp(u)),h=r!=null,g=l!=null,b=ei(i);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},docs:{agentPackageGuideUrl:s?.agentPackageGuideUrl||"https://github.com/affandar/PilotSwarm/blob/main/docs/building-agent-packages.md"},auth:{principal:null,authorization:null},ui:{focusRegion:$.SESSIONS,budgetOpen:!1,inspectorTab:lt[0],nodeMapSelectedNode:null,sequenceExpandedTurns:[],sequenceSelectedTurn:null,rightPaneMode:f.canvasOpen?"canvas":"panes",canvasOpen:f.canvasOpen,diagnosticsOpen:f.diagnosticsOpen,canvasZen:f.zen,canvasMaximized:!1,statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:ft(n)?.id||kp,touchScale:!1,sessionDetailCollapsed:!0,agentPickerUsage:{},modal:null,fullscreenPane:null,layout:{...b,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},groupRows:[],flat:[],activeSessionId:Gl(c),collapsedIds:Ir(l),collapsedIdsExplicit:g,pinnedIds:cn(a),manualOrder:ti(d),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:h,ownerFilter:an(r),navigationIntent:null,filterExceptionId:null},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,markedIds:[],previewOrigin:null,restoreArtifactId:null,paneOpen:!1,paneRestoresToHidden:!1,htmlViewMode:"rendered",htmlZoom:1,htmlFitWidth:!1,filter:{scope:"selectedSession",query:""}},canvas:{bySessionId:{},prefs:si(m),flipSeq:0},logs:{available:!1,availabilityReason:"Log tailing disabled: no K8S_CONTEXT configured in the env file.",tailing:!1,entries:[],filter:{source:"allNodes",level:"all",format:"pretty"}},sessionStats:{bySessionId:{}},fleetStats:{loading:!1,data:null,userStats:null,fetchedAt:0},budget:{tab:"providers",summary:{loading:!1,error:null,fetchedAt:0,days:14,preset:"all",providers:[],data:null},loading:!1,refreshing:!1,loaded:!1,error:null,fetchedAt:0,grid:[],overall:!1,rangeDays:Ie,selectedProvider:null,selectedScope:"*",missingProvider:null,series:{provider:null,scope:"*",rangeDays:Ie,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:Ie,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0},paused:[],pausedError:null},admin:{visible:!1,loading:!1,loadError:null,profile:null,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:0,storeAsSystem:!1},systemGhcpKey:{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},modelProviders:{loading:!1,error:null,page:"mine",providers:[],models:[],defaults:null,fetchedAt:0,mutation:{pending:null,error:null},selection:{focus:"providers",providerName:null,agentId:null},create:{editing:!1,stage:"name",name:"",typeId:"",shared:!1,draft:"",cursorIndex:0,saving:!1,error:null}},section:"providers",packages:{loading:!1,error:null,list:[],workerState:[],fetchedAt:0,selectedName:null,detail:null,detailLoading:!1,detailError:null,changelog:null,workspace:{tree:null,treeLoading:!1,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null},action:{pending:null,error:null},addDialog:{open:!1,kind:"repo",scope:"user",updateName:null,repoUrl:"",ref:"",path:"",url:"",authToken:"",submitting:!1,progress:null,error:null}},workers:{loading:!1,error:null,list:[],fetchedAt:0,attempts:0,lastAttemptAt:0,lastSkip:null}}}}function Wl(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function _p(t,e){return!(!Wl(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const zl="activeHighlightBackground",ni="activeHighlightForeground";function Rp(t){return t==="anthropic-wif"}const Xn="userChat",$p="userChatLabel",Lp="otherUserChatLabel",go=new WeakMap,yo=new WeakMap;function Op(t){return t||ni}function ql(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Op(s?.color):ni,backgroundColor:zl,bold:s?.bold??!0}))}function dt(t,{color:e=ni,bold:s=!0}={}){return{text:t,color:e,backgroundColor:zl,bold:s}}function at(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Fp=72;function Kl(t){const e=Number(t)||0;return e>0&&e<=Fp}function Vl(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return s&&cs(t)?"budget_paused":t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}const bo={day:"daily",week:"weekly",month:"monthly"};function Yl(t){if(!t)return"paused";switch(t.kind){case"no_provider":return"no provider";case"hold":return"paused · hold";case"allowance":return"paused · allowance";default:return"paused · limit"}}function Dp(t,e=Date.now()){const s=t?.provider||"this session's provider",n=t?.resetsAtUtc?vi(t.resetsAtUtc,e):null,r=n?` Resets ${n}.`:"";switch(t?.kind){case"no_provider":return t?.provider?`No provider named ${t.provider}. This session waits until that name exists again, or until it is switched to another provider and model.`:"This session's model does not name a provider, so nothing can pay for it. Switch it to a provider and model.";case"hold":return t?.resetsAtUtc?`${s} is on hold.${r}`:`${s} is on hold until an administrator releases it.`;case"allowance":{const i=bo[t?.period];return`Your ${i?`${i} `:""}allowance on ${s} is used up. The provider has room; your share of it does not.${r}`}default:{const i=bo[t?.period],a=t?.modelQualified?` for ${t.modelQualified}`:"";return`${s} has reached its ${i?`${i} `:""}limit${a}.${r}`}}}function Bp(t,e){const s=cs(t);if(s)return s;const n=t?.sessionId;if(!n)return null;const i=(Array.isArray(e?.budget?.paused)?e.budget.paused:[]).find(a=>a?.sessionId===n);return i?cs({pauseState:i.pause}):null}function Hp(t,e=null){const s=Bp(t,e);return s?{kind:s.kind,provider:s.provider,period:s.period,resetsAtUtc:s.kind==="no_provider"?null:s.resetsAtUtc,label:Yl(s),reason:Dp(s),clears:df(s),color:"red"}:null}function Up(t,e){if(e==="budget_paused")return Yl(cs(t));if(e==="cron_waiting")return"waiting";if(e==="awaiting_children"){const s=Number(t?.activeChildCount)||0;return s>0?`waiting on ${s}`:"waiting on children"}return e}function jp(t){if(!t)return null;const e=t.updatedAt||t.summaryUpdatedAt||t.latestSummaryUpdatedAt||t.createdAt||0;return{status:Xl(t)||"unknown",timestampMs:e||null,relative:e?xi(e):"—"}}function Xl(t){const e=Ql(t);return!e||e==="unknown"?"":Up(t,e)}function Ql(t){return t?.rowVisualStatus||Vl(t)}function Zl(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function ri(t){const e=Vl(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&Wl(t?.error)&&!Zl(t?.orchestrationStatus)?"warning":null}function ii(t,e="local"){const s=ri(t);if(s)return s;const n=Ql(t);if(e==="remote"&&Zl(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="awaiting_children"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function ss(t,e="local"){switch(ii(t,e)){case"running":return"green";case"budget_paused":return"red";case"cron_waiting":return"yellow";case"awaiting_children":return"magenta";case"waiting":return"yellow";case"input_required":return"cyan";case"cancelled":return"gray";case"warning":return"yellow";case"failed":return"red";case"terminated":return"gray";case"completed":return"gray";case"idle":return"white";default:return"white"}}function Jl(t,e="local"){switch(ii(t,e)){case"running":return"*";case"budget_paused":return"‖";case"cron_waiting":return"~";case"awaiting_children":return">";case"waiting":return"~";case"input_required":return"?";case"cancelled":return"x";case"warning":return"!";case"failed":case"terminated":return"x";case"idle":return"";default:return""}}function Ne(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function In(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const oi=Ne({provider:"system",subject:"system"});function So(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(r=>r.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toUpperCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toUpperCase()}function Nr(t){return So(t?.displayName)||So(t?.email)||"?"}function Gp(t,e=!1){return ls(t)?e?t.isGroup?"pinned:folders":"pinned:sessions":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function ec(t,{isMine:e=!1}={}){if(!t)return null;const s=In(t,t?.email||"");return{initials:Nr(t),hue:Kp(Vp(t,t?.email)),name:s||"unknown user",isMine:!!e}}function Wp(t){const e=new Map;for(const s of Object.values(t||{})){const n=s?.owner;if(!n?.subject||!n.displayName&&!n.email)continue;const r=Ne(n);r&&!e.has(r)&&e.set(r,n)}return e}function zp(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(Ne(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const qp=8;function Kp(t){const e=String(t||"").trim().toLowerCase();if(!e)return 0;let s=2166136261;for(let n=0;n<e.length;n+=1)s^=e.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s%qp}function Vp(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function Yp(t,e=1/0){const s=t?.sessions?.byId,n=t?.sessions?.ownerFilter||{all:!0},r=t?.auth||{},i=new Set;for(const a of Object.values(s||{})){if(!a||a.isSystem||a.isGroup)continue;const l=Ne(a.owner);if(!(!l||l===oi)&&Tr(a,n,r)&&(i.add(l),i.size>=e))break}return i.size}function Cr(t){return Yp(t,2)>1}function tc(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function qt(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of tc(t,e)){const r=Ne(n?.owner);r&&!s.has(r)&&s.set(r,n.owner)}return s.size===1?s.values().next().value:null}function vo(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function wo(t,e){const s=vo(t),n=vo(e?.agentId);return!!(s&&n&&s===n)}function Xp(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const a=e.slice(0,n).trim(),l=e.slice(n+s.length).trim();if(a&&wo(l,t))return{displayTitle:a,agentTitle:l}}const r=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(r){const a=r[1].trim(),l=r[2].trim();if(a&&l)return{displayTitle:l,agentTitle:a}}const i=e.indexOf(": ");if(i>0){const a=e.slice(0,i).trim(),l=e.slice(i+2).trim();if(l&&wo(a,t))return{displayTitle:l,agentTitle:a}}return null}function Qp(t){const e=String(t||""),s=e.indexOf(": ");if(s<=0)return null;const n=e.slice(0,s).trim(),r=e.slice(s+2).trim();return!n||!r?null:{userTitle:r,typeTitle:n}}const Zp=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function Jp(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Zp)e=e.replace(s,n);return e}function ai(t){return Jp(em(t))}function em(t){const e=String(t?.title||"").trim(),s=Xp(t);if(!s)return e;const n=Qp(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function sc(t,e){const s=ke(t?.sessionId);if(t?.isSystem)return`${Dt(t,e)} (${s})`;const n=ai(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Tr(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const r=Ne(n!==void 0?n:t?.owner);if(!r)return e.includeUnowned===!0;if(r===oi)return e.includeSystem===!0;const i=Ne(s?.principal);return e.includeMe&&i&&r===i||e.includeShared===!0&&r!==i?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(r)}function nc(t,e={},s={},n=null){const r=qt(t,n||{});if(Tr(t,e,s,r))return!0;if(!n)return!1;if(t?.isGroup)return tc(t,n).some(l=>nc(l,e,s,n));let i=t,a=0;for(;i?.parentSessionId&&a<16;){const l=n[i.parentSessionId];if(!l)return!1;if(Tr(l,e,s))return!0;i=l,a+=1}return!1}function tm(t){return(t||[]).map(e=>e?.text||"").join("")}function li(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const r=n?.parentSessionId;r&&(s.set(n.sessionId,r),e.has(r)||e.set(r,[]),e.get(r).push(n.sessionId))}return{childMap:e,parentMap:s}}function Eo(t){const{childMap:e}=li(t),s=new Map,n=new Set;function r(i){if(s.has(i))return s.get(i);if(n.has(i))return 0;n.add(i);const l=(e.get(i)||[]).reduce((c,d)=>c+1+r(d),0);return n.delete(i),s.set(i,l),l}for(const i of Object.keys(t||{}))r(i);return s}function ko(t=[],e={}){const{parentMap:s}=li(e),n=new Map;for(const r of t){let i=s.get(r.sessionId);for(;i;)n.set(i,(n.get(i)||0)+1),i=s.get(i)}return n}function ci(t={}){if(!t||typeof t!="object")return Eo(t);const e=go.get(t);if(e)return e;const s=Eo(t);return go.set(t,s),s}function di(t=[],e={}){if(!Array.isArray(t))return ko(t,e);const s=yo.get(t);if(s)return s;const n=ko(t,e);return yo.set(t,n),n}function rc(t,e,s,n){const r=s.get(t)||0,i=n.get(t)||0,a=Math.max(0,r-i),l=e?.collapsed?r:a;return l?{text:`[+${l}]`,color:"cyan"}:null}function un(t){if(!t)return"scheduled";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"scheduled";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}function sm(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${un(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Vt(t.cronInterval)}]`,color:"magenta"}:null}function ic(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function nm(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Xl(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:ss(t,e)}));const r=yi(t?.model,t?.reasoningEffort);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r,color:"cyan"}));const i=$d(t?.contextUsage);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i.text,color:i.color}));const a=Ld(t?.contextUsage);return a&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:a.text,color:a.color})),s}function rm(t,e,s,n,r){const i=[],a=s.connection?.mode||"local",l=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";l&&i.push({text:l,color:"gray",role:"depth"});const c=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),d=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),u=!!s.sessions?.selectMode,p=d.has(t.sessionId),m=c.has(t.sessionId);if(p&&i.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),t.depth===0&&ic(e)&&c.size>0&&(m&&!e?.isSystem?i.push({text:"📌 ",color:"yellow"}):i.push({text:" ",color:"gray"})),e?.isGroup)i.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)i.push({text:"⚙ ",color:"yellow",bold:!0});else if(e?.serviceKind)i.push({text:"⚗ ",color:"magenta",bold:!0});else{const B=Jl(e,a);i.push({text:B?`${B} `:" ",color:ss(e,a),role:"status"})}const f=e?.isGroup?"cyan":e?.isSystem?"yellow":ss(e,a),h=qt(e,s.sessions?.byId||{}),g=ke(e?.sessionId),b=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=b?nh(b):"",S=yi(e?.model,e?.reasoningEffort),w=e?.isSystem?Dt(e,s.branding?.title||"PilotSwarm"):ai(e),k=!!(e?.isSystem||e?.isGroup||w&&w.trim()),E=[...i];if(Cr(s)&&!e?.isSystem&&!e?.isGroup){const B=Ne(s?.auth?.principal),V=!!(B&&Ne(h)===B),ce=h?Nr(h):"?";E.push({text:`[${ce}] `,color:V?"green":"cyan",bold:!0,ownerChip:!0})}k?E.push({text:w,color:f,bold:!!(e?.isSystem||e?.isGroup)}):(E.push({text:g,color:f}),y&&(E.push({text:" · ",color:"gray"}),E.push({text:y,color:"gray"})),S&&(E.push({text:" · ",color:"gray"}),E.push({text:S,color:"green"})));const x=rc(e?.sessionId,t,n,r);x&&E.push({text:` ${x.text}`,color:x.color,bold:x.bold});const v=ii(e,a)==="budget_paused"||e?.status==="waiting"?Hp(e,s):null;v&&E.push({text:` ${v.label}`,color:v.color});const P=sm(e);P&&E.push({text:" ⏱",color:"magenta"});const N=[],_=e?.contextUsage?.compaction?.state,D=zr(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&N.push({text:`${e.memberCount}`,color:"gray"}):_==="running"?N.push({text:"⇊",color:"magenta"}):_==="failed"?N.push({text:"!",color:"red"}):D!=null?N.push({text:`${D}%`,color:D>=85?"red":D>=70?"yellow":"green"}):N.push({text:"—",color:"gray"});const L=[];e?.isGroup&&e?.memberCount!=null&&(L.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(L.push({text:" · ",color:"gray"}),L.push({text:y,color:"gray"})));const I=[],C=()=>{I.length&&I.push({text:" · ",color:"gray"})};if(e?.isGroup)I.push(...L);else{k&&(I.push({text:g,color:"cyan"}),y&&(C(),I.push({text:y,color:"gray"})),S&&(C(),I.push({text:S,color:"green"})));const B=e?.contextUsage;B&&Number.isFinite(B.currentTokens)&&Number.isFinite(B.tokenLimit)&&B.tokenLimit>0&&(C(),I.push({text:`ctx ${J(B.currentTokens)}/${J(B.tokenLimit)}`,color:"gray"}));const V=n?.[e?.sessionId];V&&(C(),I.push({text:`${V} child${V===1?"":"ren"}`,color:"gray"})),P&&(C(),I.push({text:P.text,color:P.color})),v&&(C(),I.push({text:v.reason,color:v.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(C(),I.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...E,...k&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...N.length&&!e?.isGroup?[{text:" · ",color:"gray"},...N]:[],...e?.isGroup&&L.length?[{text:" ",color:"gray"},...L]:[]],titleRuns:E,ctxRuns:N,metaRuns:L,badgeRuns:[],selectedMetaRuns:I,detailRuns:I,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:k?w:g,untitled:!k,statusColor:ss(e,a),accentColor:f,pinned:m,selectMode:u,checked:p,owner:Cr(s)&&!e?.isSystem&&!e?.isGroup?{initials:h?Nr(h):"?",isMine:!!(Ne(s?.auth?.principal)&&Ne(h)===Ne(s?.auth?.principal))}:null,childBadge:x?{text:x.text,color:x.color}:null,pause:v,cron:!!P,age:y||null,model:S||null,shortId:g,ctx:N.length>0?{text:N[0].text,color:N[0].color}:null}}}function oc(t){return String(t||"").trim().toLowerCase()}function _t(t,e){const s=oc(e);return s?String(t||"").toLowerCase().includes(s):!0}function im(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let r=s[e],i=0;for(;r&&i<16;){let a=null;if(r.parentSessionId&&s[r.parentSessionId]?a=r.parentSessionId:!r.isGroup&&r.groupId&&s[`group:${r.groupId}`]&&(a=`group:${r.groupId}`),!a||n.has(a))break;n.add(a),r=s[a],i+=1}return n}const xo=new WeakMap;function om(t,e){if(!t||t.length!==e.length)return!1;for(let s=0;s<t.length;s+=1)if(t[s]!==e[s])return!1;return!0}function ds(t){const e=ci(t.sessions.byId),s=di(t.sessions.flat,t.sessions.byId),n=oc(t.sessions?.filterQuery||""),r=t.sessions?.ownerFilter||{all:!0},i=t.auth||{},a=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),l=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),c=im(t.sessions);let d=xo.get(t.sessions.flat);return d||(d=new Map,xo.set(t.sessions.flat,d)),t.sessions.flat.filter(u=>!!(t.sessions.byId[u.sessionId]||u.standIn)).map(u=>{const p=t.sessions.byId[u.sessionId]||u.standIn,m=u.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,f=a.has(u.sessionId),h=l.has(u.sessionId),g=[u,p,m,f,h,n,r,i,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title,t.canvas?.bySessionId?.[u.sessionId],t.canvas?.prefs?.[u.sessionId],p?.pauseState,t.budget?.paused],b=d.get(u.sessionId);if(b&&om(b.deps,g))return b.row;const y=rm(u,p,t,e,s),S={sessionId:u.sessionId,text:tm(y.runs),...y,depth:u.depth,status:p?.status,statusColor:ss(p,t.connection?.mode||"local"),active:m,groupId:p?.groupId||u?.groupId||null,isSystem:!!p?.isSystem,isGroup:!!p?.isGroup,hasChildren:u.hasChildren,collapsed:u.collapsed,pinned:f,selected:h,canPin:ic(p),ownerBadge:Cr(t)&&!p?.isSystem&&!p?.isGroup&&qt(p,t.sessions.byId)?ec(qt(p,t.sessions.byId),{isMine:!!(Ne(t?.auth?.principal)&&Ne(qt(p,t.sessions.byId))===Ne(t?.auth?.principal))}):null,orderable:ls(p),orderContainer:Gp(p,f),canvasMark:Fm(t,u.sessionId),pause:y.chrome?.pause||null};return d.set(u.sessionId,{deps:g,row:S}),S}).filter(u=>{if(c?.has(u.sessionId))return!0;const p=t.sessions.byId[u.sessionId];if(!nc(p,r,i,t.sessions.byId))return!1;const m=qt(p,t.sessions.byId),f=m?`${In(m,"")} ${m.email||""}`:"";return _t(u.text,n)||_t(u.sessionId,n)||_t(f,n)||_t("",n)})}function Pr(t,e=8){const s=ds(t);if(s.length===0)return[];const n=new Set(s.map(p=>p.sessionId)),r=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(p=>n.has(p.sessionId)),i=r.findIndex(p=>p.sessionId===t.sessions.activeSessionId),a=Math.max(0,i);if(r.length<=e)return s;const l=Math.floor(e/2);let c=Math.max(0,a-l),d=Math.min(r.length,c+e);d>r.length&&(d=r.length,c=Math.max(0,d-e));const u=r.slice(c,d);return ci(t.sessions.byId),di(r,t.sessions.byId),s.filter(p=>u.some(m=>m.sessionId===p.sessionId))}function et(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function am(t){const e=t.sessions?.navigationIntent;if(!e||e.status!=="failed")return null;const s=e.errorKind==="not_found"?"not_found":"network";return{sessionId:e.sessionId,errorKind:s,retryable:s==="network",message:s==="not_found"?"This session was not found or has not been shared with you.":"Could not load the linked session. Check your connection and try again."}}function Tv(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function ac(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function lm(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(r=>typeof r=="string"&&r.trim()):[];if(n.length>0){s.push("","Choices:");for(const r of n)s.push(`- ${r}`)}return n.length>0&&e.allowFreeform===!1?s.push("","Reply with one of the choices above in the prompt below."):n.length>0?s.push("","Reply with one of the choices above, or type a free-form answer below."):s.push("","Type your answer in the prompt below and press Enter."),{id:`pending-question:${t.sessionId}:${e.question}`,role:"system",text:s.join(`
|
|
26
26
|
`),time:"",createdAt:t.updatedAt||Date.now(),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function cm(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),r=String(s?.answer||"").trim();if(!n||!r||lc(e,n))return null;const i=s.pendingPhase==="queued"?"queued":"pending",a=Number(s.answeredAt||0)||t.updatedAt||Date.now();return{id:`answered-question:${t.sessionId}:${n}:${a}`,role:"user",text:`The user was asked: "${n}"
|
|
27
27
|
The user responded: "${r}"`,time:"",createdAt:a,optimistic:!0,pendingPhase:i}}function dm(t,e){if(!t||!e?.id)return null;const s=String(e.text||"").trim();return s?{id:`pending-outbox:${t}:${e.id}`,role:"user",text:s,time:"",createdAt:Number(e.createdAt)||Date.now(),pendingPhase:e.phase==="cancelling"?"cancelling":e.phase==="rejected"?"rejected":e.phase==="queued"?"queued":"pending"}:null}function lc(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Qr(n?.text||"")?.question?.trim()===s):!1}function um(t){const e=String(t?.error||"").trim();if(!e)return null;const s=ri(t);if(!s)return null;const n=s==="failed",r=n?e:`${e}
|
|
28
28
|
|
|
@@ -79,19 +79,19 @@ ${r}`:"")}function Gt(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Ma
|
|
|
79
79
|
${r.validation.errors.map(a=>`[${a.code}] ${a.message}`).join(`
|
|
80
80
|
`)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${r?.message||r}${i}`})}}}openAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/open"})}openAdminUpdatePackage(e,s="user"){const n=String(e||"").trim();n&&this.dispatch({type:"admin/packages/addDialog/open",updateName:n,scope:s})}closeAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/close"})}setAdminAddPackageField(e,s){this.dispatch({type:"admin/packages/addDialog/setField",field:e,value:s})}async submitAdminAddPackage(){const e=this.getState().admin?.packages?.addDialog;if(!e?.open||e.submitting)return;if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Package upload is not available on this deployment."});return}const s=String(e.repoUrl||"").trim(),n=$l(s);if(n.error){this.dispatch({type:"admin/packages/addDialog/failed",error:n.error});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{let i=String(e.authToken||"").trim()||null,a="pat";!i&&n.kind==="ado"&&(this.dispatch({type:"admin/packages/addDialog/progress",message:"getting an Azure DevOps token for your account…"}),i=typeof this.transport.getRepoAccessToken=="function"?await this.transport.getRepoAccessToken("ado"):null,a="bearer");const{files:l}=await Wu(s,{token:i,tokenKind:a,onProgress:d=>this.dispatch({type:"admin/packages/addDialog/progress",message:d})});if(e.updateName){const d=zu(l);if(d&&d!==e.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${d}", not "${e.updateName}". Use Add package to publish it as its own package.`});return}}this.dispatch({type:"admin/packages/addDialog/progress",message:`publishing ${l.length} file(s)…`});const c=await this.transport.uploadAgentPackage(l,e.scope==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),c?.name&&await this.selectAdminPackage(c.name)}catch(r){const i=Array.isArray(r?.validation?.errors)?`
|
|
81
81
|
${r.validation.errors.map(a=>`[${a.code}] ${a.message}`).join(`
|
|
82
|
-
`)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${r?.message||r}${i}`})}}beginAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/beginEdit",draft:""})}setAdminGhcpKeyDraft(e,s=String(e||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:e,cursorIndex:s})}insertAdminGhcpKeyText(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(e||"").replace(/\r?\n/g,""),r=yt(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(r.prompt,r.cursor)}deleteAdminGhcpKeyChar(){const e=this.getState().admin?.ghcpKey;if(!e?.editing)return;const s=Tt(e.draft||"",e.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,Ae(n,(s.cursorIndex||0)+e))}moveAdminGhcpKeyCursorToBoundary(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,e==="start"?0:n.length)}cancelAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/cancelEdit"})}async saveAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}const n=String(this.getState().admin.ghcpKey.draft||"").trim();if(n.length===0){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Enter a key, or use Clear to remove the override."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const r=await this.transport.setSystemGitHubCopilotKey({key:n});this.dispatch({type:"admin/systemGhcpKey/saved",status:r})}else{const r=await this.transport.setCurrentUserGitHubCopilotKey({key:n});this.dispatch({type:"admin/ghcpKey/saved",profile:r})}}catch(r){this.dispatch({type:"admin/ghcpKey/saveFailed",error:r?.message||String(r)})}}async clearAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const n=await this.transport.setSystemGitHubCopilotKey({key:null});this.dispatch({type:"admin/systemGhcpKey/saved",status:n})}else{const n=await this.transport.setCurrentUserGitHubCopilotKey({key:null});this.dispatch({type:"admin/ghcpKey/saved",profile:n})}}catch(n){this.dispatch({type:"admin/ghcpKey/saveFailed",error:n?.message||String(n)})}}async openBudget({provider:e=void 0}={}){this.getState().admin?.visible&&this.closeAdminConsole(),this.dispatch({type:"ui/budgetOpen",open:!0,...e===void 0?{}:{provider:e}}),await this.loadProviderTable();const s=this.getState().budget||{};s.selectedProvider&&await Promise.all([this.loadProviderSeries(s.selectedProvider,s.selectedScope||"*"),this.loadProviderSystemUsage(s.selectedProvider,s.selectedScope||"*")])}closeBudget(){this.dispatch({type:"ui/budgetOpen",open:!1})}setBudgetTab(e){this.dispatch({type:"budget/tab",tab:e}),e==="summary"&&this.loadUsageSummary().catch(()=>{})}async setUsageSummaryFilter({days:e,providers:s,preset:n}={}){this.dispatch({type:"budget/summary/filter",days:e,providers:s,preset:n}),await this.loadUsageSummary()}async loadUsageSummary(){if(typeof this.transport.getProviderUsageSummary!="function"){this.dispatch({type:"budget/summary/failed",error:"The cluster summary is not available on this transport."});return}const e=this.getState().budget?.summary||{};this.dispatch({type:"budget/summary/loading"});try{const s=await this.transport.getProviderUsageSummary({days:e.days||14,...Array.isArray(e.providers)&&e.providers.length?{providers:e.providers}:{}});this.dispatch({type:"budget/summary/loaded",data:s,fetchedAt:Date.now()})}catch(s){this.dispatch({type:"budget/summary/failed",error:Es(s)})}}setBudgetOverall(e){const s=this.getState().budget?.overall===!0;this.dispatch({type:"budget/overall",...typeof e=="boolean"?{overall:e}:{}});const n=this.getState().budget||{};if(!(n.overall===s||!n.selectedProvider))return this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*")}async setBudgetRangeDays(e){const s=Number(e);if(!dn.includes(s))return;const n=this.getState().budget?.rangeDays??Ie;this.dispatch({type:"budget/rangeDays",rangeDays:s});const r=this.getState().budget||{};s===n||!r.selectedProvider||await Promise.all([this.loadProviderSeries(r.selectedProvider,r.selectedScope||"*"),this.loadProviderSystemUsage(r.selectedProvider,r.selectedScope||"*")])}async selectBudgetProvider(e,s="*"){this.dispatch({type:"budget/selectProvider",provider:e,scope:s});const n=this.getState().budget||{};n.selectedProvider&&await Promise.all([this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*"),this.loadProviderSystemUsage(n.selectedProvider,n.selectedScope||"*")])}async loadProviderTable(){if(!this._budgetReadable())return;this.dispatch({type:"budget/loading"});const[e,s]=await Promise.all([this._readBudgetPart(()=>this.transport.getProviderUsageGrid()),this._readBudgetPart(()=>this.transport.listPausedSessions())]);this._settleBudgetRead([["grid","the provider table",e,n=>n?.rows||[]],["paused","the paused sessions",s,n=>n?.sessions||[]]])}async refreshProviderTable(){await this.loadProviderTable();const e=this.getState().budget||{};e.selectedProvider&&await Promise.all([this.loadProviderSeries(e.selectedProvider,e.selectedScope||"*"),this.loadProviderSystemUsage(e.selectedProvider,e.selectedScope||"*")])}async loadProviderSeries(e,s="*"){const n=String(e??"").trim();if(!n||typeof this.transport.getProviderUsage!="function")return;const r=s&&s!=="*"?s:null,i=this.getState().budget?.overall===!0,a=this.getState().budget?.rangeDays??Ie;this.dispatch({type:"budget/series/loading",provider:n,scope:s,rangeDays:a});try{const l=await this.transport.getProviderUsage({days:a,provider:n,...r?{model:r}:{},chargeClass:"user",...i?{}:{mine:!0},dimension:"provider"});this.dispatch({type:"budget/series/loaded",provider:n,scope:s,rangeDays:a,days:Array.isArray(l?.daily)?l.daily:[]})}catch(l){this.dispatch({type:"budget/series/failed",provider:n,scope:s,rangeDays:a,error:Es(l)})}}async loadProviderSystemUsage(e,s="*"){const n=this.getState().auth?.authorization?.role,r=n==="admin"||n==="anonymous"||this.getState().admin?.profile?.isAdmin===!0,i=String(e??"").trim();if(!r||!i||typeof this.transport.getProviderUsage!="function")return;const a=s&&s!=="*"?s:null,l=this.getState().budget?.rangeDays??Ie;this.dispatch({type:"budget/systemUsage/loading",provider:i,scope:s,rangeDays:l});try{const c=await this.transport.getProviderUsage({days:l,provider:i,...a?{model:a}:{},chargeClass:"system",dimension:"model",limit:100});this.dispatch({type:"budget/systemUsage/loaded",provider:i,scope:s,rangeDays:l,report:c})}catch(c){this.dispatch({type:"budget/systemUsage/failed",provider:i,scope:s,rangeDays:l,error:Es(c)})}}async refreshBudgetPausesIfStale(e){if(typeof this.transport.listPausedSessions!="function")return;const s=this.getState();if(s.ui?.budgetOpen||!(Array.isArray(e)?e:[]).some(i=>i&&!i.isGroup&&i.status==="waiting"&&i.cronActive!==!0)&&(s.budget?.paused||[]).length===0)return;const r=Date.now();r-(this.budgetPauseReadAt||0)<6e4||(this.budgetPauseReadAt=r,await this.refreshPausedSessions({quiet:!0}).catch(()=>{}))}async refreshPausedSessions({quiet:e=!1}={}){if(typeof this.transport.listPausedSessions!="function"){if(e)return;this.dispatch({type:"budget/loadFailed",error:"Providers and budgets are not available on this deployment."});return}const s=await this._readBudgetPart(()=>this.transport.listPausedSessions());s.error&&e||this._settleBudgetRead([["paused","the paused sessions",s,n=>n?.sessions||[]]])}_budgetReadable(){return typeof this.transport.getProviderUsageGrid=="function"?!0:(this.dispatch({type:"budget/loadFailed",error:"Providers and budgets are not available on this deployment."}),!1)}async _readBudgetPart(e){try{return{value:await e(),error:null}}catch(s){return{value:null,error:Es(s)}}}_settleBudgetRead(e){const s={},n=[];for(const[a,l,c,d]of e)c.error?n.push({label:l,error:c.error}):s[a]=d(c.value);if(Object.keys(s).length===0){this.dispatch({type:"budget/loadFailed",error:n[0]?.error||"The read failed."});return}if(this.dispatch({type:"budget/loaded",...s}),n.length===0)return;const r=n.map(a=>`${a.label} could not be read: ${a.error}`).join(" "),i=e.some(([a,,l])=>a==="grid"&&l.error);this.dispatch(i?{type:"budget/loadFailed",error:r}:{type:"budget/pausedFailed",error:r})}async _runBudgetChange(e){try{const s=await e();await this.loadProviderTable();const n=this.getState().budget||{};return n.selectedProvider&&await this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*"),{ok:!0,error:null,code:null,result:s??null}}catch(s){const n=Es(s);return this.dispatch({type:"ui/status",text:n}),await this.loadProviderTable().catch(()=>{}),{ok:!1,error:n,code:s?.code||null,result:null}}}_refuseBudgetChange(e){return this.dispatch({type:"ui/status",text:e}),{ok:!1,error:e,code:"UNSUPPORTED",result:null}}async createProvider({name:e,type:s,credentials:n,baseUrl:r=null,shared:i=!1}={}){const a=i?"createProvider":"createMyProvider";return typeof this.transport[a]!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport[a]({name:e,type:s,credentials:n,baseUrl:r}))}async deleteProvider(e,{shared:s=null}={}){const n=(this.getState().budget?.grid||[]).find(a=>a?.providerName===e&&a?.rowKind!=="model"),i=(s===null?n?.class==="shared":s===!0)?"deleteProvider":"deleteMyProvider";return typeof this.transport[i]!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport[i](e))}async setProviderLimit({provider:e,period:s,model:n=null,tokens:r}={}){return typeof this.transport.setProviderLimit!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderLimit({name:e,period:s,model:n,tokens:r}))}async removeProviderLimit({provider:e,period:s,model:n=null}={}){return typeof this.transport.removeProviderLimit!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.removeProviderLimit({name:e,period:s,model:n}))}async setProviderAllowance({provider:e,pct:s}={}){return typeof this.transport.setProviderAllowance!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderAllowance({name:e,pct:s}))}async setProviderHold({provider:e,untilUtc:s=null,release:n=!1}={}){return typeof this.transport.setProviderHold!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderHold({name:e,untilUtc:s,release:n}))}async setClusterDefault(e){return typeof this.transport.setClusterDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setClusterDefault(e))}async setMyDefault(e){return typeof this.transport.setMyDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setMyDefault(e))}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,r=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const i=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:i||[],fetchedAt:Date.now()})}catch(i){console.error("[executionHistory] fetch error:",i?.message||i),this.dispatch({type:"executionHistory/error",sessionId:e,error:i?.message||String(i),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=Qe(this.getState()),{force:s=!1}={}){const n=hn(this.getState(),e);return n.length===0?e==="allSessions"?[]:null:e==="allSessions"||n.length>1?Promise.allSettled(n.map(r=>this.ensureFilesForSession(r,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const e=Et(this.getState());return!e?.sessionId||!e?.filename?null:this.ensureFilePreview(e.sessionId,e.filename).catch(()=>null)}async ensureFilesForSession(e,{force:s=!1}={}){if(!e||typeof this.transport.listArtifacts!="function")return null;const n=this.getState().files.bySessionId[e];if(!s&&n?.loading)return n;const r=Date.now()-(Number(n?.fetchedAt)||0);if(!s&&n?.loaded&&r<Dg)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const i=await this.transport.listArtifacts(e),a=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:i,fetchedAt:a});const l=this.getState().files.bySessionId[e];return l?.selectedFilename&&await this.ensureFilePreview(e,l.selectedFilename).catch(()=>{}),l}catch(i){return this.dispatch({type:"files/sessionError",sessionId:e,error:i?.message||String(i)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const r=this.getState().files.bySessionId[e],i=r?.previews?.[s];let a=Np(r?.entries,s);if(!n&&i?.loading||!n&&i&&(i.content!==void 0||i.error))return i;if(!a&&typeof this.transport.getArtifactMetadata=="function")try{a=await this.transport.getArtifactMetadata(e,s)}catch{a=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const l=a?.isBinary===!0?ga(s,"",a.contentType||"",a):ga(s,await this.transport.downloadArtifact(e,s),a?.contentType||"",a);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...l}),l}catch(l){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:l?.message||String(l)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(r=>({id:`${r.sessionId}/${r.filename}`,kind:"artifact",sessionId:r.sessionId,filename:r.filename}));for(const r of s||[]){const i=String(r?.href||"").trim();i&&n.push({id:`url:${i}`,kind:"url",href:i,text:String(r?.text||i).trim()||i})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:r}={}){const i=this.buildArtifactPickerItems(e,s);if(i.length===0)return null;const a=i.findIndex(l=>l.id===r);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:i,selectedIndex:a>=0?a:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const e=this.getState().ui.modal;return!e||e.type!=="artifactPicker"?null:e.items?.[e.selectedIndex||0]?.id||null}replaceArtifactPickerModal(e=null){const s=this.getState().ui.modal;if(!s||s.type!=="artifactPicker")return;const n=this.buildArtifactPickerModal({artifactLinks:s.artifactLinks||[],httpLinks:s.httpLinks||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:n})}async saveArtifactDownload(e,s){if(typeof this.transport.saveArtifactDownload!="function")return this.dispatch({type:"ui/status",text:"Artifact download is not supported by this transport"}),null;try{const n=await this.transport.saveArtifactDownload(e,s);this.dispatch({type:"files/downloaded",sessionId:e,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const r=this.getState().sessions.activeSessionId;return(e===r||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===r&&(this.dispatch({type:"files/select",sessionId:e,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(e,s,{force:!0}).catch(()=>null))),n}catch(n){return this.dispatch({type:"ui/status",text:`Download failed: ${n?.message||String(n)}`}),null}}async openSelectedFileInDefaultApp(){const e=this.getState(),s=Et(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Qe(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:r}=s,i=Qe(e);if(typeof this.transport.openPathInDefaultApp!="function"){this.dispatch({type:"ui/status",text:"Opening files in the default app is not supported by this transport"});return}let a=e.files.bySessionId[n]?.downloads?.[r]?.localPath||null;if(a||(this.dispatch({type:"ui/status",text:`Downloading ${r} to open it...`}),a=(await this.saveArtifactDownload(n,r))?.localPath||null),!a){this.dispatch({type:"ui/status",text:`Open failed: could not save ${r} locally`});return}try{await this.transport.openPathInDefaultApp(a),this.dispatch({type:"ui/status",text:i==="allSessions"?`Opened ${He(n)} ${r} in the default app`:`Opened ${r} in the default app`})}catch(l){this.dispatch({type:"ui/status",text:`Open failed: ${l?.message||String(l)}`})}}async downloadSelectedArtifact(){const e=Et(this.getState());if(!e?.sessionId||!e?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),null;this.dispatch({type:"ui/status",text:`Downloading ${e.filename}...`});const s=await this.saveArtifactDownload(e.sessionId,e.filename);return s?.localPath?(this.dispatch({type:"ui/status",text:`Downloaded ${e.filename}`}),s):null}toggleArtifactMark(e){e?.id&&this.dispatch({type:"files/toggleMark",artifactId:e.id})}markArtifactRange(e){if(!e?.id)return;const s=Rt(this.getState()),n=this.getState().files.markedIds||[],r=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,i=s.findIndex(u=>u.id===r),a=s.findIndex(u=>u.id===e.id);if(a<0)return;if(i<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[l,c]=i<=a?[i,a]:[a,i],d=s.slice(l,c+1).map(u=>u.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...d])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const r=new Set;let i=0;const a=[];for(const l of n){const c=String(l).indexOf("/");if(c<=0)continue;const d=l.slice(0,c),u=l.slice(c+1);try{await this.transport.deleteArtifact(d,u),this.dispatch({type:"files/deleted",sessionId:d,filename:u}),r.add(d),i+=1}catch(p){a.push(`${u}: ${p?.message||String(p)}`)}}for(const l of r)await this.ensureFilesForSession(l,{force:!0}).catch(()=>null);return this.dispatch({type:"files/clearMarks"}),this.dispatch({type:"ui/status",text:a.length>0?`Deleted ${i}, ${a.length} failed — ${a[0]}`:`Deleted ${i} artifact${i===1?"":"s"}`}),a.length===0}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=Et(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const r=Qe(s),i=r==="allSessions"?`${He(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${i}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteArtifact",sessionId:n.sessionId,filename:n.filename,previousFocus:s.ui.focusRegion}}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;try{await this.transport.deleteArtifact(n.sessionId,n.filename),this.dispatch({type:"files/deleted",sessionId:n.sessionId,filename:n.filename}),await this.ensureFilesForSession(n.sessionId,{force:!0}).catch(()=>null);const a=Et(this.getState());return a?.sessionId&&a?.filename&&await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>null),this.dispatch({type:"ui/status",text:r==="allSessions"?`Deleted ${He(n.sessionId)} ${n.filename}`:`Deleted ${n.filename}`}),!0}catch(a){return this.dispatch({type:"ui/status",text:`Delete failed: ${a?.message||String(a)}`}),!1}}async openArtifactPicker(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=zm(e),r=qm(e);if(n.length===0&&r.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const i=this.getState().files.bySessionId[s]?.selectedFilename||null,a=i?`${s}/${i}`:null,l=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:r,previousFocus:e.ui.focusRegion,selectedId:a});if(!l){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:l}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const r=(e.items||[]).filter(a=>a.kind!=="artifact"?!1:!this.getState().files.bySessionId[a.sessionId]?.downloads?.[a.filename]?.localPath);if(r.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${r.length} artifacts...`});let i=0;for(const a of r)(await this.saveArtifactDownload(a.sessionId,a.filename))?.localPath&&(i+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${i}/${r.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=Qe(this.getState());await this.ensureFilesForScope(s);const n=Rt(this.getState());if(n.length===0)return;const r=Et(this.getState())||n[0],i=Math.max(0,n.findIndex(c=>c.id===r?.id)),a=Math.max(0,Math.min(n.length-1,i+e)),l=n[a];!l?.sessionId||!l?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:l.id}):this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${He(l.sessionId)} ${l.filename}`:`Previewing ${l.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=Qe(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:e.id}):this.dispatch({type:"files/select",sessionId:e.sessionId,filename:e.filename}),await this.ensureFilePreview(e.sessionId,e.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${He(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],r=!!e.files.fullscreen;if(!r&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const i=!r;this.dispatch({type:"files/fullscreen",fullscreen:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen files browser: ${n?.selectedFilename||""}`:"Closed fullscreen files browser"})}toggleFocusedPaneFullscreen(){const e=this.getState(),s=e.ui.focusRegion,n=e.ui.fullscreenPane||null,r=s===$.PROMPT?n:s;if(!Xh.has(r)||r===$.INSPECTOR&&e.ui.inspectorTab==="files")return;const i=n===r?null:r;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen ${r} pane`:`Closed fullscreen ${r} pane`}),!i&&s===$.PROMPT&&this.setFocus(r)}openFilesFilter(){const e=Qe(this.getState());this.dispatch({type:"ui/modal",modal:{type:"filesFilter",title:"Files Filter",previousFocus:this.getState().ui.focusRegion,selectedIndex:0,items:[{id:"scope",label:"Scope",description:"Choose whether the files browser shows the selected session tree or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session tree"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session tree"}`})}setNavigationIntent(e){const s=String(e||"").trim();if(!s)return;this.dispatch({type:"sessions/navigationIntent",sessionId:s});const n=this.getState();if(n.sessions.byId[s]){this.loadSession(s).catch(r=>{this.dispatch({type:"sessions/navigationIntentFailed",sessionId:s,errorKind:rr(r)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}async loadSession(e){if(!e)return;if(this.getState().sessions.activeSessionId!==e&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.getState().sessions.byId[e]?.isGroup){this.detachActiveSession();return}await this.ensureSessionHistory(e,{force:!0}),await this.syncSessionDetail(e).catch(()=>{}),this.attachActiveSession(e),this.ensureInspectorData().catch(()=>{}),this.dispatch({type:"canvas/snapshotInvalidate",sessionId:e}),this.ensureCanvasSnapshot(e).catch(()=>{})}reconcileOutboxAgainstEvent(e,s){if(!(!e||!s)){if(s.eventType==="user.message"){const n=s?.data?.content,r=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(i=>typeof i=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(r.length>0)for(const i of r)this.acknowledgeOutboxPrompt(e,n,i);else typeof n=="string"&&n.trim()&&this.acknowledgeOutboxPrompt(e,n);return}if(s.eventType==="pending_messages.cancelled"){const n=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(r=>typeof r=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];this.acknowledgeCancelledOutboxPrompt(e,n)}}}maybeRevealPresentedArtifact(e,s){const n=String(s?.data?.filename||"").trim();if(!n||e!==this.getState().sessions.activeSessionId)return!1;const r=s?.createdAt?Date.parse(s.createdAt):Number.NaN;if(Number.isFinite(r)&&Date.now()-r>ar)return!1;const i=s?.data?.fullscreen===!0;return this.revealArtifact(e,n,i?{fullscreen:!0}:{pane:!0}).catch(()=>{}),!0}applyCanvasUpdate(e,s){const n=Number(s?.data?.rev);if(!e||!Number.isFinite(n)||n<=0)return!1;const r=Number(s?.data?.slot),i=Number.isInteger(r)&&r>=1&&r<=5?r:1;this.dispatch({type:"canvas/updated",sessionId:e,slot:i,...typeof s?.data?.name=="string"?{name:s.data.name}:{},rev:n,note:typeof s?.data?.note=="string"?s.data.note:"",sizeBytes:s?.data?.sizeBytes,responseContract:s?.data?.responseContract});const a=this.getState();if(e!==a.sessions.activeSessionId||a.canvas.prefs[Ze(e,i)]?.optedOut)return!0;const l=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(l)&&Date.now()-l>ar||this.dispatch({type:"canvas/flip",sessionId:e,slot:i}),!0}submitCanvasAction(e,s){if(!e)return Promise.resolve({ok:!1,reason:"no session"});const n=this.getState().canvas.bySessionId[e]?.responseContract||null,r=nu(n,s);if(!r.ok)return Promise.resolve(r);this.canvasActionLimiters||(this.canvasActionLimiters=new Map);let i=this.canvasActionLimiters.get(e);if(i||(i=ou(),this.canvasActionLimiters.set(e,i)),!i())return Promise.resolve({ok:!1,reason:"rate limited"});const a=ru(r.action,r.data);return this.transport.sendMessage(e,a,{enqueueOnly:!0}).then(()=>(this.syncSessionEvents(e).catch(()=>{}),{ok:!0,action:r.action})).catch(l=>({ok:!1,reason:l?.message||String(l)}))}async ensureCanvasSnapshot(e){if(e&&!this.getState().canvas.bySessionId[e]?.snapshotLoaded){if(typeof this.transport.getSessionEventsBefore!="function"){this.dispatch({type:"canvas/snapshot",sessionId:e,rev:0});return}try{const s=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_updated"]),n=new Map;for(const i of Array.isArray(s)?s:[]){const a=Number(i?.data?.slot)||1,l=Number(i?.data?.rev)||0;(!n.has(a)||l>(Number(n.get(a)?.data?.rev)||0))&&n.set(a,i)}n.has(1)||n.set(1,null);let r=!1;for(const[i,a]of n){const l=Number(a?.data?.rev)||0;l>0&&(r=!0),this.dispatch({type:"canvas/snapshot",sessionId:e,slot:i,rev:l,...typeof a?.data?.name=="string"?{name:a.data.name}:{},note:typeof a?.data?.note=="string"?a.data.note:"",sizeBytes:a?.data?.sizeBytes,responseContract:a?.data?.responseContract})}if(r){const i=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_data"]).catch(()=>[]),a=new Map;for(const l of Array.isArray(i)?i:[]){const c=Number(l?.data?.slot)||1,d=Number(l?.data?.dataRev)||0;(!a.has(c)||d>(Number(a.get(c)?.data?.dataRev)||0))&&a.set(c,l)}for(const[l,c]of a)c?.data?.dataRev&&this.dispatch({type:"canvas/data",sessionId:e,slot:l,dataRev:Number(c.data.dataRev),payload:c.data.payload,note:typeof c.data.note=="string"?c.data.note:""})}}catch{}}}applyCanvasPresented(e,s){const n=Number(s?.data?.slot),r=Number.isInteger(n)&&n>=1&&n<=5?n:1;if(!e)return!1;const i=this.getState();if(e!==i.sessions.activeSessionId||i.canvas.prefs[Ze(e,r)]?.optedOut)return!1;const a=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(a)&&Date.now()-a>ar?!1:(this.dispatch({type:"canvas/flip",sessionId:e,slot:r}),!0)}subscribeCanvasKv(e,s){if(!e||typeof s!="function")return()=>{};this._canvasKvListeners||(this._canvasKvListeners=new Map),this._canvasKvListeners.has(e)||this._canvasKvListeners.set(e,new Set);const n=this._canvasKvListeners.get(e);return n.add(s),()=>{n.delete(s),n.size===0&&this._canvasKvListeners.delete(e)}}applyCanvasDataEvent(e,s){this.dispatch({type:"canvas/data",sessionId:e,slot:Number(s?.data?.slot)||1,dataRev:Number(s?.data?.dataRev),payload:s?.data?.payload,...Number.isFinite(Number(s?.data?.planeSeq))?{planeSeq:Number(s.data.planeSeq)}:{},...s?.data?.patch&&typeof s.data.patch=="object"?{patch:s.data.patch}:{},note:typeof s?.data?.note=="string"?s.data.note:""})}mergeSessionEvent(e,s){if(!e||!s)return!1;if(s.transient===!0){if(s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),s.eventType==="session.canvas_kv"){const c=this._canvasKvListeners?.get(e);if(c)for(const d of c)try{d(s.data)}catch{}}return s.eventType==="session.canvas_plane_released"&&this.dispatch({type:"canvas/planeReleased",sessionId:e}),!1}const r=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(r.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:oo(r,s)}),s.eventType==="session.input_required_started"&&s.data?.question&&this.dispatch({type:"sessions/merged",session:{sessionId:e,status:"input_required",pendingQuestion:{question:s.data.question,choices:Array.isArray(s.data.choices)?s.data.choices:void 0,allowFreeform:s.data.allowFreeform??!0}}}),s.eventType==="session.artifact_presented"&&this.maybeRevealPresentedArtifact(e,s),s.eventType==="session.canvas_updated"&&this.applyCanvasUpdate(e,s),s.eventType==="session.canvas_presented"&&this.applyCanvasPresented(e,s),s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),this.reconcileOutboxAgainstEvent(e,s);const i=rg(s),a=this.getState().sessions.byId[e]||{sessionId:e},l=il(a.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(i||l)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...i||{},...l?{contextUsage:l}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||a),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0);let r=null;try{r=await this.transport.getSessionEvents(e,n,200)}catch(i){if(ws(i)){this.handleSessionGone(e);return}throw i}if(!(!Array.isArray(r)||r.length===0))for(const i of r)this.mergeSessionEvent(e,i)}attachActiveSession(e){this.activeSessionSubscriptionId===e&&this.activeSessionUnsub||(this.detachActiveSession(),this.activeSessionSubscriptionId=e,this.activeSessionUnsub=this.transport.subscribeSession(e,s=>{this.mergeSessionEvent(e,s)}),this.syncSessionEvents(e).catch(()=>{}))}scheduleSessionDetailSync(e,s=250){typeof this.transport.getSession!="function"||!e||vs(e)||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=e,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(e=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,e))}async syncSessionDetail(e){if(typeof this.transport.getSession!="function"||!e||vs(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(i){if(ws(i)){this.handleSessionGone(e);return}throw i}if(!s)return;const n=this.getState().sessions.byId[e]||null,r=lg(n,s);(r||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:r||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=this.applyActiveGroupDefault(s),r=await this.transport.createSessionForAgent(e,n);return this._recordAgentPickerUse(e),await this.placeCreatedSessionInGroup(r,n.groupId??null),await this.refreshSessions(),await this.loadSession(r.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created ${oa(e,s.title)} session ${r.sessionId.slice(0,8)}`}),r}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId&&!e.sessions.listDeselected?[e.sessions.activeSessionId]:[];return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:s).map(r=>e.sessions.byId[r]).filter(r=>r&&!r.isSystem&&!r.isGroup&&!r.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0){const c=e.sessions.activeSessionId?e.sessions.byId[e.sessions.activeSessionId]:null;return c?.isGroup&&c.groupId?this.openRenameGroupModal(c):this.openCreateEmptyGroupModal()}if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),r=s.map(c=>c.sessionId),i=s.length===1&&s[0].groupId||null,a=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group, then move the selected session(s) into it.",groupId:null,memberCount:0},...(Array.isArray(n)?n:[]).map(c=>({id:c.groupId,kind:"group",label:c.title||c.groupId,description:c.description||"Move selected session(s) into this group.",groupId:c.groupId,memberCount:c.memberCount??0}))],l=i?Math.max(0,a.findIndex(c=>c.groupId===i)):Math.min(1,a.length-1);return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupPicker",title:s.length===1?"Move Session to Group":`Move ${s.length} Sessions to Group`,previousFocus:e.ui.focusRegion,sessionIds:r,sessionLabels:s.map(c=>c.title||c.sessionId.slice(0,8)),selectedIndex:l>=0?l:0,items:a}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),a}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}openRenameGroupModal(e){if(typeof this.transport.updateSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Group rename is not supported by this transport"}),null;const s=this.getState(),n=String(e.title||"").trim();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",mode:"rename",groupId:e.groupId,title:"Rename Group",previousFocus:s.ui.focusRegion,sessionIds:[],value:n,cursorIndex:n.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Edit the group name and press Enter"}),null}async openCreateEmptyGroupModal(){if(typeof this.transport.createSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"}),null;const e=this.getState();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.ui.focusRegion,sessionIds:[],value:"",cursorIndex:0,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"}),null}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const r=Array.from(new Set((Array.isArray(s)?s:[]).map(p=>String(p||"").trim()).filter(Boolean)));if(r.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let i=null;if(typeof this.transport.placeSessionsInGroup=="function")i=await this.transport.placeSessionsInGroup(r,e??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,r);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,r);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;const a=Array.isArray(i)?i.filter(Boolean):null,l=a?a.filter(p=>p.placed!==!0):[],c=a?a.filter(p=>p.placed===!0).length:r.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&c>0&&await this.loadSession(`group:${e}`).catch(()=>{});const d=e?`group ${n||e}`:"No Group",u=l.length>0?` · skipped ${l.length} (${Zh(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${d}${u}`:`No sessions moved to ${d}${u}`}),c>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const r=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],value:r,cursorIndex:r.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const r=Gt(e,n.maxLength||80),i=Ae(r,s);this.updateSessionGroupNameModal({value:r,cursorIndex:i})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=yt(s.value||"",s.cursorIndex||0,Gt(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(e.mode==="rename"&&e.groupId){const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.updateSessionGroup(e.groupId,{title:s}),this.dispatch({type:"ui/status",text:`Renamed group to "${s}"`}),await this.refreshSessions().catch(()=>{})}catch(i){this.dispatch({type:"ui/status",text:`Rename failed: ${i?.message||String(i)}`})}return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const r=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[]}),i=e.sessionIds||[];i.length===0?(this.dispatch({type:"ui/status",text:`Created group "${r.title||s}"`}),await this.refreshSessions().catch(()=>{})):await this.moveSessionsToGroup(r.groupId,i,{statusTitle:r.title||s})}catch(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null;if(!n?.isGroup)return e;const r=n.groupId||Vs(n.sessionId);return r?{...e,groupId:r}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}async openSessionAgentPicker(e={},s=null){const n=s??this.getState().ui.focusRegion,r=()=>{this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n)};let i=[];try{i=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[]}catch(h){r(),this.dispatch({type:"ui/status",text:`Could not load agents: ${h?.message||h}`});return}const l=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(i)||i.length===0){if(r(),!l){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const c=[];for(const h of i){const g=String(h?.name||"").trim();g&&c.push({id:g,kind:"agent",agentName:g,title:oa(g,h?.title),description:String(h?.description||"").trim(),tools:Array.isArray(h?.tools)?h.tools.filter(Boolean):[],splash:typeof h?.splash=="string"&&h.splash.trim()?h.splash:null,splashMobile:typeof h?.splashMobile=="string"&&h.splashMobile.trim()?h.splashMobile:null,initialPrompt:typeof h?.initialPrompt=="string"&&h.initialPrompt.trim()?h.initialPrompt:null,group:h?.source==="package"&&h?.scope==="user"&&h?.mine!==!1?"mine":"shared",packageName:h?.packageName||null,packageTitle:h?.packageTitle||null,packageSemver:h?.packageSemver||null,packageScope:h?.scope||null,ownerLabel:h?.ownerLabel||null,startedBy:Array.isArray(h?.startedBy)?h.startedBy.filter(Boolean):[],supportsDirectStart:typeof h?.supportsDirectStart=="boolean"?h.supportsDirectStart:void 0,builtin:h?.source!=="package"})}const d=[...c.filter(h=>h.group==="shared"),...c.filter(h=>h.group==="mine")],u=l?{id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null,supportsDirectStart:!0}:null,p=await this._loadAgentPickerUsage(),m=aa.includes(this._agentPickerSort)?this._agentPickerSort:_c,f=ca(d,{query:"",sort:m,usage:p,genericItem:u});this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",catalog:d,genericItem:u,items:f,query:"",sort:m,usage:p,selectedIndex:gg(f),previousFocus:n,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Ys(e?.supportedReasoningEfforts),a=s?.reasoningEffort||ta(e);if(!i.length||!a){await this.openContextTierPicker(e,s,r);return}const l=i.map(d=>({id:d,effort:d,label:d,isDefault:a===d})),c=Math.max(0,l.findIndex(d=>d.id===a));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Xs(e?.supportedContextTiers),a=s?.contextTier||tg(e);if(!i.length||!a){if(s?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s,r);return}const l=i.map(d=>({id:d,tier:d,tokenLimit:e?.contextWindowSizes?.[d]||null,label:ng(d,e?.contextWindowSizes?.[d]),isDefault:a===d})),c=Math.max(0,l.findIndex(d=>d.id===a));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a context window and press Enter"})}async openModelPicker(e={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(e);return}const s=await this.transport.listModels();if(!Array.isArray(s)||s.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const n=await this._resolveProviderNamespace(),r=n?.error?{refusal:n.error}:n?this._buildProviderPickerGroups(n,s,e):await this._buildCatalogPickerGroups(s,e);if(r.refusal){this.dispatch({type:"ui/status",text:r.refusal});return}const{items:i,groups:a,selectedIndex:l}=r;this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:i,groups:a,selectedIndex:l,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveProviderNamespace(){if(typeof this.transport.listProviders!="function")return null;try{const[e,s,n]=await Promise.all([this.transport.listProviders(),typeof this.transport.getProviderStatus=="function"?this.transport.getProviderStatus().catch(()=>null):null,typeof this.transport.getDefaults=="function"?this.transport.getDefaults().catch(()=>null):null]),r=Array.isArray(e?.providers)?e.providers:null;return r?{providers:r,status:Array.isArray(s?.providers)?s.providers:[],statusKnown:Array.isArray(s?.providers),defaults:n||null}:{error:"Runtime provider availability could not be verified. Refresh and try again."}}catch{return{error:"Runtime provider availability could not be verified. Refresh and try again."}}}_buildProviderPickerGroups(e,s,n){const r=e.providers.filter(m=>m.usableByMe!==!1);if(r.length===0)return{refusal:"No provider can pay for a session yet — add one of your own, or ask an admin for a shared one."};const i=new Map;for(const m of s){const f=m?.providerId;f&&(i.has(f)||i.set(f,[]),i.get(f).push(m))}const a=new Map(e.status.map(m=>[m.name,m])),l=Date.now(),c=[...r].sort((m,f)=>{const h=g=>g.isMyDefault===!0?0:g.isClusterDefault===!0?1:g.class==="personal"?2:3;return h(m)-h(f)||String(m.name).localeCompare(String(f.name))}),d=n?.model||e.defaults?.mine?.model||e.defaults?.cluster?.model||(typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0),u=[],p=c.map(m=>{const f=jg(m,a.get(m.name)||null,l),h=m.hasCredential===!1?`${m.name} has no credential`:null;return{providerId:m.name,providerType:m.typeId,providerClass:m.class,isClusterDefault:m.isClusterDefault===!0,isMyDefault:m.isMyDefault===!0,hasCredential:m.hasCredential!==!1,budgetState:f.state,budgetNote:f.text,models:(i.get(m.name)||i.get(m.typeId)||[]).map(g=>{const b=g.providerId===m.name&&g.qualifiedName?g.qualifiedName:`${m.name}:${g.modelName}`,y=h||(g.credentialAvailable===!1?`${m.name} has no usable credential or endpoint`:null),S={id:b,qualifiedName:b,modelName:g.modelName||b,providerId:m.name,providerType:m.typeId,providerClass:m.class,description:g.description||"",cost:g.cost||null,supportedReasoningEfforts:Ys(g.supportedReasoningEfforts),defaultReasoningEffort:g.defaultReasoningEffort||null,supportedContextTiers:Xs(g.supportedContextTiers),defaultContextTier:g.defaultContextTier||null,contextWindowSizes:g.contextWindowSizes||null,isDefault:d===b,budgetState:f.state,budgetNote:f.text,disabledReason:y,disabled:!!y};return u.push(S),S})}}).filter(m=>m.models.length>0);return u.length===0?{refusal:"No provider in your namespace offers a model to run."}:{items:u,groups:p,selectedIndex:ea(u,d)}}async _buildCatalogPickerGroups(e,s){const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,r=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():eg(e),i=await this._resolveGhcpUserKeySet(),a=[],l=r.map(c=>({providerId:c.providerId,providerType:c.type||c.providerType,models:(c.models||[]).map(d=>{const u=d.providerType||c.type||c.providerType,p=u==="github"&&d.credentialAvailable===!1&&i===!1,m={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||c.providerId,providerType:u,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:Ys(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Xs(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:p,disabledReason:p?"needs GitHub key":null,disabled:p};return a.push(m),m})})).filter(c=>c.models.length>0);return{items:a,groups:l,selectedIndex:ea(a,s?.model||n)}}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,r=n&&s.sessions.byId[n]||null;if(!r||r.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:r.model||void 0,reasoningEffort:r.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const r=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,i=e.contextTier?` · ${Tc[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${r}${i}`}),await this.refreshSessions();const a=this._onSwitchModelApplied;this._onSwitchModelApplied=null,typeof a=="function"&&a()}openHelpModal(){this.dispatch({type:"ui/modal",modal:{type:"help",title:"Keybindings",selectedIndex:0,previousFocus:this.getState().ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Keybindings — ? or Esc to close"})}openThemePicker(){const e=xp().map(r=>({id:r.id,label:r.label,description:r.description,group:r.group,page:r.page,terminal:r.terminal,tui:r.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(r=>r.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${He(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const r=String(e||"").replace(/\r?\n/g,""),i=Ae(r,s);this.updateArtifactUploadModal({value:r,cursorIndex:i})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=yt(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveArtifactUploadCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",e==="start"?0:String(s.value||"").length)}async ensurePromptAttachmentSessionId(){const e=this.getPromptAttachments()[0]?.sessionId||null;if(e)return this.getState().sessions.activeSessionId!==e&&await this.loadSession(e),e;const s=this.getState().sessions.activeSessionId;if(s)return s;const n=await this.createSession({});if(!n?.sessionId)throw new Error("Create a session before attaching files");return n.sessionId}async revealArtifact(e,s,{force:n=!0,fullscreen:r=!1,pane:i=!1}={}){const a=e||this.getState().sessions.activeSessionId,l=String(s||"").trim();if(!a||!l)return!1;if(this.dispatch({type:"files/previewOrigin",origin:"chat",restoreArtifactId:this.getState().files.selectedArtifactId||null}),this.getState().sessions.activeSessionId!==a&&await this.loadSession(a).catch(()=>null),i||this.dispatch({type:"ui/inspectorTab",inspectorTab:"files"}),i){const c=!!this.getCurrentLayout()?.rightHidden;c&&this.expandRightColumn(),this.dispatch({type:"files/pane",open:!0,restoresToHidden:c})}else this.setFocus("inspector");return await this.ensureFilesForSession(a,{force:n}).catch(()=>null),this.dispatch({type:"files/select",sessionId:a,filename:l}),await this.ensureFilePreview(a,l,{force:n}).catch(()=>null),r&&this.dispatch({type:"files/fullscreen",fullscreen:!0}),!0}async closeArtifactPane(){const e=this.getState().files.paneRestoresToHidden;return this.dispatch({type:"files/pane",open:!1}),this.dispatch({type:"files/fullscreen",fullscreen:!1}),this.dispatch({type:"files/previewOrigin",origin:null}),e&&this.collapseRightColumn(),this.dispatch({type:"ui/focus",focusRegion:$.CHAT}),{collapsedRightColumn:!!e}}expandRightColumn(){this.dispatch({type:"ui/paneAdjust",paneAdjust:0});const e=this.getCurrentLayout({paneAdjust:0}),s=this.getState().ui.focusRegion,n=it(s,e);n!==s&&this.setFocus(n)}collapseRightColumn(){const s=(this.getState().ui.layout||{}).viewportWidth??120,n=Math.floor(s*Tl),r=s-Ks-n;this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),a=this.getState().ui.focusRegion,l=it(a,i);l!==a&&this.setFocus(l)}async closeArtifactPreview(){const e=this.getState(),s=e.files.previewOrigin;if(this.dispatch({type:"files/fullscreen",fullscreen:!1}),s!=="chat"){this.dispatch({type:"files/previewOrigin",origin:null}),this.setFocus($.INSPECTOR);return}const n=e.files.restoreArtifactId;if(n){const r=String(n).indexOf("/");r>0&&this.dispatch({type:"files/select",sessionId:n.slice(0,r),filename:n.slice(r+1)})}else this.dispatch({type:"files/select",sessionId:null,filename:null});this.dispatch({type:"files/previewOrigin",origin:null}),this.dispatch({type:"ui/focus",focusRegion:$.CHAT})}async stepArtifactPreview(e){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(e);return}const n=Po(s);if(n.length===0){await this.moveFileSelection(e);return}const r=n.indexOf(s.files.selectedArtifactId),a=(r>=0?r:e>0?-1:n.length)+(e>0?1:-1);if(a<0||a>=n.length)return;const l=n[a],c=l.indexOf("/");if(c<=0)return;const d=l.slice(0,c),u=l.slice(c+1);this.dispatch({type:"files/select",sessionId:d,filename:u}),await this.ensureFilePreview(d,u).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?Po(s):Rt(s).map(i=>i.id);if(n.length===0)return!1;const r=n.indexOf(s.files.selectedArtifactId);return r<0?!0:e>0?r<n.length-1:r>0}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:e.filename}),await this.ensureFilePreview(r,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:r,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!e?.filename)throw new Error("Upload did not return a session id and filename");const i=da(e.filename),a=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),d=c.findIndex(p=>p?.sessionId===r&&p?.filename===e.filename);if(this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),d===-1||!a.includes(c[d]?.token||i)){const p=yt(a,l,`${i} `);this.setPrompt(p.prompt,p.cursor)}const u=d>=0?c.map((p,m)=>m===d?{...p,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}:p):[...c,{id:`${r}/${e.filename}`,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}];return this.setPromptAttachments(u),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(r,e.filename,{force:!0}).catch(()=>null),this.setFocus($.PROMPT),n||this.dispatch({type:"ui/status",text:d>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:r,existingAttachmentIndex:d,token:i}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(c=>c&&typeof c.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const r=s||await this.ensurePromptAttachmentSessionId(),i=[];let a=0,l=null;for(const c of n)try{const d=await this.transport.uploadArtifactFromFile(r,c);i.push(d),await this.finalizeArtifactUpload(d,{sessionId:r,suppressStatus:!0})}catch(d){a+=1,l=d}return i.length>0?this.dispatch({type:"ui/status",text:a>0?`Uploaded ${i.length}/${n.length} file(s); last error: ${l?.message||String(l)}`:i.length===1?`Uploaded ${i[0].filename}`:`Uploaded ${i.length} files`}):l&&this.dispatch({type:"ui/status",text:`Upload failed: ${l?.message||String(l)}`}),i}async uploadPromptAttachmentFiles(e=[]){return this.uploadArtifactFiles(e)}async confirmArtifactUploadModal(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"File path cannot be empty"});return}if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}this.dispatch({type:"ui/status",text:"Uploading artifact..."});try{const n=e.sessionId||await this.ensurePromptAttachmentSessionId(),r=await this.transport.uploadArtifactFromPath(n,s),i=await this.finalizeArtifactUpload(r,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(i,n)){this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${i.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const r=mg(n),i=Ci(n),a=pg(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:n.isGroup?"Rename folder":`Rename (${He(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:r,cursorIndex:r.length,agentTitlePrefix:i,currentTitle:String(n.title||"").trim(),maxLength:a,isGroup:!!n.isGroup}}),this.dispatch({type:"ui/status",text:n.isGroup?"Type a new folder name and press Enter to save":i?`Rename title for ${i}; the agent-name prefix stays fixed`:"Type a new session title and press Enter to save"})}async openTerminatePickerModal(){const e=this.getState(),s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[];if(e.sessions.selectMode&&s.length>=1){const i=this.getBulkSelectedSessionActions(e).eligible;if(i.length===0){this.dispatch({type:"ui/status",text:"No selected sessions can be terminated"});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Terminate Selected Sessions",previousFocus:e.ui.focusRegion,bulkCount:i.length,skippedCount:s.length-i.length,selectedIds:i.map(a=>a.sessionId)}}),this.dispatch({type:"ui/status",text:"Choose what to do with the selected sessions"});return}const n=e.sessions.activeSessionId;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}const r=e.sessions.byId[n];if(!r){this.dispatch({type:"ui/status",text:"No session selected"});return}if(r.isSystem){const i=String(r.title||r.agentId||n.slice(0,8)).trim();this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Restart System Session",sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:i,state:String(r.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(r.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Terminate (${He(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(r.title||"").trim(),state:String(r.state||"").trim(),canRegenerate:!1}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"?await this.deleteActiveSession():e==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],r=[...new Set(s.map(a=>String(a||"").trim()).filter(Boolean))].map(a=>e.sessions.byId[a]).filter(Boolean),i=r.filter(a=>!a.isSystem&&!a.isGroup);return{selected:r,eligible:i,skippedCount:r.length-i.length}}updateRenameSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setRenameSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="renameSession")return;const r=Gt(e,n.maxLength),i=Ae(r,s);this.updateRenameSessionModal({value:r,cursorIndex:i})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=yt(s.value||"",s.cursorIndex||0,Gt(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveRenameSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmRenameSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim();if(!n){this.dispatch({type:"ui/status",text:"Title cannot be empty"});return}const r=this.getState().sessions.byId[s],i=r?.isGroup?r.groupId||Vs(s):null;if(i){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const l=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),l&&this.setFocus(l),this.dispatch({type:"ui/status",text:`Renaming group ${i.slice(0,8)}...`});try{await this.transport.updateSessionGroup(i,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(c){this.dispatch({type:"ui/status",text:`Rename failed: ${c?.message||String(c)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const a=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),a&&this.setFocus(a),this.dispatch({type:"ui/status",text:`Renaming ${He(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${He(s)}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const r=Ut(["private","shared_read","shared_write"],n.visibility||"private",1);try{await this.transport.setSessionVisibility(s,r),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Visibility → ${r}`})}catch(i){this.dispatch({type:"ui/status",text:i?.message||String(i)})}}async openShareSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups can't be shared"});return}if(typeof this.transport.listSessionShares!="function"){this.dispatch({type:"ui/status",text:"Session sharing is not supported by this transport"});return}let r;try{r=await this.transport.listSessionShares(s)}catch(i){this.dispatch({type:"ui/status",text:i?.message||String(i)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${He(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(r)?r:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const r=Gt(e,120),i=Ae(r,s);this.updateShareSessionModal({value:r,cursorIndex:i})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=yt(s.value||"",s.cursorIndex||0,Gt(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveShareSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim(),r=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);return}const i=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(i!==null){const f=i.toLowerCase(),h=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===f||g.email&&String(g.email).toLowerCase()===f||g.displayName&&String(g.displayName).toLowerCase()===f);if(!h){this.dispatch({type:"ui/status",text:`No grant matching "${i}"`});return}this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.revokeSessionShare(s,{provider:h.provider,subject:h.subject}),this.dispatch({type:"ui/status",text:`Revoked ${i}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const a=n.split(/\s+/),l={r:"read",read:"read",w:"write",write:"write"},c=a.length>1?a[a.length-1].toLowerCase():null,d=c&&l[c]?l[c]:"read",u=c&&l[c]?a.slice(0,-1).join(" "):n,p=u.toLowerCase();let m=null;if(typeof this.transport.listKnownUsers=="function"){let f=[];try{f=await this.transport.listKnownUsers({limit:500})}catch{f=[]}const h=Array.isArray(f)?f:[];if(m=h.find(g=>g.displayName&&g.displayName.toLowerCase()===p||g.email&&g.email.toLowerCase()===p||g.subject&&g.subject.toLowerCase()===p)||null,!m){const g=h.filter(b=>b.displayName&&b.displayName.toLowerCase().includes(p)||b.email&&b.email.toLowerCase().includes(p)||b.subject&&b.subject.toLowerCase().includes(p));if(g.length===1)m=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${u}" is ambiguous (${g.length} matches)`});return}}}m||(m={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:u,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.grantSessionShare(s,{provider:m.provider,subject:m.subject,email:m.email??null,displayName:m.displayName??null},d),this.dispatch({type:"ui/status",text:`Granted ${d} to ${u}`})}catch(f){this.dispatch({type:"ui/status",text:f?.message||String(f)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}async _loadAgentPickerUsage(){try{if(typeof this.transport.getCurrentUserProfile!="function")return null;const s=(await this.transport.getCurrentUserProfile())?.profileSettings?.[ir];if(!s||typeof s!="object")return{};const n={};for(const[r,i]of Object.entries(s)){const a=Number(i);Number.isFinite(a)&&a>0&&(n[r]=a)}return n}catch{return null}}async _recordAgentPickerUse(e){const s=String(e||"").trim();if(s)try{if(typeof this.transport.getCurrentUserProfile!="function"||typeof this.transport.setCurrentUserProfileSettings!="function")return;const r={...(await this.transport.getCurrentUserProfile())?.profileSettings||{}},i={...r[ir]||{}};i[s]=(Number(i[s])||0)+1,r[ir]=i,this.dispatch({type:"ui/agentPickerUsage",usage:i}),await this.transport.setCurrentUserProfileSettings({settings:r})}catch{}}_refreshAgentPicker(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return;const n={...s,...e},r=ca(n.catalog||[],{query:n.query,sort:n.sort,usage:n.usage,genericItem:n.genericItem||null}),i=s.items?.[s.selectedIndex||0]?.id,a=r.findIndex(l=>l.id===i);this.dispatch({type:"ui/modal",modal:{...n,items:r,selectedIndex:a>=0?a:0}})}setAgentPickerQuery(e){this._refreshAgentPicker({query:String(e??"")})}setAgentPickerSort(e){aa.includes(e)&&(this._agentPickerSort=e,this._refreshAgentPicker({sort:e}))}moveAgentPickerSection(){return!1}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const i=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,i+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const i=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),a=s.items[i];if(!a||!Array.isArray(a.options)||a.options.length===0)return;const l=a.options.map(p=>p.id).filter(Boolean);if(l.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[a.id]||l[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||l[0]:this.getState().logs.filter?.[a.id]||l[0],d=Ut(l,c,e),u=a.options.find(p=>p.id===d)||a.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[a.id]:d},...s.type==="historyFormat"?{format:d}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(d).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${a.label} = ${u?.label||d}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:r})}moveModalPane(e){const s=this.getState().ui.modal;if(s?.type==="sessionAgentPicker"){this.moveAgentPickerSection(e);return}if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const r=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,i=s.items[r],a=s.type==="filesFilter"?this.getState().files.filter?.[i.id]||i.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||i.options?.[0]?.id:this.getState().logs.filter?.[i.id]||i.options?.[0]?.id,l=i.options?.find(c=>c.id===a)||i.options?.[0];this.dispatch({type:"ui/modalSelection",index:r}),this.dispatch({type:"ui/status",text:`Editing ${i.label}: ${l?.label||a||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="help"){this.closeModal();return}if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...e.extras||{}}):e.action==="deleteArtifact"?await this.deleteSelectedArtifact({confirmed:!0}):e.action==="deleteMarkedArtifacts"?await this.deleteMarkedArtifacts({confirmed:!0}):e.action==="deleteAdminProvider"&&await this.deleteSelectedAdminProvider();return}if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();return}if(e.type==="shareSession"){await this.confirmShareSessionModal();return}if(e.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(e.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(e.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(e.type==="filesFilter"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(e.type==="themePicker"){const s=e.items?.[e.selectedIndex||0],n=ft(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.disabled){this.dispatch({type:"ui/status",text:s.ghcpKeyMissing?"This model needs a GitHub Copilot provider — add your own in Admin Console first":"This model is not available"});return}const n=e.previousFocus;if(!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({},n);return}const r=ta(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:r??null},n);return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...r?{reasoningEffort:r}:{}},n);return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,r=e.sessionOptions||{};await this.openContextTierPicker(e.modelItem,{...r,...s?.id?{reasoningEffort:s.id}:{}},n);return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,r=e.sessionOptions||{},i={...r,...s?.id?{contextTier:s.id}:{}};if(r?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.switchSessionModel({...i,model:e.modelItem?.id||r.model});return}await this.openSessionAgentPicker(i,n);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0];if(s&&s.kind!=="generic"&&s.supportsDirectStart===!1){this.dispatch({type:"ui/status",text:`${s.title||s.agentName} is created by another agent and cannot be started on its own`});return}const n=e.previousFocus,r=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(r);return}await this.createSessionForAgent(s.agentName,{...r,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.splashMobile?{splashMobile:s.splashMobile}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=this.getPromptAttachments(),r=n[0]?.sessionId||null,i=kg(s,n);let a=e.sessions.activeSessionId;r&&(a=r,e.sessions.activeSessionId!==r&&await this.loadSession(r));let l=a&&e.sessions.byId[a]||null;if(a&&!l&&(l=this.getState().sessions.byId[a]||null),!a){const g=await this.createSession({});if(!g?.sessionId)return;a=g.sessionId,l=this.getState().sessions.byId[a]||null}const c=n.some(g=>g?.kind==="image");if(!i.trim()&&!c){a&&this.getPendingOutboxItems(a).length>0&&await this.dispatchPendingOutbox(a).catch(()=>{});return}const d=l?.pendingQuestion||null,u=!!d?.question,p=this.getPromptEditSessionMatch(a);if(p){const g=this.getSessionOutbox(a).find(b=>b.id===p.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(a).catch(()=>{});return}if(u&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),b={...d,answer:i,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:a,pendingQuestion:null,answeredPendingQuestion:b}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(a,i),this.dispatch({type:"sessions/merged",session:{sessionId:a,answeredPendingQuestion:{...b,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(a,100),this.syncSessionEvents(a).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:a,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:a,pendingQuestion:d}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(i,String(i||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const m=n.filter(g=>g?.kind==="image");let f=null;if(m.length>0){if(m.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const b=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${m.length} image${m.length>1?"s":""}...`});try{f=await this.uploadPendingImageAttachments(a,m,b.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const h=i.trim()?i:f&&f.length>0?"See the attached image(s).":i;this.queuePromptInOutbox(a,h,f?{attachments:f}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(a).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),r=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),i=this.getState().ui;if(!(i.prompt===n&&i.promptCursor===r)){if(i.promptEdit?.sessionId&&i.promptEdit?.itemId){const l=this.getSessionOutbox(i.promptEdit.sessionId).map(c=>c.id===i.promptEdit.itemId&&c.phase==="pending"&&c.attempted!==!0?{...c,text:n}:c);this.setSessionOutboxItems(i.promptEdit.sessionId,l)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:r}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=yt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=Tt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Cg(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,Ae(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,Lc(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Tg(s.prompt,s.promptCursor,e);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}e<0&&this.selectPreviousPendingPrompt()||e>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,r=e.prompt??n.prompt;return Cs({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??ts(r),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===$.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(3,s-2)}setViewport(e={}){const s=Math.max(40,Number(e.width)||120),n=Math.max(18,Number(e.height)||40),r=this.getState().ui.layout||{};(r.viewportWidth!==s||r.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const i=this.getCurrentLayout({width:s,height:n}),a=this.getState().ui.focusRegion,l=it(a,i);l!==a&&this.setFocus(l)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:it(e,this.getCurrentLayout()),requestedFocusRegion:e})}focusNext(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e),n=kr(e);this.setFocus(Ut(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e),n=kr(e);this.setFocus(Ut(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e);this.setFocus(Lu(s,e))}focusRight(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e);this.setFocus(Ou(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,r=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),a=this.getState().ui.focusRegion,l=it(a,i);l!==a&&this.setFocus(l)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:i});const a=this.getCurrentLayout({sessionPaneAdjust:i}),l=this.getState().ui.focusRegion,c=it(l,a);c!==l&&this.setFocus(c)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:i});const a=this.getCurrentLayout({activityPaneAdjust:i}),l=this.getState().ui.focusRegion,c=it(l,a);c!==l&&this.setFocus(c)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,i=n.viewportHeight??40,a=(l,c,d,u)=>{const p=Math.max(d,u);return Math.max(d,Math.min(p,(l||0)+c))};if(s===$.SESSIONS||s===$.CHAT){const l=_l(r),c=as+1,d=Math.min(Rl(i,r),r-xn-1),u=s===$.CHAT?-e:e,p=a(n.sessionPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:p})}else if(s===$.INSPECTOR||s===$.ACTIVITY){const l=Math.max(es,Math.floor(r*Ml)),c=es+1,d=r-nn-1,u=s===$.INSPECTOR?-e:e,p=a(n.activityPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:p})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),r=[],i=new Set;for(const a of n?.events||[]){if(a?.eventType!=="session.turn_completed")continue;const l=Number(a?.data?.turnIndex??a?.data?.iteration);!Number.isFinite(l)||i.has(l)||(i.add(l),r.push(l))}return r.sort((a,l)=>a-l),r}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),r=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[r]})}toggleSequenceTurnExpanded(){const e=this.getActiveSequenceCompletedTurns();if(e.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);e.includes(s)||(s=e[e.length-1],this.dispatch({type:"ui/sequenceSelectedTurn",turn:s}));const n=Array.isArray(this.getState().ui.sequenceExpandedTurns)?this.getState().ui.sequenceExpandedTurns.map(Number):[],r=n.includes(s)?n.filter(i=>i!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:r})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=Ut(lt,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=Ut(lt,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,r=e[(n+1)%e.length];this.setStatsViewMode(r)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){lt.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=ds(s);if(n.length===0)return;const r=s.sessions.activeSessionId||n[0].sessionId,i=Math.max(0,n.findIndex(c=>c.sessionId===r)),a=Math.max(0,Math.min(n.length-1,i+e)),l=n[a].sessionId;this.navigateToSession(l)}navigateToSession(e){e&&(this.getState().sessions.activeSessionId!==e&&(this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.sessionNavSettleTimer&&clearTimeout(this.sessionNavSettleTimer),this.sessionNavSettleTimer=setTimeout(()=>{this.sessionNavSettleTimer=null,this.loadSession(e).catch(()=>{})},Bg))}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===$.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(1,s-3)}async moveSessionPage(e){const s=this.getSessionPageSize();await this.moveSession(s*e)}inspectorUsesBottomScroll(){return Pg.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="activity"?!0:e==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(e,s=this.getState()){return this.paneUsesStickyBottomFollow(e,s)?s.ui.followBottom?.[e]!==!1:!1}getPaneVisualScrollOffset(e,s=this.getState()){const n=this.getPaneMaxScrollOffset(e,s),r=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-r):r}applyPaneVisualScrollOffset(e,s,n={},r=this.getState()){const i=this.getPaneMaxScrollOffset(e,r),a=n.fromViewport?Math.max(0,Number(s)||0):Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,r)){const l=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:a>=i;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:l}),this.dispatch({type:"ui/scroll",pane:e,offset:l?0:a}),a}return this.dispatch({type:"ui/scroll",pane:e,offset:a}),a}updatePaneScrollFromViewport(e,s,n={}){const r=this.getState();if(this.paneUsesStickyBottomFollow(e,r)){this.applyPaneVisualScrollOffset(e,s,{...n,fromViewport:!0},r);return}this.scrollPaneTo(e,s)}expandActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/expand",sessionId:e})}collapseActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/collapse",sessionId:e})}scrollPane(e,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const l=this.getPaneVisualScrollOffset(e,n),c=Math.max(0,Math.min(l-s,r));this.applyPaneVisualScrollOffset(e,c,{followBottom:c>=r},n);return}const i=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,r)),a=Math.max(0,Math.min(i+s,r));this.dispatch({type:"ui/scroll",pane:e,offset:a}),e==="chat"&&s>0?i>=r?this.handleChatTopHistoryScrollIntent(a).catch(()=>{}):a>=r&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(e,n),i=Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,i,{followBottom:i>=r},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:i}),e==="chat"&&(r>0&&i>=r?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad())}armChatTopHistoryLoad(){const e=this.getState().sessions.activeSessionId;e&&(this.chatTopHistoryLoadArmed=!0,this.chatTopHistoryLoadSessionId=e)}disarmChatTopHistoryLoad(){this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}async handleChatTopHistoryScrollIntent(e,s={}){const r=this.getState().sessions.activeSessionId;if(r){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==r)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:Kh,force:!0})}}artifactPreviewOwnsActivitySlot(e=this.getState()){return e.ui.inspectorTab==="files"&&!!e.files?.selectedArtifactId}focusIsArtifactList(e=this.getState()){return e.ui.focusRegion===$.INSPECTOR&&e.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const e=this.getState(),s=e.ui.focusRegion;return s===$.CHAT?"chat":s===$.ACTIVITY?this.artifactPreviewOwnsActivitySlot(e)?"filePreview":"activity":s===$.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(e){const s=this.getScrollablePaneForFocus();if(!s)return;if(this.paneUsesStickyBottomFollow(s)){this.scrollPane(s,e);return}const n=s==="inspector"&&this.inspectorUsesBottomScroll(),r=s==="inspector"||s==="filePreview";this.scrollPane(s,r&&!n?-e:e)}scrollCurrentPaneToTop(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,0,{followBottom:!1});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER);return}this.scrollPaneTo(e,0)}scrollCurrentPaneToBottom(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,Number.MAX_SAFE_INTEGER,{followBottom:!0});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,0);return}this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER)}async expandActiveHistory(){const e=this.getState().sessions.activeSessionId;e&&await this.expandSessionHistory(e)}getActiveChatRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.leftHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.leftWidth-4),r=Math.max(1,s.chatPaneHeight-2),i=mi(e,n),a=[...gi(e,n),...pi(e)],l=Math.min(Math.max(0,Math.floor(r*.34)),Wt(a,n)),c=Wt(i,n);return{contentWidth:n,contentHeight:Math.max(1,r-l),totalLines:c}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),r=Math.max(1,s.activityPaneHeight-2),i=e.sessions.activeSessionId,a={sessions:{activeSessionId:i,byId:i?{[i]:e.sessions.byId[i]||null}:{}},history:{bySessionId:i?new Map([[i,e.history.bySessionId.get(i)||null]]):new Map}},l=bi(a);return{contentWidth:n,contentHeight:r,totalLines:Wt(l.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),r=e.sessions.activeSessionId,i=r&&e.orchestration.bySessionId?.[r]||null,a={branding:e.branding,sessions:{activeSessionId:r,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:r&&i?{[r]:i}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},l=It(a,{width:n}),c=l.tabs.map(m=>({text:m===l.activeTab?`[${m}] `:`${m} `,color:m===l.activeTab?"magenta":"gray",bold:m===l.activeTab})),d=(l.lines||[]).map(m=>typeof m=="string"?{text:m,color:"white"}:m),u=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(m=>typeof m=="string"?{text:m,color:"white"}:m)]:[],p=l.activeTab==="sequence"?d:[c,...d];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:Wt(u,n),totalLines:Wt(p,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,r=n?s.totalWidth:s.rightWidth,i=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,a=Math.max(20,r-4),l=Math.max(8,a-4),c=e.sessions.activeSessionId,d=c&&e.sessions.byId[c]||null,u={sessions:{activeSessionId:c,byId:c&&d?{[c]:d}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},p=Si(u,{listWidth:l,previewWidth:l}),m=Math.max(9,i-4),f=Math.max(5,Math.min(10,Math.floor(m*.35)));let h=Math.max(5,Math.min(f,(p.listBodyLines||[]).length+2)),g=Math.max(5,m-h-1);const b=8;if(g<b){const y=b-g;h=Math.max(5,h-y),g=Math.max(5,m-h-1)}return{contentWidth:l,contentHeight:Math.max(1,g-2),totalLines:Wt(p.previewLines,l)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),r=Math.min(n.contentHeight,n.stickyLineCount||0),i=Math.max(0,n.contentHeight-r);return Math.max(0,n.totalLines-i)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e,s={}){const n=this.getState(),r=n.sessions.activeSessionId;if(!r)return;const i=n.history.bySessionId.get(r);if(!i?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(r))return;if(Number(i.loadedEventCount||0)>=Or){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const a=Array.isArray(i?.chat)&&i.chat.length>0;if(!s.force&&a){const{contentHeight:l,totalLines:c}=this.getActiveChatRenderMetrics(n),d=Math.max(0,c-l);if(e<d)return}await this.expandSessionHistory(r,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:lu})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),r=n.history.bySessionId.get(e),i=Math.max(we,Number(r?.loadedEventLimit??we)||we),a=we,l=Array.isArray(r?.events)&&r.events.length>0?Number(r.events[0]?.seq||0):0;if(!r?.hasOlderEvents||l<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const c=e===n.sessions.activeSessionId,d=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),u=c?this.getActiveChatRenderMetrics(n).totalLines:0,p=(async()=>{let m;const f=Math.max(1,Math.floor(Number(s.pages)||1)),h=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&l>0){m=r||Os([],{requestedLimit:i});for(let y=0;y<f;y+=1){const S=Array.isArray(m?.events)&&m.events.length>0?Number(m.events[0]?.seq||0):0;if(!m?.hasOlderEvents||S<=1){m={...m,hasOlderEvents:!1};break}if(Number(m.loadedEventCount||0)>=Or)break;const w=await this.transport.getSessionEventsBefore(e,S,a,h);if(!Array.isArray(w)||w.length===0){m={...m,hasOlderEvents:!1};break}const k=Os(w,{requestedLimit:a}),E=[...k.events||[],...m?.events||[]];if(m={chat:Zt([...k.chat||[],...m?.chat||[]]),activity:[...k.activity||[],...m?.activity||[]],events:E,lastSeq:m?.lastSeq||m?.events?.[m?.events?.length-1]?.seq||w[w.length-1]?.seq||0,loadedEventLimit:E.length,loadedEventCount:E.length,hasOlderEvents:w.length>=a&&Number(w[0]?.seq||0)>1},!m.hasOlderEvents)break}}else{const y=Tu(i);if(y<=i){this.dispatch({type:"ui/status",text:r?.hasOlderEvents?`Already showing a large recent history window (${i} events)`:"Already showing the oldest loaded history"});return}const S=await this.transport.getSessionEvents(e,void 0,y);m={...Os(S,{requestedLimit:y}),lastSeq:S[S.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:m});for(const y of m?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(r?.chat)&&r.chat.length>0;if(c&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&d>0&&!s.autoTriggered){const y=this.getState(),S=this.getActiveChatRenderMetrics(y).totalLines,w=Math.max(0,S-u);w>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:d+w})}const b=m.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${m.loadedEventCount} events loaded)`:`Loaded older history page (${m.loadedEventCount} events loaded)`:`Loaded full available history (${m.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:b}),m.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,p),p}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(a.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${a.length} selected session${a.length===1?"":"s"}?${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of a)try{await this.transport.cancelSession(p.sessionId),c+=1}catch(m){d.push(`${p.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${a.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(i?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const a=i.title||i.agentId||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${a}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(i.agentId||r,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${i.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=i?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${l}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(r),this.dispatch({type:"ui/status",text:`Cancelled ${r.slice(0,8)}`}),await this.refreshSessions()}updateConfirmExtras(e){const s=this.getState().ui.modal;!s||s.type!=="confirm"||this.dispatch({type:"ui/modal",modal:{...s,extras:{...s.extras||{},...e||{}}}})}async regenerateActiveSession({confirmed:e=!1,instructions:s="",distillMode:n="llm",distillerModel:r="",distillerEffort:i="",distillerContextTier:a=""}={}){const l=this.getState(),c=l.sessions.activeSessionId;if(!c)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const d=l.sessions.byId[c];if(d?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(d?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(d?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const u=d?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${u}"? The transcript is archived and distilled, then the session rebuilds fresh from it at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved. As an operator action this overrides the rate limits (cooldown / minimum age).`,confirmLabel:"Regenerate",action:"regenerateSession",sessionId:c,previousFocus:l.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const u=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...u?{instructions:u.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{},...r?{distillerModel:r}:{},...i?{distillerReasoningEffort:i}:{},...a?{distillerContextTier:a}:{}}),this.dispatch({type:"ui/status",text:`Regeneration requested for ${c.slice(0,8)} — rebuilding at the next boundary`})}catch(u){this.dispatch({type:"ui/status",text:`Regenerate failed: ${u?.message||String(u)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(r=>Array.isArray(r?.models)?r.models.map(i=>({...i,providerId:i.providerId||r.providerId})):[r]).filter(r=>r&&(r.qualifiedName||r.modelName)).map(r=>({qualifiedName:r.qualifiedName||r.modelName,modelName:r.modelName||r.qualifiedName,providerId:r.providerId||"",supportedReasoningEfforts:Array.isArray(r.supportedReasoningEfforts)?r.supportedReasoningEfforts:[],supportedContextTiers:Array.isArray(r.supportedContextTiers)?r.supportedContextTiers:[]}))}catch(e){return this.dispatch({type:"ui/status",text:`Could not load distiller models: ${e?.message||String(e)}`}),[]}}async stopActiveSessionTurn(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session to stop its turn."});return}if(typeof this.transport.stopSessionTurn!="function"){this.dispatch({type:"ui/status",text:"Stop turn is not supported by this transport"});return}if(this._stopTurnInFlight||(this._stopTurnInFlight=new Set),!this._stopTurnInFlight.has(s)){this._stopTurnInFlight.add(s),this.dispatch({type:"ui/status",text:`Stopping turn for ${s.slice(0,8)}…`});try{const i=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";i==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):i==="timeout"?this.dispatch({type:"ui/status",text:"Stop requested — waiting for the turn to unwind"}):this.dispatch({type:"ui/status",text:`Stopped turn for ${s.slice(0,8)}`})}catch(r){this.dispatch({type:"ui/status",text:`Stop turn failed: ${r?.message||r}`})}finally{this._stopTurnInFlight.delete(s)}await this.refreshSessions(),await this.refreshActiveSessionDetail?.().catch?.(()=>{})}}togglePinActiveSession(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n)return;if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be pinned."});return}if(!n.isGroup&&(n.parentSessionId||n.groupId)){this.dispatch({type:"ui/status",text:"Sessions inside groups or parents cannot be pinned."});return}const r=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:r?`Unpinned ${s.slice(0,8)}`:`Pinned ${s.slice(0,8)}`})}toggleSessionSelectMode(){const e=this.getState(),s=!e.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=e.sessions.activeSessionId;n&&e.sessions.byId[n]&&this.dispatch({type:"sessions/selectToggle",sessionId:n}),this.dispatch({type:"ui/status",text:"Select mode: space toggles, Ctrl+G moves, c cancels, V/esc exits"})}else this.dispatch({type:"ui/status",text:"Select mode off"})}toggleActiveSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId;s&&(e.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(e){const s=Array.isArray(e)?e:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(e="Completed by user",{confirmed:s=!1}={}){const n=this.getState(),r=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&r.length>=1){const{eligible:l,skippedCount:c}=this.getBulkSelectedSessionActions(n);if(l.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${l.length} selected session${l.length===1?"":"s"}? This will cascade to their sub-agents.${c>0?` (${c} selected row${c===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let d=0;const u=[];for(const m of l)try{await this.transport.completeSession(m.sessionId,e),d+=1}catch(f){u.push(`${m.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Completed ${d} session${d===1?"":"s"}`:`Completed ${d}/${l.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const i=this.getState().sessions.activeSessionId;if(!i)return;const a=this.getState().sessions.byId[i];if(a?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(a?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const l=a.title||a.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${l}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:i,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(a.agentId||i,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${a.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}if(a?.status==="completed"&&!a?.cronActive&&!a?.cronInterval){this.dispatch({type:"ui/status",text:`${i.slice(0,8)} is already completed`});return}if(!s){const l=a?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${l}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:i,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${i.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(i,e),await this.refreshSessions(),this.scheduleSessionDetailSync(i,100),this.scheduleSessionsRefresh(900)}catch(l){await this.loadSession(i).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${l?.message||String(l)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(a.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${a.length} selected session${a.length===1?"":"s"}? This action cannot be undone.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of a)try{await this.transport.deleteSession(p.sessionId),this.handleSessionGone(p.sessionId),c+=1}catch(m){d.push(`${p.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${a.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){const a=i.groupId||Vs(r);if(!a||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(i.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${i.title||a}" is not empty. Move all sessions out of the group before deleting it.`,confirmLabel:"OK",action:"alert",alert:!0,previousFocus:s.ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Move all sessions out of the group before deleting it."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Group",message:`Delete empty group "${i.title||a}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(a),this.dispatch({type:"ui/status",text:`Deleted group ${i.title||a}`}),await this.refreshSessions();return}if(i?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const a=i.title||i.agentId||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${a}" and start a fresh one? This removes the current orchestration immediately.`,confirmLabel:"Hard Delete & Restart",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(i.agentId||r,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${i.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=i?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${l}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(r),this.handleSessionGone(r),this.dispatch({type:"ui/status",text:`Deleted ${r.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case M.REFRESH:await this.refreshSessions();return;case M.NEW_SESSION:await this.openNewSessionFlow();return;case M.OPEN_MODEL_PICKER:await this.openModelPicker();return;case M.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case M.OPEN_THEME_PICKER:this.openThemePicker();return;case M.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case M.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case M.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case M.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case M.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case M.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case M.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case M.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case M.CLOSE_MODAL:this.closeModal();return;case M.MODAL_PREV:this.moveModalSelection(-1);return;case M.MODAL_NEXT:this.moveModalSelection(1);return;case M.MODAL_PANE_PREV:this.moveModalPane(-1);return;case M.MODAL_PANE_NEXT:this.moveModalPane(1);return;case M.MODAL_CONFIRM:await this.confirmModal();return;case M.SEND_PROMPT:await this.sendPrompt();return;case M.FOCUS_NEXT:this.focusNext();return;case M.FOCUS_PREV:this.focusPrev();return;case M.FOCUS_LEFT:this.focusLeft();return;case M.FOCUS_RIGHT:this.focusRight();return;case M.FOCUS_PROMPT:this.setFocus($.PROMPT);return;case M.FOCUS_SESSIONS:this.setFocus($.SESSIONS);return;case M.MOVE_SESSION_UP:await this.moveSession(-1);return;case M.MOVE_SESSION_DOWN:await this.moveSession(1);return;case M.EXPAND_SESSION:this.expandActiveSession();return;case M.COLLAPSE_SESSION:this.collapseActiveSession();return;case M.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case M.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case M.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case M.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case M.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case M.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case M.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case M.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case M.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case M.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case M.OPEN_HELP:this.openHelpModal();return;case M.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case M.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case M.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case M.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case M.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case M.OPEN_LOG_FILTER:this.openLogFilter();return;case M.OPEN_FILES_FILTER:this.openFilesFilter();return;case M.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case M.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case M.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case M.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case M.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case M.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case M.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case M.SCROLL_UP:this.scrollCurrentPane(1);return;case M.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case M.PAGE_UP:if(this.getState().ui.focusRegion===$.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case M.PAGE_DOWN:if(this.getState().ui.focusRegion===$.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case M.EXPAND_HISTORY:await this.expandActiveHistory();return;case M.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case M.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case M.CANCEL_SESSION:await this.cancelActiveSession();return;case M.STOP_TURN:await this.stopActiveSessionTurn();return;case M.DONE_SESSION:await this.completeActiveSession();return;case M.DELETE_SESSION:await this.deleteActiveSession();return;case M.REGENERATE_SESSION:await this.regenerateActiveSession();return;case M.PIN_SESSION:this.togglePinActiveSession();return;case M.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case M.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case M.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case M.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case M.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case M.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case M.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case M.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case M.OPEN_WORKSPACE:this.openWorkspace();return;case M.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case M.ADMIN_SHOW_GHCP:this.setAdminSection("providers");return;case M.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case M.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case M.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case M.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case M.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case M.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case M.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case M.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case M.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case M.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const e=this.getState().sessions.activeSessionId;if(!e){this.dispatch({type:"ui/status",text:"No session selected."});return}if(typeof this.transport.exportExecutionHistory!="function"){this.dispatch({type:"ui/status",text:"History export is not supported by this transport."});return}this.dispatch({type:"ui/status",text:"Exporting execution history..."});try{const s=await this.transport.exportExecutionHistory(e);s?.filename&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:e,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${e}/${s.filename}`}),await this.ensureFilePreview(e,s.filename,{force:!0}).catch(()=>null)),this.dispatch({type:"ui/status",text:s?.filename?`History saved as artifact ${s.filename}`:`History exported → ${s?.artifactLink||"artifact created"}`})}catch(s){this.dispatch({type:"ui/status",text:`Export failed: ${s?.message||String(s)}`})}}}function Fr(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Wg=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],zg=24,qg=32,Kg=6,ya=30,Vg=56,lr=.4,Yg=1.4,Xg=2;function Fc(t=[]){const e=Math.max(0,...t.map(h=>h.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),r=Array.from({length:e},()=>({max:0,longestToken:0,spaceCells:0}));for(let h=0;h<t.length;h+=1){const g=t[h];for(let b=0;b<e;b+=1){const y=Fr(g[b]||"");y.length>r[b].max&&(r[b].max=y.length),h>0&&/\s/.test(y)&&(r[b].spaceCells+=1);for(const S of y.split(/\s+/))S.length>r[b].longestToken&&(r[b].longestToken=S.length)}}let i=-1,a=0;for(let h=0;h<e;h+=1){const g=r[h];if(g.max<zg||g.spaceCells/n<.4)continue;const y=Fr(s[h]||"").toLowerCase(),S=Wg.some(k=>y.includes(k))?60:0,w=g.max+S;w>a&&(a=w,i=h)}if(i<0)return null;const l=r.map((h,g)=>g===i?0:Math.max(Kg,Math.min(h.max+2,qg),h.longestToken+2)),c=l.reduce((h,g)=>h+g,0),d=r[i],u=Math.max(ya,Math.min(d.max*.45,Vg,Math.max(ya,c*Yg))),p=l.map((h,g)=>g===i?u:h),m=p.reduce((h,g)=>h+g,0);if(m>0&&p[i]/m<lr){const h=m-p[i];p[i]=h*(lr/(1-lr))}const f=p.reduce((h,g)=>h+g,0);return f>0?{widths:p.map(h=>`${(h/f*100).toFixed(2)}%`),flexIndex:i,minWidth:`${Math.ceil(f+Xg)}ch`}:null}const Cn=0;function Ye(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(t[r],e[r]))return!1;return!0}function cr(){try{const t=globalThis?.process,e=t?.memoryUsage;if(typeof e?.rss=="function"){const s=Number(e.rss());return Number.isFinite(s)&&s>0?s:null}if(typeof e=="function"){const s=Number(e.call(t)?.rss);return Number.isFinite(s)&&s>0?s:null}}catch{}return null}function Qg(t){if(!Number.isFinite(t)||t<=0)return null;const e=Math.round(t/(1024*1024));return[{text:"rss ",color:"gray"},{text:`${e}M`,color:"white",bold:!0}]}function Zg(t){const e=t?.principal;if(!e)return null;const s=e.displayName||e.email||e.subject||null;return s?t?.authorization?.role==="admin"||Array.isArray(e.roles)&&e.roles.includes("admin")?`(*) ${s}`:s:null}function Jg(t,e=null,s=null){const n=[],r=typeof s=="string"?s.trim():"";r&&n.push({text:r,color:"yellow",bold:!0}),Array.isArray(t)&&t.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...t));const i=typeof e=="string"?e.trim():"";return i?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:i,color:"cyan",bold:!0}),n):n.length>0?n:null}function ey(t=2e3){const[e,s]=o.useState(()=>cr());return o.useEffect(()=>{if(cr()==null)return;const n=()=>{const i=cr();i!=null&&s(a=>a===i?a:i)};n();const r=setInterval(n,t);return()=>clearInterval(r)},[t]),o.useMemo(()=>Qg(e),[e])}function fs(t,e){return t&&e?{[t]:e}:{}}function ba(t){return typeof t=="string"?{text:t,color:"white"}:t}function $s(t,e,s,n,r,i){const a=(e.tabs||lt).map(p=>({text:p===e.activeTab?`[${p}] `:`${p} `,color:p===e.activeTab?"magenta":"gray",bold:p===e.activeTab})),l=(e.lines||[]).map(ba),c=(e.stickyLines||[]).map(ba),d=e.activeTab==="sequence"?[a,...c]:[],u=e.activeTab==="sequence"?l:[a,...l];return o.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:r,stickyLines:d,marginBottom:Cn,lines:u,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:i})}function Sa(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}o.memo(function({controller:e,maxRows:s,width:n,height:r,frame:i,versionLabel:a=null}){const l=tt(),c=ey(),d=ee(e,h=>({sessions:h.sessions,mode:h.connection?.mode||"local",brandingTitle:h.branding?.title||"PilotSwarm",focused:h.ui.focusRegion==="sessions",identityLabel:Zg(h.auth)}),Ye),u=o.useMemo(()=>Jg(c,a,d.identityLabel),[c,a,d.identityLabel]),p=o.useMemo(()=>({sessions:d.sessions,connection:{mode:d.mode},branding:{title:d.brandingTitle}}),[d.brandingTitle,d.mode,d.sessions]),m=o.useMemo(()=>Pr(p,s),[p,s]),f=o.useMemo(()=>m.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:m.map(h=>h.active?ql(h.runs,{preserveColors:!0}):h.runs),[m]);return o.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:u,color:"yellow",focused:d.focused,width:n,height:r,marginBottom:Cn,lines:f,paneId:"sessions",paneLabel:"Sessions",frame:i})});o.memo(function({controller:e,width:s,height:n,frame:r}){const i=tt(),a=ee(e,w=>{const k=w.sessions.activeSessionId;return{activeSessionId:k,activeSession:k&&w.sessions.byId[k]||null,activeHistory:k&&w.history.bySessionId.get(k)||null,activeOutbox:k&&w.outbox?.bySessionId?.[k]||null,authPrincipal:w.auth?.principal||null,branding:w.branding,connectionError:w.connection.error,connectionMode:w.connection.mode,chatScroll:w.ui.scroll.chat,focused:w.ui.focusRegion==="chat"}},Ye),l=Math.max(20,s-4),c=o.useMemo(()=>{const w=new Map;return a.activeSessionId&&a.activeHistory&&w.set(a.activeSessionId,a.activeHistory),{branding:a.branding,auth:{principal:a.authPrincipal},connection:{error:a.connectionError,mode:a.connectionMode},ui:{},sessions:{activeSessionId:a.activeSessionId,byId:fs(a.activeSessionId,a.activeSession)},history:{bySessionId:w},outbox:{bySessionId:a.activeSessionId&&a.activeOutbox?{[a.activeSessionId]:a.activeOutbox}:{}}}},[a.activeHistory,a.activeSessionId,a.activeSession,a.activeOutbox,a.authPrincipal,a.branding,a.connectionError,a.connectionMode]),d=o.useMemo(()=>mc(c,{width:l}),[l,c]),u=sl(!!d?.animateTitleRight),p=o.useMemo(()=>nl(d?.titleRight,u),[u,d?.titleRight]),m=!a.activeSessionId&&a.connectionError,f=o.useMemo(()=>m?[{kind:"markup",value:a.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:a.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:mi(c,l),[a.branding.splash,a.connectionError,l,c,m]),h=String(a.activeSession?.status||"").toLowerCase()==="running",g=tl(h),b=o.useMemo(()=>m?[]:pi(c,{spinnerFrame:g,maxWidth:l}),[c,m,g,l]),y=o.useMemo(()=>m?[]:gi(c,l),[c,m,l]),S=o.useMemo(()=>y.length>0||b.length>0?[...y,...b]:[],[y,b]);return o.createElement(i.Panel,{title:d.title,titleRight:p,color:d.color,focused:a.focused,width:s,height:n,lines:f,bottomStickyLines:S,scrollOffset:a.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:r})});const ty=o.memo(function({controller:e,width:s,height:n,shellTitle:r,focused:i=!1,frame:a,showFullscreenTitle:l=!1,embedded:c=!1}){const d=tt(),u=ee(e,_=>({activeSessionId:_.sessions.activeSessionId,activeSession:_.sessions.activeSessionId&&_.sessions.byId[_.sessions.activeSessionId]||null,sessionsFlat:_.sessions.flat,filesBySessionId:_.files.bySessionId,filesFullscreen:!!_.files.fullscreen,selectedArtifactId:_.files.selectedArtifactId,filesFilter:_.files.filter,filePreviewScroll:_.ui.scroll.filePreview}),Ye),p=Math.max(20,s-4),m=o.useMemo(()=>({sessions:{activeSessionId:u.activeSessionId,byId:u.activeSessionId&&u.activeSession?{[u.activeSessionId]:u.activeSession}:{},flat:u.sessionsFlat},files:{bySessionId:u.filesBySessionId,fullscreen:u.filesFullscreen,selectedArtifactId:u.selectedArtifactId,filter:u.filesFilter},ui:{scroll:{filePreview:u.filePreviewScroll}}}),[u]),f=o.useMemo(()=>Si(m,{listWidth:Math.max(8,p-4),previewWidth:Math.max(8,p-4)}),[p,m]),h=r||(l?f.fullscreenTitle:f.panelTitle||f.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),b=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(b,(f.listBodyLines||[]).length+2)),S=Math.max(5,g-y-1);const w=8;if(S<w){const _=w-S;y=Math.max(5,y-_),S=Math.max(5,g-y-1)}const k=Math.max(1,y-2),E=Math.max(0,f.selectedIndex-Math.floor(k/2)),x=!c&&a?{x:a.x+2,y:a.y+2,width:p,height:y}:null,v=!c&&a?{x:a.x+2,y:a.y+2+y+1,width:p,height:S}:null,P=lt.map(_=>({text:_==="files"?`[${_}] `:`${_} `,color:_==="files"?"magenta":"gray",bold:_==="files"})),N=o.createElement(d.Column,{width:p},o.createElement(d.Lines,{lines:[P]}),o.createElement(d.Panel,{title:f.listTitle,color:"gray",focused:!1,width:p,height:y,lines:f.listBodyLines||f.listLines.slice(1),scrollOffset:E,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:x}),o.createElement(d.Panel,{title:f.previewTitle,color:"gray",focused:!1,width:p,height:S,lines:f.previewLines,scrollOffset:f.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:v}));return c?N:o.createElement(d.Panel,{title:h,color:"magenta",focused:i,width:s,height:n,marginBottom:Cn,paneId:"inspector",paneLabel:"Inspector",frame:a},N)}),sy=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return o.createElement(a.Panel,{title:u.title,color:"magenta",focused:i.focused,width:s,height:n,marginBottom:Cn,paneId:"inspector",paneLabel:"Inspector",frame:r},o.createElement(ty,{controller:e,width:s,height:n,frame:r,focused:i.focused,embedded:!0}))}),ny=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,activeOrchestration:p.sessions.activeSessionId&&p.orchestration.bySessionId?.[p.sessions.activeSessionId]||null,histories:p.history.bySessionId,expandedTurns:p.ui.sequenceExpandedTurns,selectedTurn:p.ui.sequenceSelectedTurn}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},history:{bySessionId:c.histories},orchestration:{bySessionId:c.activeSessionId&&c.activeOrchestration?{[c.activeSessionId]:c.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[c.activeOrchestration,c.activeSession,c.activeSessionId,c.histories]),u=o.useMemo(()=>It(d,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,d,c.expandedTurns,c.selectedTurn]);return $s(a,u,i,s,n,r)}),ry=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,logs:p.logs}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)}),iy=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,executionHistory:p.executionHistory}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)}),oy=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,sessionsById:p.sessions.byId,sessionsFlat:p.sessions.flat,histories:p.history.bySessionId}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.histories},ui:{inspectorTab:"nodes"}}),[c.activeSessionId,c.histories,c.sessionsById,c.sessionsFlat]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)}),ay=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,sessionStats:p.sessionStats,fleetStats:p.fleetStats,statsViewMode:p.ui.statsViewMode}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},sessionStats:c.sessionStats,fleetStats:c.fleetStats,ui:{inspectorTab:"stats",statsViewMode:c.statsViewMode}}),[c.activeSession,c.activeSessionId,c.fleetStats,c.sessionStats,c.statsViewMode]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)});o.memo(function({controller:e,width:s,height:n,frame:r}){const i=ee(e,a=>({inspectorTab:a.ui.inspectorTab,inspectorScroll:a.ui.scroll.inspector,inspectorFollowBottom:a.ui.followBottom?.inspector!==!1,focused:a.ui.focusRegion==="inspector"}),Ye);return i.inspectorTab==="files"?o.createElement(sy,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="sequence"?o.createElement(ny,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="logs"?o.createElement(ry,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="history"?o.createElement(iy,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="stats"?o.createElement(ay,{controller:e,width:s,height:n,frame:r,meta:i}):o.createElement(oy,{controller:e,width:s,height:n,frame:r,meta:i})});o.memo(function({controller:e,width:s,height:n,maxLines:r,frame:i}){const a=tt(),l=ee(e,p=>{const m=p.sessions.activeSessionId;return{sessionsById:p.sessions.byId,activeSessionId:m,activeSession:m&&p.sessions.byId[m]||null,activeHistory:m&&p.history.bySessionId.get(m)||null,scroll:p.ui.scroll.activity,followBottom:p.ui.followBottom?.activity!==!1,focused:p.ui.focusRegion==="activity",inspectorTab:p.ui.inspectorTab,nodeMapSelectedNode:p.ui.nodeMapSelectedNode,adminWorkers:p.admin?.workers,branding:p.branding,historyBySessionId:p.history.bySessionId,sessionsFlat:p.sessions.flat}},Ye),c=l.inspectorTab==="nodes",d=o.useMemo(()=>{const p=new Map;return l.activeSessionId&&l.activeHistory&&p.set(l.activeSessionId,l.activeHistory),{branding:l.branding,admin:{workers:l.adminWorkers},ui:{nodeMapSelectedNode:l.nodeMapSelectedNode},sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:c?l.historyBySessionId:p}}},[l.activeHistory,l.activeSessionId,l.sessionsById,l.adminWorkers,l.branding,l.historyBySessionId,l.nodeMapSelectedNode,l.sessionsFlat,c]),u=o.useMemo(()=>c?fc(d):bi(d,r),[r,c,d]);return o.createElement(a.Panel,{title:u.title,color:"gray",focused:l.focused,width:s,height:n,lines:u.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:i})});o.memo(function({controller:e,rows:s}){const n=tt(),r=ee(e,i=>{const a=i.sessions.activeSessionId,l=a&&i.sessions.byId[a]||null,c=a&&i.outbox?.bySessionId?.[a]?i.outbox.bySessionId[a]:[];return{prompt:i.ui.prompt,promptCursor:i.ui.promptCursor,focused:i.ui.focusRegion==="prompt",answeringQuestion:!!l?.pendingQuestion?.question,editingPending:i.ui.promptEdit?.sessionId===a,hasOutbox:c.length>0,hasPendingOutbox:c.some(d=>d?.phase==="pending")}},Ye);return o.createElement(n.Input,{label:r.answeringQuestion?"answer":r.editingPending?"pending":"you",value:r.prompt,cursorIndex:r.promptCursor,focused:r.focused,placeholder:r.answeringQuestion?"Type an answer and press Enter":r.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":r.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});o.memo(function({controller:e}){const s=tt(),n=ee(e,u=>({connected:u.connection.connected,workersOnline:u.connection.workersOnline,focusRegion:u.ui.focusRegion,inspectorTab:u.ui.inspectorTab,fullscreenPane:u.ui.fullscreenPane||null,logsAvailable:u.logs.available,logsTailing:u.logs.tailing,filesFullscreen:!!u.files.fullscreen,mode:u.connection.mode,statusText:u.ui.statusText,modal:u.ui.modal,activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,selectedIds:u.sessions.selectedIds,selectMode:u.sessions.selectMode}),Ye),r=o.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,fullscreenPane:n.fullscreenPane,statusText:n.statusText,modal:n.modal},logs:{available:n.logsAvailable,tailing:n.logsTailing},files:{fullscreen:n.filesFullscreen},sessions:{activeSessionId:n.activeSessionId,selectedIds:n.selectedIds,selectMode:n.selectMode,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}}}),[n]),i=o.useMemo(()=>hf(r),[r]),a=typeof s.getViewport=="function"?s.getViewport():{width:120},l=Math.max(20,(a.width||120)-4),c=Math.min(Math.max(18,Math.floor(l*.45)),l-8),d=Math.max(8,l-c-3);return o.createElement(s.StatusLine,{left:Sa(i.left,d),right:Sa(i.right,c)})});const ly="modulepreload",cy=function(t){return"/"+t},va={},Dc=function(e,s,n){let r=Promise.resolve();if(s&&s.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");r=c(s.map(d=>{if(d=cy(d),d in va)return;va[d]=!0;const u=d.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":ly,u||(m.as="script"),m.crossOrigin="",m.href=d,l&&m.setAttribute("nonce",l),document.head.appendChild(m),u)return new Promise((f,h)=>{m.addEventListener("load",f),m.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return r.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})},dy=920,Bc=7,uy=19,Ti=.24,Hc=16,Uc=8,Pi=224,py=190,my=48,bt=16,jc=.5,ks=jc,fy=24,hy=700,gy=5e3,yy=new Set(["low","medium","high","xhigh"]),by=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Sy=["pilotswarm_theme","pilotswarm_session_owner_filter"],vy={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},wa={sequence:aS,logs:lS,nodes:cS,history:mS,files:fS,stats:hS};function wy(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const r=n.indexOf(e),a=((r===-1?0:r)+s+n.length)%n.length;return n[a]}function Ey(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function ky(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function xy(t){return typeof t?.transport?.listArtifacts=="function"}function Iy(t){return typeof t?.transport?.deleteArtifact=="function"}function Ay(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const Ny="Session link copied to clipboard",Gc="Artifact link copied to clipboard",Cy=140,Ty="Only people with access can open this link.";function Wc(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function Tn(t,e,{fullscreen:s=!0}={}){const n=Wc(t);return!n||!e?n:`${n}&artifact=${encodeURIComponent(e)}${s?"&view=full":""}`}let Pn=[];function Av(t){Pn=Array.isArray(t)?t:[]}function Sn(t){const e=Cc(Ai(t,Pn));navigator?.clipboard?.writeText&&navigator.clipboard.writeText(e).catch(()=>{})}function zc({url:t,keyPrefix:e,copied:s,onCopy:n}){const r=Ai(t,Pn),i=l=>l.currentTarget.select();if(r.length<=1)return o.createElement("div",{className:"ps-link-row"},o.createElement("input",{className:"ps-link-input",readOnly:!0,value:t,onFocus:i}),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(e,t)},s===e?"Copied":"Copy"));const a=`${e}:all`;return o.createElement("div",{className:"ps-link-origins"},r.map((l,c)=>{const d=`${e}:${c}`;return o.createElement("div",{className:"ps-link-origin",key:d},o.createElement("div",{className:"ps-link-origin-label"},l.label),o.createElement("div",{className:"ps-link-row"},o.createElement("input",{className:"ps-link-input",readOnly:!0,value:l.url,"aria-label":`${l.label} link`,onFocus:i}),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(d,l.url)},s===d?"Copied":"Copy")))}),o.createElement("div",{className:"ps-link-copy-all"},o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(a,Cc(r))},s===a?"Copied all":"Copy all")))}async function Py(t,e){try{const s=t.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(e))?.visibility||"private")==="private"){const r=typeof s.listSessionShares=="function"?await s.listSessionShares(e).catch(()=>[]):[];return!Array.isArray(r)||r.length===0}}catch{}return!1}function My(){if(!(typeof window>"u")){try{for(const t of by)window.localStorage.removeItem(t)}catch{}try{for(const t of Sy)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function Ft(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),typeof e.sessionDetailCollapsed=="boolean"&&(s.sessionDetailCollapsed=e.sessionDetailCollapsed),e.agentPickerUsage&&typeof e.agentPickerUsage=="object"&&!Array.isArray(e.agentPickerUsage)){const n={};for(const[i,a]of Object.entries(e.agentPickerUsage)){const l=Number(a);typeof i=="string"&&i&&Number.isFinite(l)&&l>0&&(n[i]=Math.min(Math.round(l),1e6))}const r=Object.entries(n).sort((i,a)=>a[1]-i[1]).slice(0,200);r.length>0&&(s.agentPickerUsage=Object.fromEntries(r))}if(typeof e.touchScale=="boolean"&&(s.touchScale=e.touchScale),typeof e.touchScaleMobile=="boolean"&&(s.touchScaleMobile=e.touchScaleMobile),Ee(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Ee(n,"includeShared")?n:{...n,includeShared:!0}}if(Ee(e,"layoutAdjustments")&&(s.layoutAdjustments=ei(e.layoutAdjustments)),Ee(e,"pinnedSessionIds")&&(s.pinnedSessionIds=cn(e.pinnedSessionIds)),Ee(e,"sessionOrder")&&(s.sessionOrder=ti(e.sessionOrder)),Ee(e,"collapsedSessionIds")&&(s.collapsedSessionIds=_y(e.collapsedSessionIds)),Ee(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return(e.rightPaneMode==="canvas"||e.rightPaneMode==="panes")&&(s.rightPaneMode=e.rightPaneMode),Ee(e,"desktopPanes")&&e.desktopPanes&&typeof e.desktopPanes=="object"&&(s.desktopPanes={canvasOpen:e.desktopPanes.canvasOpen===!0,diagnosticsOpen:e.desktopPanes.diagnosticsOpen===!0,zen:e.desktopPanes.zen===!0}),Ee(e,"canvasPrefs")&&(s.canvasPrefs=si(e.canvasPrefs)),s}function Ls(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function vn(){return Ls()?"touchScaleMobile":"touchScale"}function wn(){return Ls()?"touchScale":"touchScaleMobile"}function _y(t){if(t instanceof Set){const n=[];for(const r of t){const i=String(r||"").trim();i&&n.push(i)}return n.sort(),n}if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s.sort(),s}function Ee(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function dr(t,e=null,s=null,n=null){return Ft({themeId:t.themeId,[vn()]:t.touchScale,sessionDetailCollapsed:t.sessionDetailCollapsed,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust,canvasPaneAdjust:t.canvasPaneAdjust,diagnosticsPaneAdjust:t.diagnosticsPaneAdjust,diagnosticsSplitAdjust:t.diagnosticsSplitAdjust},pinnedSessionIds:t.pinnedIds,sessionOrder:t.manualOrder,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,...Ls()?{...s==="canvas"||s==="panes"?{rightPaneMode:s}:{},...n&&typeof n=="object"?{desktopPanes:n}:{}}:{rightPaneMode:t.canvasOpen?"canvas":"panes",desktopPanes:{canvasOpen:t.canvasOpen===!0,diagnosticsOpen:t.diagnosticsOpen===!0,zen:t.canvasZen===!0}},canvasPrefs:t.canvasPrefs,...typeof e=="boolean"?{[wn()]:e}:{},...t.agentPickerUsage&&typeof t.agentPickerUsage=="object"&&Object.keys(t.agentPickerUsage).length>0?{agentPickerUsage:t.agentPickerUsage}:{}})}function Ea(t,e=null,s=null){return Ft({themeId:t?.ui?.themeId,[vn()]:t?.ui?.touchScale,sessionDetailCollapsed:t?.ui?.sessionDetailCollapsed,sessionOwnerFilter:bn(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,...Ls()?s==="canvas"||s==="panes"?{rightPaneMode:s}:{}:{rightPaneMode:t?.ui?.rightPaneMode,desktopPanes:{canvasOpen:t?.ui?.canvasOpen===!0,diagnosticsOpen:t?.ui?.diagnosticsOpen===!0,zen:t?.ui?.canvasZen===!0}},canvasPrefs:t?.canvas?.prefs,...typeof e=="boolean"?{[wn()]:e}:{}})}function Ry(t,e){const s=Ft(t),n=Ft(e);return Ft({themeId:Ee(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Ee(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Ee(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Ee(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:Ee(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Ee(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Ee(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Ee(s,"desktopPanes")?{desktopPanes:s.desktopPanes}:{},...Ee(s,"rightPaneMode")?{rightPaneMode:s.rightPaneMode}:{},...Ee(s,"canvasPrefs")?{canvasPrefs:s.canvasPrefs}:{},...Ee(s,vn())?{touchScale:s[vn()]}:Ls()&&Ee(s,"touchScale")?{touchScale:s.touchScale}:{},...Ee(s,"sessionDetailCollapsed")?{sessionDetailCollapsed:s.sessionDetailCollapsed}:{},...Ee(s,"agentPickerUsage")?{agentPickerUsage:s.agentPickerUsage}:{}})}async function $y(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:Ft(e)})}function Mi(t){return xy(t)?lt:lt.filter(e=>e!=="files")}function Le(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(t[r],e[r]))return!1;return!0}function rs(t,e,s){return Math.max(e,Math.min(s,t))}const Qs=120,_i=640,Ri=320;function Dr(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Hc-Uc*2),n=s*Ti,r=Math.max(0,s-Pi);return{minAdjust:-n,maxAdjust:r-n}}function Ly(t,e){const s=Dr(t),n=Math.max(0,Number(t)||0),i=Math.max(0,n-Hc-Uc*2)*Ti;return rs(i+(Number(e)||0),0,i+s.maxAdjust)}function Oy(t){return t<=my?"hidden":t<=py?"compact":"wrap"}function qc(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:ts(t?.ui?.prompt||"")}function Mn(t){return Cs({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,qc(t),t.ui.layout?.sessionPaneAdjust??0)}function Fy(t,e,s=!1){return Math.max(20,t-(s?6:4))}function Kc({slack:t=1,debounceMs:e=120}={}){const[s,n]=o.useState(null),r=o.useRef({node:null,observer:null,timer:null,frame:null}),i=o.useCallback(a=>{const l=r.current;if(l.observer&&(l.observer.disconnect(),l.observer=null),l.timer&&(window.clearTimeout(l.timer),l.timer=null),l.frame&&(cancelAnimationFrame(l.frame),l.frame=null),l.node=a,!a||typeof window>"u"||typeof ResizeObserver>"u")return;const c=()=>{if(l.timer=null,l.node!==a||!a.isConnected)return;const u=a.querySelector(".ps-line")||a,p=window.getComputedStyle(u),m=document.createElement("span");m.style.cssText="position:absolute;visibility:hidden;white-space:pre;",m.style.fontFamily=p.fontFamily,m.style.fontSize=p.fontSize,m.style.fontWeight=p.fontWeight,m.style.letterSpacing=p.letterSpacing,m.textContent="0".repeat(100),a.appendChild(m);const f=m.getBoundingClientRect().width/100||0;if(m.remove(),!(f>0))return;const h=window.getComputedStyle(a),g=a.clientWidth-(parseFloat(h.paddingLeft)||0)-(parseFloat(h.paddingRight)||0);if(!(g>50))return;const b=Math.max(20,Math.floor(g/f)-t);n(y=>y===b?y:b)},d=()=>{l.timer&&window.clearTimeout(l.timer),l.timer=window.setTimeout(c,e)};l.frame=requestAnimationFrame(c),l.observer=new ResizeObserver(d);try{l.observer.observe(a,{box:"content-box"})}catch{l.observer.observe(a)}},[t,e]);return[s,i]}function je(t){const e=[],s=n=>{const r=String(n||"");return!r.includes("\\n")||r.includes(`
|
|
82
|
+
`)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${r?.message||r}${i}`})}}beginAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/beginEdit",draft:""})}setAdminGhcpKeyDraft(e,s=String(e||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:e,cursorIndex:s})}insertAdminGhcpKeyText(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(e||"").replace(/\r?\n/g,""),r=yt(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(r.prompt,r.cursor)}deleteAdminGhcpKeyChar(){const e=this.getState().admin?.ghcpKey;if(!e?.editing)return;const s=Tt(e.draft||"",e.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,Ae(n,(s.cursorIndex||0)+e))}moveAdminGhcpKeyCursorToBoundary(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,e==="start"?0:n.length)}cancelAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/cancelEdit"})}async saveAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}const n=String(this.getState().admin.ghcpKey.draft||"").trim();if(n.length===0){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Enter a key, or use Clear to remove the override."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const r=await this.transport.setSystemGitHubCopilotKey({key:n});this.dispatch({type:"admin/systemGhcpKey/saved",status:r})}else{const r=await this.transport.setCurrentUserGitHubCopilotKey({key:n});this.dispatch({type:"admin/ghcpKey/saved",profile:r})}}catch(r){this.dispatch({type:"admin/ghcpKey/saveFailed",error:r?.message||String(r)})}}async clearAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const n=await this.transport.setSystemGitHubCopilotKey({key:null});this.dispatch({type:"admin/systemGhcpKey/saved",status:n})}else{const n=await this.transport.setCurrentUserGitHubCopilotKey({key:null});this.dispatch({type:"admin/ghcpKey/saved",profile:n})}}catch(n){this.dispatch({type:"admin/ghcpKey/saveFailed",error:n?.message||String(n)})}}async openBudget({provider:e=void 0}={}){this.getState().admin?.visible&&this.closeAdminConsole(),this.dispatch({type:"ui/budgetOpen",open:!0,...e===void 0?{}:{provider:e}}),await this.loadProviderTable();const s=this.getState().budget||{};s.selectedProvider&&await Promise.all([this.loadProviderSeries(s.selectedProvider,s.selectedScope||"*"),this.loadProviderSystemUsage(s.selectedProvider,s.selectedScope||"*")])}closeBudget(){this.dispatch({type:"ui/budgetOpen",open:!1})}setBudgetTab(e){this.dispatch({type:"budget/tab",tab:e}),e==="summary"&&this.loadUsageSummary().catch(()=>{})}async setUsageSummaryFilter({days:e,providers:s,preset:n}={}){this.dispatch({type:"budget/summary/filter",days:e,providers:s,preset:n}),await this.loadUsageSummary()}async loadUsageSummary(){if(typeof this.transport.getProviderUsageSummary!="function"){this.dispatch({type:"budget/summary/failed",error:"The cluster summary is not available on this transport."});return}const e=this.getState().budget?.summary||{};this.dispatch({type:"budget/summary/loading"});try{const s=await this.transport.getProviderUsageSummary({days:e.days||14,...Array.isArray(e.providers)&&e.providers.length?{providers:e.providers}:{}});this.dispatch({type:"budget/summary/loaded",data:s,fetchedAt:Date.now()})}catch(s){this.dispatch({type:"budget/summary/failed",error:Es(s)})}}setBudgetOverall(e){const s=this.getState().budget?.overall===!0;this.dispatch({type:"budget/overall",...typeof e=="boolean"?{overall:e}:{}});const n=this.getState().budget||{};if(!(n.overall===s||!n.selectedProvider))return this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*")}async setBudgetRangeDays(e){const s=Number(e);if(!dn.includes(s))return;const n=this.getState().budget?.rangeDays??Ie;this.dispatch({type:"budget/rangeDays",rangeDays:s});const r=this.getState().budget||{};s===n||!r.selectedProvider||await Promise.all([this.loadProviderSeries(r.selectedProvider,r.selectedScope||"*"),this.loadProviderSystemUsage(r.selectedProvider,r.selectedScope||"*")])}async selectBudgetProvider(e,s="*"){this.dispatch({type:"budget/selectProvider",provider:e,scope:s});const n=this.getState().budget||{};n.selectedProvider&&await Promise.all([this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*"),this.loadProviderSystemUsage(n.selectedProvider,n.selectedScope||"*")])}async loadProviderTable(){if(!this._budgetReadable())return;this.dispatch({type:"budget/loading"});const[e,s]=await Promise.all([this._readBudgetPart(()=>this.transport.getProviderUsageGrid()),this._readBudgetPart(()=>this.transport.listPausedSessions())]);this._settleBudgetRead([["grid","the provider table",e,n=>n?.rows||[]],["paused","the paused sessions",s,n=>n?.sessions||[]]])}async refreshProviderTable(){await this.loadProviderTable();const e=this.getState().budget||{};e.selectedProvider&&await Promise.all([this.loadProviderSeries(e.selectedProvider,e.selectedScope||"*"),this.loadProviderSystemUsage(e.selectedProvider,e.selectedScope||"*")])}async loadProviderSeries(e,s="*"){const n=String(e??"").trim();if(!n||typeof this.transport.getProviderUsage!="function")return;const r=s&&s!=="*"?s:null,i=this.getState().budget?.overall===!0,a=this.getState().budget?.rangeDays??Ie;this.dispatch({type:"budget/series/loading",provider:n,scope:s,rangeDays:a});try{const l=await this.transport.getProviderUsage({days:a,provider:n,...r?{model:r}:{},chargeClass:"user",...i?{}:{mine:!0},dimension:"provider"});this.dispatch({type:"budget/series/loaded",provider:n,scope:s,rangeDays:a,days:Array.isArray(l?.daily)?l.daily:[]})}catch(l){this.dispatch({type:"budget/series/failed",provider:n,scope:s,rangeDays:a,error:Es(l)})}}async loadProviderSystemUsage(e,s="*"){const n=this.getState().auth?.authorization?.role,r=n==="admin"||n==="anonymous"||this.getState().admin?.profile?.isAdmin===!0,i=String(e??"").trim();if(!r||!i||typeof this.transport.getProviderUsage!="function")return;const a=s&&s!=="*"?s:null,l=this.getState().budget?.rangeDays??Ie;this.dispatch({type:"budget/systemUsage/loading",provider:i,scope:s,rangeDays:l});try{const c=await this.transport.getProviderUsage({days:l,provider:i,...a?{model:a}:{},chargeClass:"system",dimension:"model",limit:100});this.dispatch({type:"budget/systemUsage/loaded",provider:i,scope:s,rangeDays:l,report:c})}catch(c){this.dispatch({type:"budget/systemUsage/failed",provider:i,scope:s,rangeDays:l,error:Es(c)})}}async refreshBudgetPausesIfStale(e){if(typeof this.transport.listPausedSessions!="function")return;const s=this.getState();if(s.ui?.budgetOpen||!(Array.isArray(e)?e:[]).some(i=>i&&!i.isGroup&&i.status==="waiting"&&i.cronActive!==!0)&&(s.budget?.paused||[]).length===0)return;const r=Date.now();r-(this.budgetPauseReadAt||0)<6e4||(this.budgetPauseReadAt=r,await this.refreshPausedSessions({quiet:!0}).catch(()=>{}))}async refreshPausedSessions({quiet:e=!1}={}){if(typeof this.transport.listPausedSessions!="function"){if(e)return;this.dispatch({type:"budget/loadFailed",error:"Providers and budgets are not available on this deployment."});return}const s=await this._readBudgetPart(()=>this.transport.listPausedSessions());s.error&&e||this._settleBudgetRead([["paused","the paused sessions",s,n=>n?.sessions||[]]])}_budgetReadable(){return typeof this.transport.getProviderUsageGrid=="function"?!0:(this.dispatch({type:"budget/loadFailed",error:"Providers and budgets are not available on this deployment."}),!1)}async _readBudgetPart(e){try{return{value:await e(),error:null}}catch(s){return{value:null,error:Es(s)}}}_settleBudgetRead(e){const s={},n=[];for(const[a,l,c,d]of e)c.error?n.push({label:l,error:c.error}):s[a]=d(c.value);if(Object.keys(s).length===0){this.dispatch({type:"budget/loadFailed",error:n[0]?.error||"The read failed."});return}if(this.dispatch({type:"budget/loaded",...s}),n.length===0)return;const r=n.map(a=>`${a.label} could not be read: ${a.error}`).join(" "),i=e.some(([a,,l])=>a==="grid"&&l.error);this.dispatch(i?{type:"budget/loadFailed",error:r}:{type:"budget/pausedFailed",error:r})}async _runBudgetChange(e){try{const s=await e();await this.loadProviderTable();const n=this.getState().budget||{};return n.selectedProvider&&await this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*"),{ok:!0,error:null,code:null,result:s??null}}catch(s){const n=Es(s);return this.dispatch({type:"ui/status",text:n}),await this.loadProviderTable().catch(()=>{}),{ok:!1,error:n,code:s?.code||null,result:null}}}_refuseBudgetChange(e){return this.dispatch({type:"ui/status",text:e}),{ok:!1,error:e,code:"UNSUPPORTED",result:null}}async createProvider({name:e,type:s,credentials:n,baseUrl:r=null,shared:i=!1}={}){const a=i?"createProvider":"createMyProvider";return typeof this.transport[a]!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport[a]({name:e,type:s,credentials:n,baseUrl:r}))}async deleteProvider(e,{shared:s=null}={}){const n=(this.getState().budget?.grid||[]).find(a=>a?.providerName===e&&a?.rowKind!=="model"),i=(s===null?n?.class==="shared":s===!0)?"deleteProvider":"deleteMyProvider";return typeof this.transport[i]!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport[i](e))}async setProviderLimit({provider:e,period:s,model:n=null,tokens:r}={}){return typeof this.transport.setProviderLimit!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderLimit({name:e,period:s,model:n,tokens:r}))}async removeProviderLimit({provider:e,period:s,model:n=null}={}){return typeof this.transport.removeProviderLimit!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.removeProviderLimit({name:e,period:s,model:n}))}async setProviderAllowance({provider:e,pct:s}={}){return typeof this.transport.setProviderAllowance!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderAllowance({name:e,pct:s}))}async setProviderHold({provider:e,untilUtc:s=null,release:n=!1}={}){return typeof this.transport.setProviderHold!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderHold({name:e,untilUtc:s,release:n}))}async setClusterDefault(e){return typeof this.transport.setClusterDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setClusterDefault(e))}async setMyDefault(e){return typeof this.transport.setMyDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setMyDefault(e))}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,r=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const i=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:i||[],fetchedAt:Date.now()})}catch(i){console.error("[executionHistory] fetch error:",i?.message||i),this.dispatch({type:"executionHistory/error",sessionId:e,error:i?.message||String(i),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=Qe(this.getState()),{force:s=!1}={}){const n=hn(this.getState(),e);return n.length===0?e==="allSessions"?[]:null:e==="allSessions"||n.length>1?Promise.allSettled(n.map(r=>this.ensureFilesForSession(r,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const e=Et(this.getState());return!e?.sessionId||!e?.filename?null:this.ensureFilePreview(e.sessionId,e.filename).catch(()=>null)}async ensureFilesForSession(e,{force:s=!1}={}){if(!e||typeof this.transport.listArtifacts!="function")return null;const n=this.getState().files.bySessionId[e];if(!s&&n?.loading)return n;const r=Date.now()-(Number(n?.fetchedAt)||0);if(!s&&n?.loaded&&r<Dg)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const i=await this.transport.listArtifacts(e),a=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:i,fetchedAt:a});const l=this.getState().files.bySessionId[e];return l?.selectedFilename&&await this.ensureFilePreview(e,l.selectedFilename).catch(()=>{}),l}catch(i){return this.dispatch({type:"files/sessionError",sessionId:e,error:i?.message||String(i)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const r=this.getState().files.bySessionId[e],i=r?.previews?.[s];let a=Np(r?.entries,s);if(!n&&i?.loading||!n&&i&&(i.content!==void 0||i.error))return i;if(!a&&typeof this.transport.getArtifactMetadata=="function")try{a=await this.transport.getArtifactMetadata(e,s)}catch{a=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const l=a?.isBinary===!0?ga(s,"",a.contentType||"",a):ga(s,await this.transport.downloadArtifact(e,s),a?.contentType||"",a);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...l}),l}catch(l){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:l?.message||String(l)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(r=>({id:`${r.sessionId}/${r.filename}`,kind:"artifact",sessionId:r.sessionId,filename:r.filename}));for(const r of s||[]){const i=String(r?.href||"").trim();i&&n.push({id:`url:${i}`,kind:"url",href:i,text:String(r?.text||i).trim()||i})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:r}={}){const i=this.buildArtifactPickerItems(e,s);if(i.length===0)return null;const a=i.findIndex(l=>l.id===r);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:i,selectedIndex:a>=0?a:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const e=this.getState().ui.modal;return!e||e.type!=="artifactPicker"?null:e.items?.[e.selectedIndex||0]?.id||null}replaceArtifactPickerModal(e=null){const s=this.getState().ui.modal;if(!s||s.type!=="artifactPicker")return;const n=this.buildArtifactPickerModal({artifactLinks:s.artifactLinks||[],httpLinks:s.httpLinks||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:n})}async saveArtifactDownload(e,s){if(typeof this.transport.saveArtifactDownload!="function")return this.dispatch({type:"ui/status",text:"Artifact download is not supported by this transport"}),null;try{const n=await this.transport.saveArtifactDownload(e,s);this.dispatch({type:"files/downloaded",sessionId:e,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const r=this.getState().sessions.activeSessionId;return(e===r||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===r&&(this.dispatch({type:"files/select",sessionId:e,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(e,s,{force:!0}).catch(()=>null))),n}catch(n){return this.dispatch({type:"ui/status",text:`Download failed: ${n?.message||String(n)}`}),null}}async openSelectedFileInDefaultApp(){const e=this.getState(),s=Et(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Qe(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:r}=s,i=Qe(e);if(typeof this.transport.openPathInDefaultApp!="function"){this.dispatch({type:"ui/status",text:"Opening files in the default app is not supported by this transport"});return}let a=e.files.bySessionId[n]?.downloads?.[r]?.localPath||null;if(a||(this.dispatch({type:"ui/status",text:`Downloading ${r} to open it...`}),a=(await this.saveArtifactDownload(n,r))?.localPath||null),!a){this.dispatch({type:"ui/status",text:`Open failed: could not save ${r} locally`});return}try{await this.transport.openPathInDefaultApp(a),this.dispatch({type:"ui/status",text:i==="allSessions"?`Opened ${He(n)} ${r} in the default app`:`Opened ${r} in the default app`})}catch(l){this.dispatch({type:"ui/status",text:`Open failed: ${l?.message||String(l)}`})}}async downloadSelectedArtifact(){const e=Et(this.getState());if(!e?.sessionId||!e?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),null;this.dispatch({type:"ui/status",text:`Downloading ${e.filename}...`});const s=await this.saveArtifactDownload(e.sessionId,e.filename);return s?.localPath?(this.dispatch({type:"ui/status",text:`Downloaded ${e.filename}`}),s):null}toggleArtifactMark(e){e?.id&&this.dispatch({type:"files/toggleMark",artifactId:e.id})}markArtifactRange(e){if(!e?.id)return;const s=Rt(this.getState()),n=this.getState().files.markedIds||[],r=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,i=s.findIndex(u=>u.id===r),a=s.findIndex(u=>u.id===e.id);if(a<0)return;if(i<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[l,c]=i<=a?[i,a]:[a,i],d=s.slice(l,c+1).map(u=>u.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...d])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const r=new Set;let i=0;const a=[];for(const l of n){const c=String(l).indexOf("/");if(c<=0)continue;const d=l.slice(0,c),u=l.slice(c+1);try{await this.transport.deleteArtifact(d,u),this.dispatch({type:"files/deleted",sessionId:d,filename:u}),r.add(d),i+=1}catch(p){a.push(`${u}: ${p?.message||String(p)}`)}}for(const l of r)await this.ensureFilesForSession(l,{force:!0}).catch(()=>null);return this.dispatch({type:"files/clearMarks"}),this.dispatch({type:"ui/status",text:a.length>0?`Deleted ${i}, ${a.length} failed — ${a[0]}`:`Deleted ${i} artifact${i===1?"":"s"}`}),a.length===0}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=Et(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const r=Qe(s),i=r==="allSessions"?`${He(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${i}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteArtifact",sessionId:n.sessionId,filename:n.filename,previousFocus:s.ui.focusRegion}}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;try{await this.transport.deleteArtifact(n.sessionId,n.filename),this.dispatch({type:"files/deleted",sessionId:n.sessionId,filename:n.filename}),await this.ensureFilesForSession(n.sessionId,{force:!0}).catch(()=>null);const a=Et(this.getState());return a?.sessionId&&a?.filename&&await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>null),this.dispatch({type:"ui/status",text:r==="allSessions"?`Deleted ${He(n.sessionId)} ${n.filename}`:`Deleted ${n.filename}`}),!0}catch(a){return this.dispatch({type:"ui/status",text:`Delete failed: ${a?.message||String(a)}`}),!1}}async openArtifactPicker(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=zm(e),r=qm(e);if(n.length===0&&r.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const i=this.getState().files.bySessionId[s]?.selectedFilename||null,a=i?`${s}/${i}`:null,l=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:r,previousFocus:e.ui.focusRegion,selectedId:a});if(!l){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:l}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const r=(e.items||[]).filter(a=>a.kind!=="artifact"?!1:!this.getState().files.bySessionId[a.sessionId]?.downloads?.[a.filename]?.localPath);if(r.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${r.length} artifacts...`});let i=0;for(const a of r)(await this.saveArtifactDownload(a.sessionId,a.filename))?.localPath&&(i+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${i}/${r.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=Qe(this.getState());await this.ensureFilesForScope(s);const n=Rt(this.getState());if(n.length===0)return;const r=Et(this.getState())||n[0],i=Math.max(0,n.findIndex(c=>c.id===r?.id)),a=Math.max(0,Math.min(n.length-1,i+e)),l=n[a];!l?.sessionId||!l?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:l.id}):this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${He(l.sessionId)} ${l.filename}`:`Previewing ${l.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=Qe(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:e.id}):this.dispatch({type:"files/select",sessionId:e.sessionId,filename:e.filename}),await this.ensureFilePreview(e.sessionId,e.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${He(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],r=!!e.files.fullscreen;if(!r&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const i=!r;this.dispatch({type:"files/fullscreen",fullscreen:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen files browser: ${n?.selectedFilename||""}`:"Closed fullscreen files browser"})}toggleFocusedPaneFullscreen(){const e=this.getState(),s=e.ui.focusRegion,n=e.ui.fullscreenPane||null,r=s===$.PROMPT?n:s;if(!Xh.has(r)||r===$.INSPECTOR&&e.ui.inspectorTab==="files")return;const i=n===r?null:r;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen ${r} pane`:`Closed fullscreen ${r} pane`}),!i&&s===$.PROMPT&&this.setFocus(r)}openFilesFilter(){const e=Qe(this.getState());this.dispatch({type:"ui/modal",modal:{type:"filesFilter",title:"Files Filter",previousFocus:this.getState().ui.focusRegion,selectedIndex:0,items:[{id:"scope",label:"Scope",description:"Choose whether the files browser shows the selected session tree or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session tree"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session tree"}`})}setNavigationIntent(e){const s=String(e||"").trim();if(!s)return;this.dispatch({type:"sessions/navigationIntent",sessionId:s});const n=this.getState();if(n.sessions.byId[s]){this.loadSession(s).catch(r=>{this.dispatch({type:"sessions/navigationIntentFailed",sessionId:s,errorKind:rr(r)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}async loadSession(e){if(!e)return;if(this.getState().sessions.activeSessionId!==e&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.getState().sessions.byId[e]?.isGroup){this.detachActiveSession();return}await this.ensureSessionHistory(e,{force:!0}),await this.syncSessionDetail(e).catch(()=>{}),this.attachActiveSession(e),this.ensureInspectorData().catch(()=>{}),this.dispatch({type:"canvas/snapshotInvalidate",sessionId:e}),this.ensureCanvasSnapshot(e).catch(()=>{})}reconcileOutboxAgainstEvent(e,s){if(!(!e||!s)){if(s.eventType==="user.message"){const n=s?.data?.content,r=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(i=>typeof i=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(r.length>0)for(const i of r)this.acknowledgeOutboxPrompt(e,n,i);else typeof n=="string"&&n.trim()&&this.acknowledgeOutboxPrompt(e,n);return}if(s.eventType==="pending_messages.cancelled"){const n=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(r=>typeof r=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];this.acknowledgeCancelledOutboxPrompt(e,n)}}}maybeRevealPresentedArtifact(e,s){const n=String(s?.data?.filename||"").trim();if(!n||e!==this.getState().sessions.activeSessionId)return!1;const r=s?.createdAt?Date.parse(s.createdAt):Number.NaN;if(Number.isFinite(r)&&Date.now()-r>ar)return!1;const i=s?.data?.fullscreen===!0;return this.revealArtifact(e,n,i?{fullscreen:!0}:{pane:!0}).catch(()=>{}),!0}applyCanvasUpdate(e,s){const n=Number(s?.data?.rev);if(!e||!Number.isFinite(n)||n<=0)return!1;const r=Number(s?.data?.slot),i=Number.isInteger(r)&&r>=1&&r<=5?r:1;this.dispatch({type:"canvas/updated",sessionId:e,slot:i,...typeof s?.data?.name=="string"?{name:s.data.name}:{},rev:n,note:typeof s?.data?.note=="string"?s.data.note:"",sizeBytes:s?.data?.sizeBytes,responseContract:s?.data?.responseContract});const a=this.getState();if(e!==a.sessions.activeSessionId||a.canvas.prefs[Ze(e,i)]?.optedOut)return!0;const l=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(l)&&Date.now()-l>ar||this.dispatch({type:"canvas/flip",sessionId:e,slot:i}),!0}submitCanvasAction(e,s){if(!e)return Promise.resolve({ok:!1,reason:"no session"});const n=this.getState().canvas.bySessionId[e]?.responseContract||null,r=nu(n,s);if(!r.ok)return Promise.resolve(r);this.canvasActionLimiters||(this.canvasActionLimiters=new Map);let i=this.canvasActionLimiters.get(e);if(i||(i=ou(),this.canvasActionLimiters.set(e,i)),!i())return Promise.resolve({ok:!1,reason:"rate limited"});const a=ru(r.action,r.data);return this.transport.sendMessage(e,a,{enqueueOnly:!0}).then(()=>(this.syncSessionEvents(e).catch(()=>{}),{ok:!0,action:r.action})).catch(l=>({ok:!1,reason:l?.message||String(l)}))}async ensureCanvasSnapshot(e){if(e&&!this.getState().canvas.bySessionId[e]?.snapshotLoaded){if(typeof this.transport.getSessionEventsBefore!="function"){this.dispatch({type:"canvas/snapshot",sessionId:e,rev:0});return}try{const s=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_updated"]),n=new Map;for(const i of Array.isArray(s)?s:[]){const a=Number(i?.data?.slot)||1,l=Number(i?.data?.rev)||0;(!n.has(a)||l>(Number(n.get(a)?.data?.rev)||0))&&n.set(a,i)}n.has(1)||n.set(1,null);let r=!1;for(const[i,a]of n){const l=Number(a?.data?.rev)||0;l>0&&(r=!0),this.dispatch({type:"canvas/snapshot",sessionId:e,slot:i,rev:l,...typeof a?.data?.name=="string"?{name:a.data.name}:{},note:typeof a?.data?.note=="string"?a.data.note:"",sizeBytes:a?.data?.sizeBytes,responseContract:a?.data?.responseContract})}if(r){const i=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_data"]).catch(()=>[]),a=new Map;for(const l of Array.isArray(i)?i:[]){const c=Number(l?.data?.slot)||1,d=Number(l?.data?.dataRev)||0;(!a.has(c)||d>(Number(a.get(c)?.data?.dataRev)||0))&&a.set(c,l)}for(const[l,c]of a)c?.data?.dataRev&&this.dispatch({type:"canvas/data",sessionId:e,slot:l,dataRev:Number(c.data.dataRev),payload:c.data.payload,note:typeof c.data.note=="string"?c.data.note:""})}}catch{}}}applyCanvasPresented(e,s){const n=Number(s?.data?.slot),r=Number.isInteger(n)&&n>=1&&n<=5?n:1;if(!e)return!1;const i=this.getState();if(e!==i.sessions.activeSessionId||i.canvas.prefs[Ze(e,r)]?.optedOut)return!1;const a=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(a)&&Date.now()-a>ar?!1:(this.dispatch({type:"canvas/flip",sessionId:e,slot:r}),!0)}subscribeCanvasKv(e,s){if(!e||typeof s!="function")return()=>{};this._canvasKvListeners||(this._canvasKvListeners=new Map),this._canvasKvListeners.has(e)||this._canvasKvListeners.set(e,new Set);const n=this._canvasKvListeners.get(e);return n.add(s),()=>{n.delete(s),n.size===0&&this._canvasKvListeners.delete(e)}}applyCanvasDataEvent(e,s){this.dispatch({type:"canvas/data",sessionId:e,slot:Number(s?.data?.slot)||1,dataRev:Number(s?.data?.dataRev),payload:s?.data?.payload,...Number.isFinite(Number(s?.data?.planeSeq))?{planeSeq:Number(s.data.planeSeq)}:{},...s?.data?.patch&&typeof s.data.patch=="object"?{patch:s.data.patch}:{},note:typeof s?.data?.note=="string"?s.data.note:""})}mergeSessionEvent(e,s){if(!e||!s)return!1;if(s.transient===!0){if(s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),s.eventType==="session.canvas_kv"){const c=this._canvasKvListeners?.get(e);if(c)for(const d of c)try{d(s.data)}catch{}}return s.eventType==="session.canvas_plane_released"&&this.dispatch({type:"canvas/planeReleased",sessionId:e}),!1}const r=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(r.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:oo(r,s)}),s.eventType==="session.input_required_started"&&s.data?.question&&this.dispatch({type:"sessions/merged",session:{sessionId:e,status:"input_required",pendingQuestion:{question:s.data.question,choices:Array.isArray(s.data.choices)?s.data.choices:void 0,allowFreeform:s.data.allowFreeform??!0}}}),s.eventType==="session.artifact_presented"&&this.maybeRevealPresentedArtifact(e,s),s.eventType==="session.canvas_updated"&&this.applyCanvasUpdate(e,s),s.eventType==="session.canvas_presented"&&this.applyCanvasPresented(e,s),s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),this.reconcileOutboxAgainstEvent(e,s);const i=rg(s),a=this.getState().sessions.byId[e]||{sessionId:e},l=il(a.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(i||l)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...i||{},...l?{contextUsage:l}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||a),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0);let r=null;try{r=await this.transport.getSessionEvents(e,n,200)}catch(i){if(ws(i)){this.handleSessionGone(e);return}throw i}if(!(!Array.isArray(r)||r.length===0))for(const i of r)this.mergeSessionEvent(e,i)}attachActiveSession(e){this.activeSessionSubscriptionId===e&&this.activeSessionUnsub||(this.detachActiveSession(),this.activeSessionSubscriptionId=e,this.activeSessionUnsub=this.transport.subscribeSession(e,s=>{this.mergeSessionEvent(e,s)}),this.syncSessionEvents(e).catch(()=>{}))}scheduleSessionDetailSync(e,s=250){typeof this.transport.getSession!="function"||!e||vs(e)||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=e,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(e=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,e))}async syncSessionDetail(e){if(typeof this.transport.getSession!="function"||!e||vs(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(i){if(ws(i)){this.handleSessionGone(e);return}throw i}if(!s)return;const n=this.getState().sessions.byId[e]||null,r=lg(n,s);(r||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:r||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=this.applyActiveGroupDefault(s),r=await this.transport.createSessionForAgent(e,n);return this._recordAgentPickerUse(e),await this.placeCreatedSessionInGroup(r,n.groupId??null),await this.refreshSessions(),await this.loadSession(r.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created ${oa(e,s.title)} session ${r.sessionId.slice(0,8)}`}),r}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId&&!e.sessions.listDeselected?[e.sessions.activeSessionId]:[];return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:s).map(r=>e.sessions.byId[r]).filter(r=>r&&!r.isSystem&&!r.isGroup&&!r.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0){const c=e.sessions.activeSessionId?e.sessions.byId[e.sessions.activeSessionId]:null;return c?.isGroup&&c.groupId?this.openRenameGroupModal(c):this.openCreateEmptyGroupModal()}if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),r=s.map(c=>c.sessionId),i=s.length===1&&s[0].groupId||null,a=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group, then move the selected session(s) into it.",groupId:null,memberCount:0},...(Array.isArray(n)?n:[]).map(c=>({id:c.groupId,kind:"group",label:c.title||c.groupId,description:c.description||"Move selected session(s) into this group.",groupId:c.groupId,memberCount:c.memberCount??0}))],l=i?Math.max(0,a.findIndex(c=>c.groupId===i)):Math.min(1,a.length-1);return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupPicker",title:s.length===1?"Move Session to Group":`Move ${s.length} Sessions to Group`,previousFocus:e.ui.focusRegion,sessionIds:r,sessionLabels:s.map(c=>c.title||c.sessionId.slice(0,8)),selectedIndex:l>=0?l:0,items:a}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),a}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}openRenameGroupModal(e){if(typeof this.transport.updateSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Group rename is not supported by this transport"}),null;const s=this.getState(),n=String(e.title||"").trim();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",mode:"rename",groupId:e.groupId,title:"Rename Group",previousFocus:s.ui.focusRegion,sessionIds:[],value:n,cursorIndex:n.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Edit the group name and press Enter"}),null}async openCreateEmptyGroupModal(){if(typeof this.transport.createSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"}),null;const e=this.getState();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.ui.focusRegion,sessionIds:[],value:"",cursorIndex:0,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"}),null}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const r=Array.from(new Set((Array.isArray(s)?s:[]).map(p=>String(p||"").trim()).filter(Boolean)));if(r.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let i=null;if(typeof this.transport.placeSessionsInGroup=="function")i=await this.transport.placeSessionsInGroup(r,e??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,r);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,r);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;const a=Array.isArray(i)?i.filter(Boolean):null,l=a?a.filter(p=>p.placed!==!0):[],c=a?a.filter(p=>p.placed===!0).length:r.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&c>0&&await this.loadSession(`group:${e}`).catch(()=>{});const d=e?`group ${n||e}`:"No Group",u=l.length>0?` · skipped ${l.length} (${Zh(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${d}${u}`:`No sessions moved to ${d}${u}`}),c>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const r=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],value:r,cursorIndex:r.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const r=Gt(e,n.maxLength||80),i=Ae(r,s);this.updateSessionGroupNameModal({value:r,cursorIndex:i})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=yt(s.value||"",s.cursorIndex||0,Gt(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(e.mode==="rename"&&e.groupId){const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.updateSessionGroup(e.groupId,{title:s}),this.dispatch({type:"ui/status",text:`Renamed group to "${s}"`}),await this.refreshSessions().catch(()=>{})}catch(i){this.dispatch({type:"ui/status",text:`Rename failed: ${i?.message||String(i)}`})}return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const r=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[]}),i=e.sessionIds||[];i.length===0?(this.dispatch({type:"ui/status",text:`Created group "${r.title||s}"`}),await this.refreshSessions().catch(()=>{})):await this.moveSessionsToGroup(r.groupId,i,{statusTitle:r.title||s})}catch(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null;if(!n?.isGroup)return e;const r=n.groupId||Vs(n.sessionId);return r?{...e,groupId:r}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}async openSessionAgentPicker(e={},s=null){const n=s??this.getState().ui.focusRegion,r=()=>{this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n)};let i=[];try{i=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[]}catch(h){r(),this.dispatch({type:"ui/status",text:`Could not load agents: ${h?.message||h}`});return}const l=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(i)||i.length===0){if(r(),!l){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const c=[];for(const h of i){const g=String(h?.name||"").trim();g&&c.push({id:g,kind:"agent",agentName:g,title:oa(g,h?.title),description:String(h?.description||"").trim(),tools:Array.isArray(h?.tools)?h.tools.filter(Boolean):[],splash:typeof h?.splash=="string"&&h.splash.trim()?h.splash:null,splashMobile:typeof h?.splashMobile=="string"&&h.splashMobile.trim()?h.splashMobile:null,initialPrompt:typeof h?.initialPrompt=="string"&&h.initialPrompt.trim()?h.initialPrompt:null,group:h?.source==="package"&&h?.scope==="user"&&h?.mine!==!1?"mine":"shared",packageName:h?.packageName||null,packageTitle:h?.packageTitle||null,packageSemver:h?.packageSemver||null,packageScope:h?.scope||null,ownerLabel:h?.ownerLabel||null,startedBy:Array.isArray(h?.startedBy)?h.startedBy.filter(Boolean):[],supportsDirectStart:typeof h?.supportsDirectStart=="boolean"?h.supportsDirectStart:void 0,builtin:h?.source!=="package"})}const d=[...c.filter(h=>h.group==="shared"),...c.filter(h=>h.group==="mine")],u=l?{id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null,supportsDirectStart:!0}:null,p=await this._loadAgentPickerUsage(),m=aa.includes(this._agentPickerSort)?this._agentPickerSort:_c,f=ca(d,{query:"",sort:m,usage:p,genericItem:u});this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",catalog:d,genericItem:u,items:f,query:"",sort:m,usage:p,selectedIndex:gg(f),previousFocus:n,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Ys(e?.supportedReasoningEfforts),a=s?.reasoningEffort||ta(e);if(!i.length||!a){await this.openContextTierPicker(e,s,r);return}const l=i.map(d=>({id:d,effort:d,label:d,isDefault:a===d})),c=Math.max(0,l.findIndex(d=>d.id===a));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Xs(e?.supportedContextTiers),a=s?.contextTier||tg(e);if(!i.length||!a){if(s?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s,r);return}const l=i.map(d=>({id:d,tier:d,tokenLimit:e?.contextWindowSizes?.[d]||null,label:ng(d,e?.contextWindowSizes?.[d]),isDefault:a===d})),c=Math.max(0,l.findIndex(d=>d.id===a));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a context window and press Enter"})}async openModelPicker(e={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(e);return}const s=await this.transport.listModels();if(!Array.isArray(s)||s.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const n=await this._resolveProviderNamespace(),r=n?.error?{refusal:n.error}:n?this._buildProviderPickerGroups(n,s,e):await this._buildCatalogPickerGroups(s,e);if(r.refusal){this.dispatch({type:"ui/status",text:r.refusal});return}const{items:i,groups:a,selectedIndex:l}=r;this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:i,groups:a,selectedIndex:l,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveProviderNamespace(){if(typeof this.transport.listProviders!="function")return null;try{const[e,s,n]=await Promise.all([this.transport.listProviders(),typeof this.transport.getProviderStatus=="function"?this.transport.getProviderStatus().catch(()=>null):null,typeof this.transport.getDefaults=="function"?this.transport.getDefaults().catch(()=>null):null]),r=Array.isArray(e?.providers)?e.providers:null;return r?{providers:r,status:Array.isArray(s?.providers)?s.providers:[],statusKnown:Array.isArray(s?.providers),defaults:n||null}:{error:"Runtime provider availability could not be verified. Refresh and try again."}}catch{return{error:"Runtime provider availability could not be verified. Refresh and try again."}}}_buildProviderPickerGroups(e,s,n){const r=e.providers.filter(m=>m.usableByMe!==!1);if(r.length===0)return{refusal:"No provider can pay for a session yet — add one of your own, or ask an admin for a shared one."};const i=new Map;for(const m of s){const f=m?.providerId;f&&(i.has(f)||i.set(f,[]),i.get(f).push(m))}const a=new Map(e.status.map(m=>[m.name,m])),l=Date.now(),c=[...r].sort((m,f)=>{const h=g=>g.isMyDefault===!0?0:g.isClusterDefault===!0?1:g.class==="personal"?2:3;return h(m)-h(f)||String(m.name).localeCompare(String(f.name))}),d=n?.model||e.defaults?.mine?.model||e.defaults?.cluster?.model||(typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0),u=[],p=c.map(m=>{const f=jg(m,a.get(m.name)||null,l),h=m.hasCredential===!1?`${m.name} has no credential`:null;return{providerId:m.name,providerType:m.typeId,providerClass:m.class,isClusterDefault:m.isClusterDefault===!0,isMyDefault:m.isMyDefault===!0,hasCredential:m.hasCredential!==!1,budgetState:f.state,budgetNote:f.text,models:(i.get(m.name)||i.get(m.typeId)||[]).map(g=>{const b=g.providerId===m.name&&g.qualifiedName?g.qualifiedName:`${m.name}:${g.modelName}`,y=h||(g.credentialAvailable===!1?`${m.name} has no usable credential or endpoint`:null),S={id:b,qualifiedName:b,modelName:g.modelName||b,providerId:m.name,providerType:m.typeId,providerClass:m.class,description:g.description||"",cost:g.cost||null,supportedReasoningEfforts:Ys(g.supportedReasoningEfforts),defaultReasoningEffort:g.defaultReasoningEffort||null,supportedContextTiers:Xs(g.supportedContextTiers),defaultContextTier:g.defaultContextTier||null,contextWindowSizes:g.contextWindowSizes||null,isDefault:d===b,budgetState:f.state,budgetNote:f.text,disabledReason:y,disabled:!!y};return u.push(S),S})}}).filter(m=>m.models.length>0);return u.length===0?{refusal:"No provider in your namespace offers a model to run."}:{items:u,groups:p,selectedIndex:ea(u,d)}}async _buildCatalogPickerGroups(e,s){const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,r=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():eg(e),i=await this._resolveGhcpUserKeySet(),a=[],l=r.map(c=>({providerId:c.providerId,providerType:c.type||c.providerType,models:(c.models||[]).map(d=>{const u=d.providerType||c.type||c.providerType,p=u==="github"&&d.credentialAvailable===!1&&i===!1,m={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||c.providerId,providerType:u,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:Ys(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Xs(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:p,disabledReason:p?"needs GitHub key":null,disabled:p};return a.push(m),m})})).filter(c=>c.models.length>0);return{items:a,groups:l,selectedIndex:ea(a,s?.model||n)}}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,r=n&&s.sessions.byId[n]||null;if(!r||r.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:r.model||void 0,reasoningEffort:r.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const r=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,i=e.contextTier?` · ${Tc[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${r}${i}`}),await this.refreshSessions();const a=this._onSwitchModelApplied;this._onSwitchModelApplied=null,typeof a=="function"&&a()}openHelpModal(){this.dispatch({type:"ui/modal",modal:{type:"help",title:"Keybindings",selectedIndex:0,previousFocus:this.getState().ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Keybindings — ? or Esc to close"})}openThemePicker(){const e=xp().map(r=>({id:r.id,label:r.label,description:r.description,group:r.group,page:r.page,terminal:r.terminal,tui:r.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(r=>r.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${He(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const r=String(e||"").replace(/\r?\n/g,""),i=Ae(r,s);this.updateArtifactUploadModal({value:r,cursorIndex:i})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=yt(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveArtifactUploadCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",e==="start"?0:String(s.value||"").length)}async ensurePromptAttachmentSessionId(){const e=this.getPromptAttachments()[0]?.sessionId||null;if(e)return this.getState().sessions.activeSessionId!==e&&await this.loadSession(e),e;const s=this.getState().sessions.activeSessionId;if(s)return s;const n=await this.createSession({});if(!n?.sessionId)throw new Error("Create a session before attaching files");return n.sessionId}async revealArtifact(e,s,{force:n=!0,fullscreen:r=!1,pane:i=!1}={}){const a=e||this.getState().sessions.activeSessionId,l=String(s||"").trim();if(!a||!l)return!1;if(this.dispatch({type:"files/previewOrigin",origin:"chat",restoreArtifactId:this.getState().files.selectedArtifactId||null}),this.getState().sessions.activeSessionId!==a&&await this.loadSession(a).catch(()=>null),i||this.dispatch({type:"ui/inspectorTab",inspectorTab:"files"}),i){const c=!!this.getCurrentLayout()?.rightHidden;c&&this.expandRightColumn(),this.dispatch({type:"files/pane",open:!0,restoresToHidden:c})}else this.setFocus("inspector");return await this.ensureFilesForSession(a,{force:n}).catch(()=>null),this.dispatch({type:"files/select",sessionId:a,filename:l}),await this.ensureFilePreview(a,l,{force:n}).catch(()=>null),r&&this.dispatch({type:"files/fullscreen",fullscreen:!0}),!0}async closeArtifactPane(){const e=this.getState().files.paneRestoresToHidden;return this.dispatch({type:"files/pane",open:!1}),this.dispatch({type:"files/fullscreen",fullscreen:!1}),this.dispatch({type:"files/previewOrigin",origin:null}),e&&this.collapseRightColumn(),this.dispatch({type:"ui/focus",focusRegion:$.CHAT}),{collapsedRightColumn:!!e}}expandRightColumn(){this.dispatch({type:"ui/paneAdjust",paneAdjust:0});const e=this.getCurrentLayout({paneAdjust:0}),s=this.getState().ui.focusRegion,n=it(s,e);n!==s&&this.setFocus(n)}collapseRightColumn(){const s=(this.getState().ui.layout||{}).viewportWidth??120,n=Math.floor(s*Tl),r=s-Ks-n;this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),a=this.getState().ui.focusRegion,l=it(a,i);l!==a&&this.setFocus(l)}async closeArtifactPreview(){const e=this.getState(),s=e.files.previewOrigin;if(this.dispatch({type:"files/fullscreen",fullscreen:!1}),s!=="chat"){this.dispatch({type:"files/previewOrigin",origin:null}),this.setFocus($.INSPECTOR);return}const n=e.files.restoreArtifactId;if(n){const r=String(n).indexOf("/");r>0&&this.dispatch({type:"files/select",sessionId:n.slice(0,r),filename:n.slice(r+1)})}else this.dispatch({type:"files/select",sessionId:null,filename:null});this.dispatch({type:"files/previewOrigin",origin:null}),this.dispatch({type:"ui/focus",focusRegion:$.CHAT})}async stepArtifactPreview(e){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(e);return}const n=Po(s);if(n.length===0){await this.moveFileSelection(e);return}const r=n.indexOf(s.files.selectedArtifactId),a=(r>=0?r:e>0?-1:n.length)+(e>0?1:-1);if(a<0||a>=n.length)return;const l=n[a],c=l.indexOf("/");if(c<=0)return;const d=l.slice(0,c),u=l.slice(c+1);this.dispatch({type:"files/select",sessionId:d,filename:u}),await this.ensureFilePreview(d,u).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?Po(s):Rt(s).map(i=>i.id);if(n.length===0)return!1;const r=n.indexOf(s.files.selectedArtifactId);return r<0?!0:e>0?r<n.length-1:r>0}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:e.filename}),await this.ensureFilePreview(r,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:r,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!e?.filename)throw new Error("Upload did not return a session id and filename");const i=da(e.filename),a=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),d=c.findIndex(p=>p?.sessionId===r&&p?.filename===e.filename);if(this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),d===-1||!a.includes(c[d]?.token||i)){const p=yt(a,l,`${i} `);this.setPrompt(p.prompt,p.cursor)}const u=d>=0?c.map((p,m)=>m===d?{...p,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}:p):[...c,{id:`${r}/${e.filename}`,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}];return this.setPromptAttachments(u),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(r,e.filename,{force:!0}).catch(()=>null),this.setFocus($.PROMPT),n||this.dispatch({type:"ui/status",text:d>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:r,existingAttachmentIndex:d,token:i}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(c=>c&&typeof c.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const r=s||await this.ensurePromptAttachmentSessionId(),i=[];let a=0,l=null;for(const c of n)try{const d=await this.transport.uploadArtifactFromFile(r,c);i.push(d),await this.finalizeArtifactUpload(d,{sessionId:r,suppressStatus:!0})}catch(d){a+=1,l=d}return i.length>0?this.dispatch({type:"ui/status",text:a>0?`Uploaded ${i.length}/${n.length} file(s); last error: ${l?.message||String(l)}`:i.length===1?`Uploaded ${i[0].filename}`:`Uploaded ${i.length} files`}):l&&this.dispatch({type:"ui/status",text:`Upload failed: ${l?.message||String(l)}`}),i}async uploadPromptAttachmentFiles(e=[]){return this.uploadArtifactFiles(e)}async confirmArtifactUploadModal(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"File path cannot be empty"});return}if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}this.dispatch({type:"ui/status",text:"Uploading artifact..."});try{const n=e.sessionId||await this.ensurePromptAttachmentSessionId(),r=await this.transport.uploadArtifactFromPath(n,s),i=await this.finalizeArtifactUpload(r,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(i,n)){this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${i.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const r=mg(n),i=Ci(n),a=pg(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:n.isGroup?"Rename folder":`Rename (${He(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:r,cursorIndex:r.length,agentTitlePrefix:i,currentTitle:String(n.title||"").trim(),maxLength:a,isGroup:!!n.isGroup}}),this.dispatch({type:"ui/status",text:n.isGroup?"Type a new folder name and press Enter to save":i?`Rename title for ${i}; the agent-name prefix stays fixed`:"Type a new session title and press Enter to save"})}async openTerminatePickerModal(){const e=this.getState(),s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[];if(e.sessions.selectMode&&s.length>=1){const i=this.getBulkSelectedSessionActions(e).eligible;if(i.length===0){this.dispatch({type:"ui/status",text:"No selected sessions can be terminated"});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Terminate Selected Sessions",previousFocus:e.ui.focusRegion,bulkCount:i.length,skippedCount:s.length-i.length,selectedIds:i.map(a=>a.sessionId)}}),this.dispatch({type:"ui/status",text:"Choose what to do with the selected sessions"});return}const n=e.sessions.activeSessionId;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}const r=e.sessions.byId[n];if(!r){this.dispatch({type:"ui/status",text:"No session selected"});return}if(r.isSystem){const i=String(r.title||r.agentId||n.slice(0,8)).trim();this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Restart System Session",sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:i,state:String(r.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(r.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Terminate (${He(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(r.title||"").trim(),state:String(r.state||"").trim(),canRegenerate:!1}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"?await this.deleteActiveSession():e==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],r=[...new Set(s.map(a=>String(a||"").trim()).filter(Boolean))].map(a=>e.sessions.byId[a]).filter(Boolean),i=r.filter(a=>!a.isSystem&&!a.isGroup);return{selected:r,eligible:i,skippedCount:r.length-i.length}}updateRenameSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setRenameSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="renameSession")return;const r=Gt(e,n.maxLength),i=Ae(r,s);this.updateRenameSessionModal({value:r,cursorIndex:i})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=yt(s.value||"",s.cursorIndex||0,Gt(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveRenameSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmRenameSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim();if(!n){this.dispatch({type:"ui/status",text:"Title cannot be empty"});return}const r=this.getState().sessions.byId[s],i=r?.isGroup?r.groupId||Vs(s):null;if(i){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const l=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),l&&this.setFocus(l),this.dispatch({type:"ui/status",text:`Renaming group ${i.slice(0,8)}...`});try{await this.transport.updateSessionGroup(i,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(c){this.dispatch({type:"ui/status",text:`Rename failed: ${c?.message||String(c)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const a=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),a&&this.setFocus(a),this.dispatch({type:"ui/status",text:`Renaming ${He(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${He(s)}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const r=Ut(["private","shared_read","shared_write"],n.visibility||"private",1);try{await this.transport.setSessionVisibility(s,r),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Visibility → ${r}`})}catch(i){this.dispatch({type:"ui/status",text:i?.message||String(i)})}}async openShareSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups can't be shared"});return}if(typeof this.transport.listSessionShares!="function"){this.dispatch({type:"ui/status",text:"Session sharing is not supported by this transport"});return}let r;try{r=await this.transport.listSessionShares(s)}catch(i){this.dispatch({type:"ui/status",text:i?.message||String(i)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${He(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(r)?r:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const r=Gt(e,120),i=Ae(r,s);this.updateShareSessionModal({value:r,cursorIndex:i})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=yt(s.value||"",s.cursorIndex||0,Gt(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=Tt(e.value||"",e.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",Ae(s.value||"",(s.cursorIndex||0)+e))}moveShareSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim(),r=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);return}const i=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(i!==null){const f=i.toLowerCase(),h=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===f||g.email&&String(g.email).toLowerCase()===f||g.displayName&&String(g.displayName).toLowerCase()===f);if(!h){this.dispatch({type:"ui/status",text:`No grant matching "${i}"`});return}this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.revokeSessionShare(s,{provider:h.provider,subject:h.subject}),this.dispatch({type:"ui/status",text:`Revoked ${i}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const a=n.split(/\s+/),l={r:"read",read:"read",w:"write",write:"write"},c=a.length>1?a[a.length-1].toLowerCase():null,d=c&&l[c]?l[c]:"read",u=c&&l[c]?a.slice(0,-1).join(" "):n,p=u.toLowerCase();let m=null;if(typeof this.transport.listKnownUsers=="function"){let f=[];try{f=await this.transport.listKnownUsers({limit:500})}catch{f=[]}const h=Array.isArray(f)?f:[];if(m=h.find(g=>g.displayName&&g.displayName.toLowerCase()===p||g.email&&g.email.toLowerCase()===p||g.subject&&g.subject.toLowerCase()===p)||null,!m){const g=h.filter(b=>b.displayName&&b.displayName.toLowerCase().includes(p)||b.email&&b.email.toLowerCase().includes(p)||b.subject&&b.subject.toLowerCase().includes(p));if(g.length===1)m=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${u}" is ambiguous (${g.length} matches)`});return}}}m||(m={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:u,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.grantSessionShare(s,{provider:m.provider,subject:m.subject,email:m.email??null,displayName:m.displayName??null},d),this.dispatch({type:"ui/status",text:`Granted ${d} to ${u}`})}catch(f){this.dispatch({type:"ui/status",text:f?.message||String(f)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}async _loadAgentPickerUsage(){try{if(typeof this.transport.getCurrentUserProfile!="function")return null;const s=(await this.transport.getCurrentUserProfile())?.profileSettings?.[ir];if(!s||typeof s!="object")return{};const n={};for(const[r,i]of Object.entries(s)){const a=Number(i);Number.isFinite(a)&&a>0&&(n[r]=a)}return n}catch{return null}}async _recordAgentPickerUse(e){const s=String(e||"").trim();if(s)try{if(typeof this.transport.getCurrentUserProfile!="function"||typeof this.transport.setCurrentUserProfileSettings!="function")return;const r={...(await this.transport.getCurrentUserProfile())?.profileSettings||{}},i={...r[ir]||{}};i[s]=(Number(i[s])||0)+1,r[ir]=i,this.dispatch({type:"ui/agentPickerUsage",usage:i}),await this.transport.setCurrentUserProfileSettings({settings:r})}catch{}}_refreshAgentPicker(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return;const n={...s,...e},r=ca(n.catalog||[],{query:n.query,sort:n.sort,usage:n.usage,genericItem:n.genericItem||null}),i=s.items?.[s.selectedIndex||0]?.id,a=r.findIndex(l=>l.id===i);this.dispatch({type:"ui/modal",modal:{...n,items:r,selectedIndex:a>=0?a:0}})}setAgentPickerQuery(e){this._refreshAgentPicker({query:String(e??"")})}setAgentPickerSort(e){aa.includes(e)&&(this._agentPickerSort=e,this._refreshAgentPicker({sort:e}))}moveAgentPickerSection(){return!1}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const i=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,i+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const i=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),a=s.items[i];if(!a||!Array.isArray(a.options)||a.options.length===0)return;const l=a.options.map(p=>p.id).filter(Boolean);if(l.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[a.id]||l[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||l[0]:this.getState().logs.filter?.[a.id]||l[0],d=Ut(l,c,e),u=a.options.find(p=>p.id===d)||a.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[a.id]:d},...s.type==="historyFormat"?{format:d}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(d).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${a.label} = ${u?.label||d}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:r})}moveModalPane(e){const s=this.getState().ui.modal;if(s?.type==="sessionAgentPicker"){this.moveAgentPickerSection(e);return}if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const r=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,i=s.items[r],a=s.type==="filesFilter"?this.getState().files.filter?.[i.id]||i.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||i.options?.[0]?.id:this.getState().logs.filter?.[i.id]||i.options?.[0]?.id,l=i.options?.find(c=>c.id===a)||i.options?.[0];this.dispatch({type:"ui/modalSelection",index:r}),this.dispatch({type:"ui/status",text:`Editing ${i.label}: ${l?.label||a||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="help"){this.closeModal();return}if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...e.extras||{}}):e.action==="deleteArtifact"?await this.deleteSelectedArtifact({confirmed:!0}):e.action==="deleteMarkedArtifacts"?await this.deleteMarkedArtifacts({confirmed:!0}):e.action==="deleteAdminProvider"&&await this.deleteSelectedAdminProvider();return}if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();return}if(e.type==="shareSession"){await this.confirmShareSessionModal();return}if(e.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(e.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(e.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(e.type==="filesFilter"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(e.type==="themePicker"){const s=e.items?.[e.selectedIndex||0],n=ft(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.disabled){this.dispatch({type:"ui/status",text:s.ghcpKeyMissing?"This model needs a GitHub Copilot provider — add your own in Admin Console first":"This model is not available"});return}const n=e.previousFocus;if(!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({},n);return}const r=ta(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:r??null},n);return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...r?{reasoningEffort:r}:{}},n);return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,r=e.sessionOptions||{};await this.openContextTierPicker(e.modelItem,{...r,...s?.id?{reasoningEffort:s.id}:{}},n);return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,r=e.sessionOptions||{},i={...r,...s?.id?{contextTier:s.id}:{}};if(r?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.switchSessionModel({...i,model:e.modelItem?.id||r.model});return}await this.openSessionAgentPicker(i,n);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0];if(s&&s.kind!=="generic"&&s.supportsDirectStart===!1){this.dispatch({type:"ui/status",text:`${s.title||s.agentName} is created by another agent and cannot be started on its own`});return}const n=e.previousFocus,r=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(r);return}await this.createSessionForAgent(s.agentName,{...r,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.splashMobile?{splashMobile:s.splashMobile}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=this.getPromptAttachments(),r=n[0]?.sessionId||null,i=kg(s,n);let a=e.sessions.activeSessionId;r&&(a=r,e.sessions.activeSessionId!==r&&await this.loadSession(r));let l=a&&e.sessions.byId[a]||null;if(a&&!l&&(l=this.getState().sessions.byId[a]||null),!a){const g=await this.createSession({});if(!g?.sessionId)return;a=g.sessionId,l=this.getState().sessions.byId[a]||null}const c=n.some(g=>g?.kind==="image");if(!i.trim()&&!c){a&&this.getPendingOutboxItems(a).length>0&&await this.dispatchPendingOutbox(a).catch(()=>{});return}const d=l?.pendingQuestion||null,u=!!d?.question,p=this.getPromptEditSessionMatch(a);if(p){const g=this.getSessionOutbox(a).find(b=>b.id===p.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(a).catch(()=>{});return}if(u&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),b={...d,answer:i,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:a,pendingQuestion:null,answeredPendingQuestion:b}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(a,i),this.dispatch({type:"sessions/merged",session:{sessionId:a,answeredPendingQuestion:{...b,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(a,100),this.syncSessionEvents(a).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:a,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:a,pendingQuestion:d}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(i,String(i||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const m=n.filter(g=>g?.kind==="image");let f=null;if(m.length>0){if(m.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const b=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${m.length} image${m.length>1?"s":""}...`});try{f=await this.uploadPendingImageAttachments(a,m,b.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const h=i.trim()?i:f&&f.length>0?"See the attached image(s).":i;this.queuePromptInOutbox(a,h,f?{attachments:f}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(a).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),r=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),i=this.getState().ui;if(!(i.prompt===n&&i.promptCursor===r)){if(i.promptEdit?.sessionId&&i.promptEdit?.itemId){const l=this.getSessionOutbox(i.promptEdit.sessionId).map(c=>c.id===i.promptEdit.itemId&&c.phase==="pending"&&c.attempted!==!0?{...c,text:n}:c);this.setSessionOutboxItems(i.promptEdit.sessionId,l)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:r}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=yt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=Tt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Cg(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,Ae(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,Lc(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Tg(s.prompt,s.promptCursor,e);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}e<0&&this.selectPreviousPendingPrompt()||e>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,r=e.prompt??n.prompt;return Cs({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??ts(r),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===$.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(3,s-2)}setViewport(e={}){const s=Math.max(40,Number(e.width)||120),n=Math.max(18,Number(e.height)||40),r=this.getState().ui.layout||{};(r.viewportWidth!==s||r.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const i=this.getCurrentLayout({width:s,height:n}),a=this.getState().ui.focusRegion,l=it(a,i);l!==a&&this.setFocus(l)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:it(e,this.getCurrentLayout()),requestedFocusRegion:e})}focusNext(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e),n=kr(e);this.setFocus(Ut(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e),n=kr(e);this.setFocus(Ut(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e);this.setFocus(Lu(s,e))}focusRight(){const e=this.getCurrentLayout(),s=it(this.getState().ui.focusRegion,e);this.setFocus(Ou(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,r=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),a=this.getState().ui.focusRegion,l=it(a,i);l!==a&&this.setFocus(l)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:i});const a=this.getCurrentLayout({sessionPaneAdjust:i}),l=this.getState().ui.focusRegion,c=it(l,a);c!==l&&this.setFocus(c)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:i});const a=this.getCurrentLayout({activityPaneAdjust:i}),l=this.getState().ui.focusRegion,c=it(l,a);c!==l&&this.setFocus(c)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,i=n.viewportHeight??40,a=(l,c,d,u)=>{const p=Math.max(d,u);return Math.max(d,Math.min(p,(l||0)+c))};if(s===$.SESSIONS||s===$.CHAT){const l=_l(r),c=as+1,d=Math.min(Rl(i,r),r-xn-1),u=s===$.CHAT?-e:e,p=a(n.sessionPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:p})}else if(s===$.INSPECTOR||s===$.ACTIVITY){const l=Math.max(es,Math.floor(r*Ml)),c=es+1,d=r-nn-1,u=s===$.INSPECTOR?-e:e,p=a(n.activityPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:p})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),r=[],i=new Set;for(const a of n?.events||[]){if(a?.eventType!=="session.turn_completed")continue;const l=Number(a?.data?.turnIndex??a?.data?.iteration);!Number.isFinite(l)||i.has(l)||(i.add(l),r.push(l))}return r.sort((a,l)=>a-l),r}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),r=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[r]})}toggleSequenceTurnExpanded(){const e=this.getActiveSequenceCompletedTurns();if(e.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);e.includes(s)||(s=e[e.length-1],this.dispatch({type:"ui/sequenceSelectedTurn",turn:s}));const n=Array.isArray(this.getState().ui.sequenceExpandedTurns)?this.getState().ui.sequenceExpandedTurns.map(Number):[],r=n.includes(s)?n.filter(i=>i!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:r})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=Ut(lt,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=Ut(lt,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,r=e[(n+1)%e.length];this.setStatsViewMode(r)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){lt.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=ds(s);if(n.length===0)return;const r=s.sessions.activeSessionId||n[0].sessionId,i=Math.max(0,n.findIndex(c=>c.sessionId===r)),a=Math.max(0,Math.min(n.length-1,i+e)),l=n[a].sessionId;this.navigateToSession(l)}navigateToSession(e){e&&(this.getState().sessions.activeSessionId!==e&&(this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.sessionNavSettleTimer&&clearTimeout(this.sessionNavSettleTimer),this.sessionNavSettleTimer=setTimeout(()=>{this.sessionNavSettleTimer=null,this.loadSession(e).catch(()=>{})},Bg))}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===$.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(1,s-3)}async moveSessionPage(e){const s=this.getSessionPageSize();await this.moveSession(s*e)}inspectorUsesBottomScroll(){return Pg.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="activity"?!0:e==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(e,s=this.getState()){return this.paneUsesStickyBottomFollow(e,s)?s.ui.followBottom?.[e]!==!1:!1}getPaneVisualScrollOffset(e,s=this.getState()){const n=this.getPaneMaxScrollOffset(e,s),r=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-r):r}applyPaneVisualScrollOffset(e,s,n={},r=this.getState()){const i=this.getPaneMaxScrollOffset(e,r),a=n.fromViewport?Math.max(0,Number(s)||0):Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,r)){const l=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:a>=i;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:l}),this.dispatch({type:"ui/scroll",pane:e,offset:l?0:a}),a}return this.dispatch({type:"ui/scroll",pane:e,offset:a}),a}updatePaneScrollFromViewport(e,s,n={}){const r=this.getState();if(this.paneUsesStickyBottomFollow(e,r)){this.applyPaneVisualScrollOffset(e,s,{...n,fromViewport:!0},r);return}this.scrollPaneTo(e,s)}expandActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/expand",sessionId:e})}collapseActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/collapse",sessionId:e})}scrollPane(e,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const l=this.getPaneVisualScrollOffset(e,n),c=Math.max(0,Math.min(l-s,r));this.applyPaneVisualScrollOffset(e,c,{followBottom:c>=r},n);return}const i=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,r)),a=Math.max(0,Math.min(i+s,r));this.dispatch({type:"ui/scroll",pane:e,offset:a}),e==="chat"&&s>0?i>=r?this.handleChatTopHistoryScrollIntent(a).catch(()=>{}):a>=r&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(e,n),i=Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,i,{followBottom:i>=r},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:i}),e==="chat"&&(r>0&&i>=r?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad())}armChatTopHistoryLoad(){const e=this.getState().sessions.activeSessionId;e&&(this.chatTopHistoryLoadArmed=!0,this.chatTopHistoryLoadSessionId=e)}disarmChatTopHistoryLoad(){this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}async handleChatTopHistoryScrollIntent(e,s={}){const r=this.getState().sessions.activeSessionId;if(r){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==r)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:Kh,force:!0})}}artifactPreviewOwnsActivitySlot(e=this.getState()){return e.ui.inspectorTab==="files"&&!!e.files?.selectedArtifactId}focusIsArtifactList(e=this.getState()){return e.ui.focusRegion===$.INSPECTOR&&e.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const e=this.getState(),s=e.ui.focusRegion;return s===$.CHAT?"chat":s===$.ACTIVITY?this.artifactPreviewOwnsActivitySlot(e)?"filePreview":"activity":s===$.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(e){const s=this.getScrollablePaneForFocus();if(!s)return;if(this.paneUsesStickyBottomFollow(s)){this.scrollPane(s,e);return}const n=s==="inspector"&&this.inspectorUsesBottomScroll(),r=s==="inspector"||s==="filePreview";this.scrollPane(s,r&&!n?-e:e)}scrollCurrentPaneToTop(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,0,{followBottom:!1});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER);return}this.scrollPaneTo(e,0)}scrollCurrentPaneToBottom(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,Number.MAX_SAFE_INTEGER,{followBottom:!0});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,0);return}this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER)}async expandActiveHistory(){const e=this.getState().sessions.activeSessionId;e&&await this.expandSessionHistory(e)}getActiveChatRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.leftHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.leftWidth-4),r=Math.max(1,s.chatPaneHeight-2),i=mi(e,n),a=[...gi(e,n),...pi(e)],l=Math.min(Math.max(0,Math.floor(r*.34)),Wt(a,n)),c=Wt(i,n);return{contentWidth:n,contentHeight:Math.max(1,r-l),totalLines:c}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),r=Math.max(1,s.activityPaneHeight-2),i=e.sessions.activeSessionId,a={sessions:{activeSessionId:i,byId:i?{[i]:e.sessions.byId[i]||null}:{}},history:{bySessionId:i?new Map([[i,e.history.bySessionId.get(i)||null]]):new Map}},l=bi(a);return{contentWidth:n,contentHeight:r,totalLines:Wt(l.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),r=e.sessions.activeSessionId,i=r&&e.orchestration.bySessionId?.[r]||null,a={branding:e.branding,sessions:{activeSessionId:r,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:r&&i?{[r]:i}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},l=It(a,{width:n}),c=l.tabs.map(m=>({text:m===l.activeTab?`[${m}] `:`${m} `,color:m===l.activeTab?"magenta":"gray",bold:m===l.activeTab})),d=(l.lines||[]).map(m=>typeof m=="string"?{text:m,color:"white"}:m),u=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(m=>typeof m=="string"?{text:m,color:"white"}:m)]:[],p=l.activeTab==="sequence"?d:[c,...d];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:Wt(u,n),totalLines:Wt(p,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,r=n?s.totalWidth:s.rightWidth,i=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,a=Math.max(20,r-4),l=Math.max(8,a-4),c=e.sessions.activeSessionId,d=c&&e.sessions.byId[c]||null,u={sessions:{activeSessionId:c,byId:c&&d?{[c]:d}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},p=Si(u,{listWidth:l,previewWidth:l}),m=Math.max(9,i-4),f=Math.max(5,Math.min(10,Math.floor(m*.35)));let h=Math.max(5,Math.min(f,(p.listBodyLines||[]).length+2)),g=Math.max(5,m-h-1);const b=8;if(g<b){const y=b-g;h=Math.max(5,h-y),g=Math.max(5,m-h-1)}return{contentWidth:l,contentHeight:Math.max(1,g-2),totalLines:Wt(p.previewLines,l)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),r=Math.min(n.contentHeight,n.stickyLineCount||0),i=Math.max(0,n.contentHeight-r);return Math.max(0,n.totalLines-i)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e,s={}){const n=this.getState(),r=n.sessions.activeSessionId;if(!r)return;const i=n.history.bySessionId.get(r);if(!i?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(r))return;if(Number(i.loadedEventCount||0)>=Or){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const a=Array.isArray(i?.chat)&&i.chat.length>0;if(!s.force&&a){const{contentHeight:l,totalLines:c}=this.getActiveChatRenderMetrics(n),d=Math.max(0,c-l);if(e<d)return}await this.expandSessionHistory(r,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:lu})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),r=n.history.bySessionId.get(e),i=Math.max(we,Number(r?.loadedEventLimit??we)||we),a=we,l=Array.isArray(r?.events)&&r.events.length>0?Number(r.events[0]?.seq||0):0;if(!r?.hasOlderEvents||l<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const c=e===n.sessions.activeSessionId,d=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),u=c?this.getActiveChatRenderMetrics(n).totalLines:0,p=(async()=>{let m;const f=Math.max(1,Math.floor(Number(s.pages)||1)),h=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&l>0){m=r||Os([],{requestedLimit:i});for(let y=0;y<f;y+=1){const S=Array.isArray(m?.events)&&m.events.length>0?Number(m.events[0]?.seq||0):0;if(!m?.hasOlderEvents||S<=1){m={...m,hasOlderEvents:!1};break}if(Number(m.loadedEventCount||0)>=Or)break;const w=await this.transport.getSessionEventsBefore(e,S,a,h);if(!Array.isArray(w)||w.length===0){m={...m,hasOlderEvents:!1};break}const k=Os(w,{requestedLimit:a}),E=[...k.events||[],...m?.events||[]];if(m={chat:Zt([...k.chat||[],...m?.chat||[]]),activity:[...k.activity||[],...m?.activity||[]],events:E,lastSeq:m?.lastSeq||m?.events?.[m?.events?.length-1]?.seq||w[w.length-1]?.seq||0,loadedEventLimit:E.length,loadedEventCount:E.length,hasOlderEvents:w.length>=a&&Number(w[0]?.seq||0)>1},!m.hasOlderEvents)break}}else{const y=Tu(i);if(y<=i){this.dispatch({type:"ui/status",text:r?.hasOlderEvents?`Already showing a large recent history window (${i} events)`:"Already showing the oldest loaded history"});return}const S=await this.transport.getSessionEvents(e,void 0,y);m={...Os(S,{requestedLimit:y}),lastSeq:S[S.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:m});for(const y of m?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(r?.chat)&&r.chat.length>0;if(c&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&d>0&&!s.autoTriggered){const y=this.getState(),S=this.getActiveChatRenderMetrics(y).totalLines,w=Math.max(0,S-u);w>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:d+w})}const b=m.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${m.loadedEventCount} events loaded)`:`Loaded older history page (${m.loadedEventCount} events loaded)`:`Loaded full available history (${m.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:b}),m.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,p),p}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(a.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${a.length} selected session${a.length===1?"":"s"}?${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of a)try{await this.transport.cancelSession(p.sessionId),c+=1}catch(m){d.push(`${p.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${a.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(i?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const a=i.title||i.agentId||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${a}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(i.agentId||r,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${i.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=i?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${l}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(r),this.dispatch({type:"ui/status",text:`Cancelled ${r.slice(0,8)}`}),await this.refreshSessions()}updateConfirmExtras(e){const s=this.getState().ui.modal;!s||s.type!=="confirm"||this.dispatch({type:"ui/modal",modal:{...s,extras:{...s.extras||{},...e||{}}}})}async regenerateActiveSession({confirmed:e=!1,instructions:s="",distillMode:n="llm",distillerModel:r="",distillerEffort:i="",distillerContextTier:a=""}={}){const l=this.getState(),c=l.sessions.activeSessionId;if(!c)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const d=l.sessions.byId[c];if(d?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(d?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(d?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const u=d?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${u}"? The transcript is archived and distilled, then the session rebuilds fresh from it at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved. As an operator action this overrides the rate limits (cooldown / minimum age).`,confirmLabel:"Regenerate",action:"regenerateSession",sessionId:c,previousFocus:l.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const u=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...u?{instructions:u.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{},...r?{distillerModel:r}:{},...i?{distillerReasoningEffort:i}:{},...a?{distillerContextTier:a}:{}}),this.dispatch({type:"ui/status",text:`Regeneration requested for ${c.slice(0,8)} — rebuilding at the next boundary`})}catch(u){this.dispatch({type:"ui/status",text:`Regenerate failed: ${u?.message||String(u)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(r=>Array.isArray(r?.models)?r.models.map(i=>({...i,providerId:i.providerId||r.providerId})):[r]).filter(r=>r&&(r.qualifiedName||r.modelName)).map(r=>({qualifiedName:r.qualifiedName||r.modelName,modelName:r.modelName||r.qualifiedName,providerId:r.providerId||"",supportedReasoningEfforts:Array.isArray(r.supportedReasoningEfforts)?r.supportedReasoningEfforts:[],supportedContextTiers:Array.isArray(r.supportedContextTiers)?r.supportedContextTiers:[]}))}catch(e){return this.dispatch({type:"ui/status",text:`Could not load distiller models: ${e?.message||String(e)}`}),[]}}async stopActiveSessionTurn(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session to stop its turn."});return}if(typeof this.transport.stopSessionTurn!="function"){this.dispatch({type:"ui/status",text:"Stop turn is not supported by this transport"});return}if(this._stopTurnInFlight||(this._stopTurnInFlight=new Set),!this._stopTurnInFlight.has(s)){this._stopTurnInFlight.add(s),this.dispatch({type:"ui/status",text:`Stopping turn for ${s.slice(0,8)}…`});try{const i=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";i==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):i==="timeout"?this.dispatch({type:"ui/status",text:"Stop requested — waiting for the turn to unwind"}):this.dispatch({type:"ui/status",text:`Stopped turn for ${s.slice(0,8)}`})}catch(r){this.dispatch({type:"ui/status",text:`Stop turn failed: ${r?.message||r}`})}finally{this._stopTurnInFlight.delete(s)}await this.refreshSessions(),await this.refreshActiveSessionDetail?.().catch?.(()=>{})}}togglePinActiveSession(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n)return;if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be pinned."});return}if(!n.isGroup&&(n.parentSessionId||n.groupId)){this.dispatch({type:"ui/status",text:"Sessions inside groups or parents cannot be pinned."});return}const r=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:r?`Unpinned ${s.slice(0,8)}`:`Pinned ${s.slice(0,8)}`})}toggleSessionSelectMode(){const e=this.getState(),s=!e.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=e.sessions.activeSessionId;n&&e.sessions.byId[n]&&this.dispatch({type:"sessions/selectToggle",sessionId:n}),this.dispatch({type:"ui/status",text:"Select mode: space toggles, Ctrl+G moves, c cancels, V/esc exits"})}else this.dispatch({type:"ui/status",text:"Select mode off"})}toggleActiveSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId;s&&(e.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(e){const s=Array.isArray(e)?e:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(e="Completed by user",{confirmed:s=!1}={}){const n=this.getState(),r=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&r.length>=1){const{eligible:l,skippedCount:c}=this.getBulkSelectedSessionActions(n);if(l.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${l.length} selected session${l.length===1?"":"s"}? This will cascade to their sub-agents.${c>0?` (${c} selected row${c===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let d=0;const u=[];for(const m of l)try{await this.transport.completeSession(m.sessionId,e),d+=1}catch(f){u.push(`${m.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Completed ${d} session${d===1?"":"s"}`:`Completed ${d}/${l.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const i=this.getState().sessions.activeSessionId;if(!i)return;const a=this.getState().sessions.byId[i];if(a?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(a?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const l=a.title||a.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${l}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:i,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(a.agentId||i,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${a.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}if(a?.status==="completed"&&!a?.cronActive&&!a?.cronInterval){this.dispatch({type:"ui/status",text:`${i.slice(0,8)} is already completed`});return}if(!s){const l=a?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${l}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:i,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${i.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(i,e),await this.refreshSessions(),this.scheduleSessionDetailSync(i,100),this.scheduleSessionsRefresh(900)}catch(l){await this.loadSession(i).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${l?.message||String(l)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(a.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${a.length} selected session${a.length===1?"":"s"}? This action cannot be undone.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of a)try{await this.transport.deleteSession(p.sessionId),this.handleSessionGone(p.sessionId),c+=1}catch(m){d.push(`${p.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${a.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){const a=i.groupId||Vs(r);if(!a||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(i.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${i.title||a}" is not empty. Move all sessions out of the group before deleting it.`,confirmLabel:"OK",action:"alert",alert:!0,previousFocus:s.ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Move all sessions out of the group before deleting it."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Group",message:`Delete empty group "${i.title||a}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(a),this.dispatch({type:"ui/status",text:`Deleted group ${i.title||a}`}),await this.refreshSessions();return}if(i?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const a=i.title||i.agentId||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${a}" and start a fresh one? This removes the current orchestration immediately.`,confirmLabel:"Hard Delete & Restart",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(i.agentId||r,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${i.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=i?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${l}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(r),this.handleSessionGone(r),this.dispatch({type:"ui/status",text:`Deleted ${r.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case M.REFRESH:await this.refreshSessions();return;case M.NEW_SESSION:await this.openNewSessionFlow();return;case M.OPEN_MODEL_PICKER:await this.openModelPicker();return;case M.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case M.OPEN_THEME_PICKER:this.openThemePicker();return;case M.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case M.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case M.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case M.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case M.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case M.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case M.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case M.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case M.CLOSE_MODAL:this.closeModal();return;case M.MODAL_PREV:this.moveModalSelection(-1);return;case M.MODAL_NEXT:this.moveModalSelection(1);return;case M.MODAL_PANE_PREV:this.moveModalPane(-1);return;case M.MODAL_PANE_NEXT:this.moveModalPane(1);return;case M.MODAL_CONFIRM:await this.confirmModal();return;case M.SEND_PROMPT:await this.sendPrompt();return;case M.FOCUS_NEXT:this.focusNext();return;case M.FOCUS_PREV:this.focusPrev();return;case M.FOCUS_LEFT:this.focusLeft();return;case M.FOCUS_RIGHT:this.focusRight();return;case M.FOCUS_PROMPT:this.setFocus($.PROMPT);return;case M.FOCUS_SESSIONS:this.setFocus($.SESSIONS);return;case M.MOVE_SESSION_UP:await this.moveSession(-1);return;case M.MOVE_SESSION_DOWN:await this.moveSession(1);return;case M.EXPAND_SESSION:this.expandActiveSession();return;case M.COLLAPSE_SESSION:this.collapseActiveSession();return;case M.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case M.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case M.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case M.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case M.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case M.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case M.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case M.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case M.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case M.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case M.OPEN_HELP:this.openHelpModal();return;case M.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case M.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case M.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case M.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case M.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case M.OPEN_LOG_FILTER:this.openLogFilter();return;case M.OPEN_FILES_FILTER:this.openFilesFilter();return;case M.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case M.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case M.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case M.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case M.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case M.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case M.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case M.SCROLL_UP:this.scrollCurrentPane(1);return;case M.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case M.PAGE_UP:if(this.getState().ui.focusRegion===$.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case M.PAGE_DOWN:if(this.getState().ui.focusRegion===$.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case M.EXPAND_HISTORY:await this.expandActiveHistory();return;case M.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case M.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case M.CANCEL_SESSION:await this.cancelActiveSession();return;case M.STOP_TURN:await this.stopActiveSessionTurn();return;case M.DONE_SESSION:await this.completeActiveSession();return;case M.DELETE_SESSION:await this.deleteActiveSession();return;case M.REGENERATE_SESSION:await this.regenerateActiveSession();return;case M.PIN_SESSION:this.togglePinActiveSession();return;case M.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case M.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case M.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case M.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case M.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case M.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case M.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case M.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case M.OPEN_WORKSPACE:this.openWorkspace();return;case M.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case M.ADMIN_SHOW_GHCP:this.setAdminSection("providers");return;case M.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case M.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case M.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case M.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case M.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case M.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case M.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case M.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case M.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case M.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const e=this.getState().sessions.activeSessionId;if(!e){this.dispatch({type:"ui/status",text:"No session selected."});return}if(typeof this.transport.exportExecutionHistory!="function"){this.dispatch({type:"ui/status",text:"History export is not supported by this transport."});return}this.dispatch({type:"ui/status",text:"Exporting execution history..."});try{const s=await this.transport.exportExecutionHistory(e);s?.filename&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:e,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${e}/${s.filename}`}),await this.ensureFilePreview(e,s.filename,{force:!0}).catch(()=>null)),this.dispatch({type:"ui/status",text:s?.filename?`History saved as artifact ${s.filename}`:`History exported → ${s?.artifactLink||"artifact created"}`})}catch(s){this.dispatch({type:"ui/status",text:`Export failed: ${s?.message||String(s)}`})}}}function Fr(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Wg=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],zg=24,qg=32,Kg=6,ya=30,Vg=56,lr=.4,Yg=1.4,Xg=2;function Fc(t=[]){const e=Math.max(0,...t.map(h=>h.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),r=Array.from({length:e},()=>({max:0,longestToken:0,spaceCells:0}));for(let h=0;h<t.length;h+=1){const g=t[h];for(let b=0;b<e;b+=1){const y=Fr(g[b]||"");y.length>r[b].max&&(r[b].max=y.length),h>0&&/\s/.test(y)&&(r[b].spaceCells+=1);for(const S of y.split(/\s+/))S.length>r[b].longestToken&&(r[b].longestToken=S.length)}}let i=-1,a=0;for(let h=0;h<e;h+=1){const g=r[h];if(g.max<zg||g.spaceCells/n<.4)continue;const y=Fr(s[h]||"").toLowerCase(),S=Wg.some(k=>y.includes(k))?60:0,w=g.max+S;w>a&&(a=w,i=h)}if(i<0)return null;const l=r.map((h,g)=>g===i?0:Math.max(Kg,Math.min(h.max+2,qg),h.longestToken+2)),c=l.reduce((h,g)=>h+g,0),d=r[i],u=Math.max(ya,Math.min(d.max*.45,Vg,Math.max(ya,c*Yg))),p=l.map((h,g)=>g===i?u:h),m=p.reduce((h,g)=>h+g,0);if(m>0&&p[i]/m<lr){const h=m-p[i];p[i]=h*(lr/(1-lr))}const f=p.reduce((h,g)=>h+g,0);return f>0?{widths:p.map(h=>`${(h/f*100).toFixed(2)}%`),flexIndex:i,minWidth:`${Math.ceil(f+Xg)}ch`}:null}const Cn=0;function Ye(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(t[r],e[r]))return!1;return!0}function cr(){try{const t=globalThis?.process,e=t?.memoryUsage;if(typeof e?.rss=="function"){const s=Number(e.rss());return Number.isFinite(s)&&s>0?s:null}if(typeof e=="function"){const s=Number(e.call(t)?.rss);return Number.isFinite(s)&&s>0?s:null}}catch{}return null}function Qg(t){if(!Number.isFinite(t)||t<=0)return null;const e=Math.round(t/(1024*1024));return[{text:"rss ",color:"gray"},{text:`${e}M`,color:"white",bold:!0}]}function Zg(t){const e=t?.principal;if(!e)return null;const s=e.displayName||e.email||e.subject||null;return s?t?.authorization?.role==="admin"||Array.isArray(e.roles)&&e.roles.includes("admin")?`(*) ${s}`:s:null}function Jg(t,e=null,s=null){const n=[],r=typeof s=="string"?s.trim():"";r&&n.push({text:r,color:"yellow",bold:!0}),Array.isArray(t)&&t.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...t));const i=typeof e=="string"?e.trim():"";return i?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:i,color:"cyan",bold:!0}),n):n.length>0?n:null}function ey(t=2e3){const[e,s]=o.useState(()=>cr());return o.useEffect(()=>{if(cr()==null)return;const n=()=>{const i=cr();i!=null&&s(a=>a===i?a:i)};n();const r=setInterval(n,t);return()=>clearInterval(r)},[t]),o.useMemo(()=>Qg(e),[e])}function fs(t,e){return t&&e?{[t]:e}:{}}function ba(t){return typeof t=="string"?{text:t,color:"white"}:t}function $s(t,e,s,n,r,i){const a=(e.tabs||lt).map(p=>({text:p===e.activeTab?`[${p}] `:`${p} `,color:p===e.activeTab?"magenta":"gray",bold:p===e.activeTab})),l=(e.lines||[]).map(ba),c=(e.stickyLines||[]).map(ba),d=e.activeTab==="sequence"?[a,...c]:[],u=e.activeTab==="sequence"?l:[a,...l];return o.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:r,stickyLines:d,marginBottom:Cn,lines:u,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:i})}function Sa(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}o.memo(function({controller:e,maxRows:s,width:n,height:r,frame:i,versionLabel:a=null}){const l=tt(),c=ey(),d=ee(e,h=>({sessions:h.sessions,mode:h.connection?.mode||"local",brandingTitle:h.branding?.title||"PilotSwarm",focused:h.ui.focusRegion==="sessions",identityLabel:Zg(h.auth)}),Ye),u=o.useMemo(()=>Jg(c,a,d.identityLabel),[c,a,d.identityLabel]),p=o.useMemo(()=>({sessions:d.sessions,connection:{mode:d.mode},branding:{title:d.brandingTitle}}),[d.brandingTitle,d.mode,d.sessions]),m=o.useMemo(()=>Pr(p,s),[p,s]),f=o.useMemo(()=>m.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:m.map(h=>h.active?ql(h.runs,{preserveColors:!0}):h.runs),[m]);return o.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:u,color:"yellow",focused:d.focused,width:n,height:r,marginBottom:Cn,lines:f,paneId:"sessions",paneLabel:"Sessions",frame:i})});o.memo(function({controller:e,width:s,height:n,frame:r}){const i=tt(),a=ee(e,w=>{const k=w.sessions.activeSessionId;return{activeSessionId:k,activeSession:k&&w.sessions.byId[k]||null,activeHistory:k&&w.history.bySessionId.get(k)||null,activeOutbox:k&&w.outbox?.bySessionId?.[k]||null,authPrincipal:w.auth?.principal||null,branding:w.branding,connectionError:w.connection.error,connectionMode:w.connection.mode,chatScroll:w.ui.scroll.chat,focused:w.ui.focusRegion==="chat"}},Ye),l=Math.max(20,s-4),c=o.useMemo(()=>{const w=new Map;return a.activeSessionId&&a.activeHistory&&w.set(a.activeSessionId,a.activeHistory),{branding:a.branding,auth:{principal:a.authPrincipal},connection:{error:a.connectionError,mode:a.connectionMode},ui:{},sessions:{activeSessionId:a.activeSessionId,byId:fs(a.activeSessionId,a.activeSession)},history:{bySessionId:w},outbox:{bySessionId:a.activeSessionId&&a.activeOutbox?{[a.activeSessionId]:a.activeOutbox}:{}}}},[a.activeHistory,a.activeSessionId,a.activeSession,a.activeOutbox,a.authPrincipal,a.branding,a.connectionError,a.connectionMode]),d=o.useMemo(()=>mc(c,{width:l}),[l,c]),u=sl(!!d?.animateTitleRight),p=o.useMemo(()=>nl(d?.titleRight,u),[u,d?.titleRight]),m=!a.activeSessionId&&a.connectionError,f=o.useMemo(()=>m?[{kind:"markup",value:a.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:a.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:mi(c,l),[a.branding.splash,a.connectionError,l,c,m]),h=String(a.activeSession?.status||"").toLowerCase()==="running",g=tl(h),b=o.useMemo(()=>m?[]:pi(c,{spinnerFrame:g,maxWidth:l}),[c,m,g,l]),y=o.useMemo(()=>m?[]:gi(c,l),[c,m,l]),S=o.useMemo(()=>y.length>0||b.length>0?[...y,...b]:[],[y,b]);return o.createElement(i.Panel,{title:d.title,titleRight:p,color:d.color,focused:a.focused,width:s,height:n,lines:f,bottomStickyLines:S,scrollOffset:a.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:r})});const ty=o.memo(function({controller:e,width:s,height:n,shellTitle:r,focused:i=!1,frame:a,showFullscreenTitle:l=!1,embedded:c=!1}){const d=tt(),u=ee(e,_=>({activeSessionId:_.sessions.activeSessionId,activeSession:_.sessions.activeSessionId&&_.sessions.byId[_.sessions.activeSessionId]||null,sessionsFlat:_.sessions.flat,filesBySessionId:_.files.bySessionId,filesFullscreen:!!_.files.fullscreen,selectedArtifactId:_.files.selectedArtifactId,filesFilter:_.files.filter,filePreviewScroll:_.ui.scroll.filePreview}),Ye),p=Math.max(20,s-4),m=o.useMemo(()=>({sessions:{activeSessionId:u.activeSessionId,byId:u.activeSessionId&&u.activeSession?{[u.activeSessionId]:u.activeSession}:{},flat:u.sessionsFlat},files:{bySessionId:u.filesBySessionId,fullscreen:u.filesFullscreen,selectedArtifactId:u.selectedArtifactId,filter:u.filesFilter},ui:{scroll:{filePreview:u.filePreviewScroll}}}),[u]),f=o.useMemo(()=>Si(m,{listWidth:Math.max(8,p-4),previewWidth:Math.max(8,p-4)}),[p,m]),h=r||(l?f.fullscreenTitle:f.panelTitle||f.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),b=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(b,(f.listBodyLines||[]).length+2)),S=Math.max(5,g-y-1);const w=8;if(S<w){const _=w-S;y=Math.max(5,y-_),S=Math.max(5,g-y-1)}const k=Math.max(1,y-2),E=Math.max(0,f.selectedIndex-Math.floor(k/2)),x=!c&&a?{x:a.x+2,y:a.y+2,width:p,height:y}:null,v=!c&&a?{x:a.x+2,y:a.y+2+y+1,width:p,height:S}:null,P=lt.map(_=>({text:_==="files"?`[${_}] `:`${_} `,color:_==="files"?"magenta":"gray",bold:_==="files"})),N=o.createElement(d.Column,{width:p},o.createElement(d.Lines,{lines:[P]}),o.createElement(d.Panel,{title:f.listTitle,color:"gray",focused:!1,width:p,height:y,lines:f.listBodyLines||f.listLines.slice(1),scrollOffset:E,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:x}),o.createElement(d.Panel,{title:f.previewTitle,color:"gray",focused:!1,width:p,height:S,lines:f.previewLines,scrollOffset:f.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:v}));return c?N:o.createElement(d.Panel,{title:h,color:"magenta",focused:i,width:s,height:n,marginBottom:Cn,paneId:"inspector",paneLabel:"Inspector",frame:a},N)}),sy=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return o.createElement(a.Panel,{title:u.title,color:"magenta",focused:i.focused,width:s,height:n,marginBottom:Cn,paneId:"inspector",paneLabel:"Inspector",frame:r},o.createElement(ty,{controller:e,width:s,height:n,frame:r,focused:i.focused,embedded:!0}))}),ny=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,activeOrchestration:p.sessions.activeSessionId&&p.orchestration.bySessionId?.[p.sessions.activeSessionId]||null,histories:p.history.bySessionId,expandedTurns:p.ui.sequenceExpandedTurns,selectedTurn:p.ui.sequenceSelectedTurn}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},history:{bySessionId:c.histories},orchestration:{bySessionId:c.activeSessionId&&c.activeOrchestration?{[c.activeSessionId]:c.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[c.activeOrchestration,c.activeSession,c.activeSessionId,c.histories]),u=o.useMemo(()=>It(d,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,d,c.expandedTurns,c.selectedTurn]);return $s(a,u,i,s,n,r)}),ry=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,logs:p.logs}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)}),iy=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,executionHistory:p.executionHistory}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)}),oy=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,sessionsById:p.sessions.byId,sessionsFlat:p.sessions.flat,histories:p.history.bySessionId}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.histories},ui:{inspectorTab:"nodes"}}),[c.activeSessionId,c.histories,c.sessionsById,c.sessionsFlat]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)}),ay=o.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const a=tt(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,sessionStats:p.sessionStats,fleetStats:p.fleetStats,statsViewMode:p.ui.statsViewMode}),Ye),d=o.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:fs(c.activeSessionId,c.activeSession)},sessionStats:c.sessionStats,fleetStats:c.fleetStats,ui:{inspectorTab:"stats",statsViewMode:c.statsViewMode}}),[c.activeSession,c.activeSessionId,c.fleetStats,c.sessionStats,c.statsViewMode]),u=o.useMemo(()=>It(d,{width:l}),[l,d]);return $s(a,u,i,s,n,r)});o.memo(function({controller:e,width:s,height:n,frame:r}){const i=ee(e,a=>({inspectorTab:a.ui.inspectorTab,inspectorScroll:a.ui.scroll.inspector,inspectorFollowBottom:a.ui.followBottom?.inspector!==!1,focused:a.ui.focusRegion==="inspector"}),Ye);return i.inspectorTab==="files"?o.createElement(sy,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="sequence"?o.createElement(ny,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="logs"?o.createElement(ry,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="history"?o.createElement(iy,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="stats"?o.createElement(ay,{controller:e,width:s,height:n,frame:r,meta:i}):o.createElement(oy,{controller:e,width:s,height:n,frame:r,meta:i})});o.memo(function({controller:e,width:s,height:n,maxLines:r,frame:i}){const a=tt(),l=ee(e,p=>{const m=p.sessions.activeSessionId;return{sessionsById:p.sessions.byId,activeSessionId:m,activeSession:m&&p.sessions.byId[m]||null,activeHistory:m&&p.history.bySessionId.get(m)||null,scroll:p.ui.scroll.activity,followBottom:p.ui.followBottom?.activity!==!1,focused:p.ui.focusRegion==="activity",inspectorTab:p.ui.inspectorTab,nodeMapSelectedNode:p.ui.nodeMapSelectedNode,adminWorkers:p.admin?.workers,branding:p.branding,historyBySessionId:p.history.bySessionId,sessionsFlat:p.sessions.flat}},Ye),c=l.inspectorTab==="nodes",d=o.useMemo(()=>{const p=new Map;return l.activeSessionId&&l.activeHistory&&p.set(l.activeSessionId,l.activeHistory),{branding:l.branding,admin:{workers:l.adminWorkers},ui:{nodeMapSelectedNode:l.nodeMapSelectedNode},sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:c?l.historyBySessionId:p}}},[l.activeHistory,l.activeSessionId,l.sessionsById,l.adminWorkers,l.branding,l.historyBySessionId,l.nodeMapSelectedNode,l.sessionsFlat,c]),u=o.useMemo(()=>c?fc(d):bi(d,r),[r,c,d]);return o.createElement(a.Panel,{title:u.title,color:"gray",focused:l.focused,width:s,height:n,lines:u.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:i})});o.memo(function({controller:e,rows:s}){const n=tt(),r=ee(e,i=>{const a=i.sessions.activeSessionId,l=a&&i.sessions.byId[a]||null,c=a&&i.outbox?.bySessionId?.[a]?i.outbox.bySessionId[a]:[];return{prompt:i.ui.prompt,promptCursor:i.ui.promptCursor,focused:i.ui.focusRegion==="prompt",answeringQuestion:!!l?.pendingQuestion?.question,editingPending:i.ui.promptEdit?.sessionId===a,hasOutbox:c.length>0,hasPendingOutbox:c.some(d=>d?.phase==="pending")}},Ye);return o.createElement(n.Input,{label:r.answeringQuestion?"answer":r.editingPending?"pending":"you",value:r.prompt,cursorIndex:r.promptCursor,focused:r.focused,placeholder:r.answeringQuestion?"Type an answer and press Enter":r.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":r.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});o.memo(function({controller:e}){const s=tt(),n=ee(e,u=>({connected:u.connection.connected,workersOnline:u.connection.workersOnline,focusRegion:u.ui.focusRegion,inspectorTab:u.ui.inspectorTab,fullscreenPane:u.ui.fullscreenPane||null,logsAvailable:u.logs.available,logsTailing:u.logs.tailing,filesFullscreen:!!u.files.fullscreen,mode:u.connection.mode,statusText:u.ui.statusText,modal:u.ui.modal,activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,selectedIds:u.sessions.selectedIds,selectMode:u.sessions.selectMode}),Ye),r=o.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,fullscreenPane:n.fullscreenPane,statusText:n.statusText,modal:n.modal},logs:{available:n.logsAvailable,tailing:n.logsTailing},files:{fullscreen:n.filesFullscreen},sessions:{activeSessionId:n.activeSessionId,selectedIds:n.selectedIds,selectMode:n.selectMode,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}}}),[n]),i=o.useMemo(()=>hf(r),[r]),a=typeof s.getViewport=="function"?s.getViewport():{width:120},l=Math.max(20,(a.width||120)-4),c=Math.min(Math.max(18,Math.floor(l*.45)),l-8),d=Math.max(8,l-c-3);return o.createElement(s.StatusLine,{left:Sa(i.left,d),right:Sa(i.right,c)})});const ly="modulepreload",cy=function(t){return"/"+t},va={},Dc=function(e,s,n){let r=Promise.resolve();if(s&&s.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");r=c(s.map(d=>{if(d=cy(d),d in va)return;va[d]=!0;const u=d.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":ly,u||(m.as="script"),m.crossOrigin="",m.href=d,l&&m.setAttribute("nonce",l),document.head.appendChild(m),u)return new Promise((f,h)=>{m.addEventListener("load",f),m.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return r.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})},dy=920,Bc=7,uy=19,Ti=.24,Hc=16,Uc=8,Pi=224,py=190,my=48,bt=16,jc=.5,ks=jc,fy=24,hy=700,gy=5e3,yy=new Set(["low","medium","high","xhigh"]),by=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Sy=["pilotswarm_theme","pilotswarm_session_owner_filter"],vy={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},wa={sequence:uS,logs:pS,nodes:mS,history:yS,files:bS,stats:SS};function wy(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const r=n.indexOf(e),a=((r===-1?0:r)+s+n.length)%n.length;return n[a]}function Ey(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function ky(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function xy(t){return typeof t?.transport?.listArtifacts=="function"}function Iy(t){return typeof t?.transport?.deleteArtifact=="function"}function Ay(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const Ny="Session link copied to clipboard",Gc="Artifact link copied to clipboard",Cy=140,Ty="Only people with access can open this link.";function Wc(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function Tn(t,e,{fullscreen:s=!0}={}){const n=Wc(t);return!n||!e?n:`${n}&artifact=${encodeURIComponent(e)}${s?"&view=full":""}`}let Pn=[];function Pv(t){Pn=Array.isArray(t)?t:[]}function Sn(t){const e=Cc(Ai(t,Pn));navigator?.clipboard?.writeText&&navigator.clipboard.writeText(e).catch(()=>{})}function zc({url:t,keyPrefix:e,copied:s,onCopy:n}){const r=Ai(t,Pn),i=l=>l.currentTarget.select();if(r.length<=1)return o.createElement("div",{className:"ps-link-row"},o.createElement("input",{className:"ps-link-input",readOnly:!0,value:t,onFocus:i}),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(e,t)},s===e?"Copied":"Copy"));const a=`${e}:all`;return o.createElement("div",{className:"ps-link-origins"},r.map((l,c)=>{const d=`${e}:${c}`;return o.createElement("div",{className:"ps-link-origin",key:d},o.createElement("div",{className:"ps-link-origin-label"},l.label),o.createElement("div",{className:"ps-link-row"},o.createElement("input",{className:"ps-link-input",readOnly:!0,value:l.url,"aria-label":`${l.label} link`,onFocus:i}),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(d,l.url)},s===d?"Copied":"Copy")))}),o.createElement("div",{className:"ps-link-copy-all"},o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(a,Cc(r))},s===a?"Copied all":"Copy all")))}async function Py(t,e){try{const s=t.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(e))?.visibility||"private")==="private"){const r=typeof s.listSessionShares=="function"?await s.listSessionShares(e).catch(()=>[]):[];return!Array.isArray(r)||r.length===0}}catch{}return!1}function My(){if(!(typeof window>"u")){try{for(const t of by)window.localStorage.removeItem(t)}catch{}try{for(const t of Sy)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function Ft(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),typeof e.sessionDetailCollapsed=="boolean"&&(s.sessionDetailCollapsed=e.sessionDetailCollapsed),e.agentPickerUsage&&typeof e.agentPickerUsage=="object"&&!Array.isArray(e.agentPickerUsage)){const n={};for(const[i,a]of Object.entries(e.agentPickerUsage)){const l=Number(a);typeof i=="string"&&i&&Number.isFinite(l)&&l>0&&(n[i]=Math.min(Math.round(l),1e6))}const r=Object.entries(n).sort((i,a)=>a[1]-i[1]).slice(0,200);r.length>0&&(s.agentPickerUsage=Object.fromEntries(r))}if(typeof e.touchScale=="boolean"&&(s.touchScale=e.touchScale),typeof e.touchScaleMobile=="boolean"&&(s.touchScaleMobile=e.touchScaleMobile),Ee(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Ee(n,"includeShared")?n:{...n,includeShared:!0}}if(Ee(e,"layoutAdjustments")&&(s.layoutAdjustments=ei(e.layoutAdjustments)),Ee(e,"pinnedSessionIds")&&(s.pinnedSessionIds=cn(e.pinnedSessionIds)),Ee(e,"sessionOrder")&&(s.sessionOrder=ti(e.sessionOrder)),Ee(e,"collapsedSessionIds")&&(s.collapsedSessionIds=_y(e.collapsedSessionIds)),Ee(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return(e.rightPaneMode==="canvas"||e.rightPaneMode==="panes")&&(s.rightPaneMode=e.rightPaneMode),Ee(e,"desktopPanes")&&e.desktopPanes&&typeof e.desktopPanes=="object"&&(s.desktopPanes={canvasOpen:e.desktopPanes.canvasOpen===!0,diagnosticsOpen:e.desktopPanes.diagnosticsOpen===!0,zen:e.desktopPanes.zen===!0}),Ee(e,"canvasPrefs")&&(s.canvasPrefs=si(e.canvasPrefs)),s}function Ls(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function vn(){return Ls()?"touchScaleMobile":"touchScale"}function wn(){return Ls()?"touchScale":"touchScaleMobile"}function _y(t){if(t instanceof Set){const n=[];for(const r of t){const i=String(r||"").trim();i&&n.push(i)}return n.sort(),n}if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s.sort(),s}function Ee(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function dr(t,e=null,s=null,n=null){return Ft({themeId:t.themeId,[vn()]:t.touchScale,sessionDetailCollapsed:t.sessionDetailCollapsed,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust,canvasPaneAdjust:t.canvasPaneAdjust,diagnosticsPaneAdjust:t.diagnosticsPaneAdjust,diagnosticsSplitAdjust:t.diagnosticsSplitAdjust},pinnedSessionIds:t.pinnedIds,sessionOrder:t.manualOrder,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,...Ls()?{...s==="canvas"||s==="panes"?{rightPaneMode:s}:{},...n&&typeof n=="object"?{desktopPanes:n}:{}}:{rightPaneMode:t.canvasOpen?"canvas":"panes",desktopPanes:{canvasOpen:t.canvasOpen===!0,diagnosticsOpen:t.diagnosticsOpen===!0,zen:t.canvasZen===!0}},canvasPrefs:t.canvasPrefs,...typeof e=="boolean"?{[wn()]:e}:{},...t.agentPickerUsage&&typeof t.agentPickerUsage=="object"&&Object.keys(t.agentPickerUsage).length>0?{agentPickerUsage:t.agentPickerUsage}:{}})}function Ea(t,e=null,s=null){return Ft({themeId:t?.ui?.themeId,[vn()]:t?.ui?.touchScale,sessionDetailCollapsed:t?.ui?.sessionDetailCollapsed,sessionOwnerFilter:bn(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,...Ls()?s==="canvas"||s==="panes"?{rightPaneMode:s}:{}:{rightPaneMode:t?.ui?.rightPaneMode,desktopPanes:{canvasOpen:t?.ui?.canvasOpen===!0,diagnosticsOpen:t?.ui?.diagnosticsOpen===!0,zen:t?.ui?.canvasZen===!0}},canvasPrefs:t?.canvas?.prefs,...typeof e=="boolean"?{[wn()]:e}:{}})}function Ry(t,e){const s=Ft(t),n=Ft(e);return Ft({themeId:Ee(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Ee(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Ee(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Ee(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:Ee(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Ee(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Ee(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Ee(s,"desktopPanes")?{desktopPanes:s.desktopPanes}:{},...Ee(s,"rightPaneMode")?{rightPaneMode:s.rightPaneMode}:{},...Ee(s,"canvasPrefs")?{canvasPrefs:s.canvasPrefs}:{},...Ee(s,vn())?{touchScale:s[vn()]}:Ls()&&Ee(s,"touchScale")?{touchScale:s.touchScale}:{},...Ee(s,"sessionDetailCollapsed")?{sessionDetailCollapsed:s.sessionDetailCollapsed}:{},...Ee(s,"agentPickerUsage")?{agentPickerUsage:s.agentPickerUsage}:{}})}async function $y(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:Ft(e)})}function Mi(t){return xy(t)?lt:lt.filter(e=>e!=="files")}function Le(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(t[r],e[r]))return!1;return!0}function rs(t,e,s){return Math.max(e,Math.min(s,t))}const Qs=120,_i=640,Ri=320;function Dr(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Hc-Uc*2),n=s*Ti,r=Math.max(0,s-Pi);return{minAdjust:-n,maxAdjust:r-n}}function Ly(t,e){const s=Dr(t),n=Math.max(0,Number(t)||0),i=Math.max(0,n-Hc-Uc*2)*Ti;return rs(i+(Number(e)||0),0,i+s.maxAdjust)}function Oy(t){return t<=my?"hidden":t<=py?"compact":"wrap"}function qc(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:ts(t?.ui?.prompt||"")}function Mn(t){return Cs({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,qc(t),t.ui.layout?.sessionPaneAdjust??0)}function Fy(t,e,s=!1){return Math.max(20,t-(s?6:4))}function Kc({slack:t=1,debounceMs:e=120}={}){const[s,n]=o.useState(null),r=o.useRef({node:null,observer:null,timer:null,frame:null}),i=o.useCallback(a=>{const l=r.current;if(l.observer&&(l.observer.disconnect(),l.observer=null),l.timer&&(window.clearTimeout(l.timer),l.timer=null),l.frame&&(cancelAnimationFrame(l.frame),l.frame=null),l.node=a,!a||typeof window>"u"||typeof ResizeObserver>"u")return;const c=()=>{if(l.timer=null,l.node!==a||!a.isConnected)return;const u=a.querySelector(".ps-line")||a,p=window.getComputedStyle(u),m=document.createElement("span");m.style.cssText="position:absolute;visibility:hidden;white-space:pre;",m.style.fontFamily=p.fontFamily,m.style.fontSize=p.fontSize,m.style.fontWeight=p.fontWeight,m.style.letterSpacing=p.letterSpacing,m.textContent="0".repeat(100),a.appendChild(m);const f=m.getBoundingClientRect().width/100||0;if(m.remove(),!(f>0))return;const h=window.getComputedStyle(a),g=a.clientWidth-(parseFloat(h.paddingLeft)||0)-(parseFloat(h.paddingRight)||0);if(!(g>50))return;const b=Math.max(20,Math.floor(g/f)-t);n(y=>y===b?y:b)},d=()=>{l.timer&&window.clearTimeout(l.timer),l.timer=window.setTimeout(c,e)};l.frame=requestAnimationFrame(c),l.observer=new ResizeObserver(d);try{l.observer.observe(a,{box:"content-box"})}catch{l.observer.observe(a)}},[t,e]);return[s,i]}function je(t){const e=[],s=n=>{const r=String(n||"");return!r.includes("\\n")||r.includes(`
|
|
83
83
|
`)?r:r.replace(/\\n/g,`
|
|
84
84
|
`)};for(const n of t||[]){if(n?.kind==="markup"){const r=n.splashAlt?[{text:n.value,variant:"desktop"},{text:n.splashAlt,variant:"mobile"}]:[{text:n.value,variant:null}];for(const i of r)for(const a of ol(i.text||""))e.push({kind:"runs",runs:a,preserve:!0,splashVariant:i.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){e.push(n);continue}if(n?.kind==="runs"){const r=Array.isArray(n.runs)?n.runs:[];if(r.length===1){const i=r[0]||{},a=s(i.text||"");if(a.includes(`
|
|
85
85
|
`)){const l=a.split(`
|
|
86
86
|
`);for(const c of l)e.push({kind:"runs",runs:[{...i,text:c}]});continue}e.push({kind:"runs",runs:[{...i,text:a}]});continue}e.push({kind:"runs",runs:r.map(i=>({...i,text:s(i?.text||"")}))});continue}if(Array.isArray(n)){e.push({kind:"runs",runs:n});continue}if(n&&typeof n=="object"&&typeof n.text=="string"){const r=s(n.text);if(r.includes(`
|
|
87
87
|
`)){const i=r.split(`
|
|
88
|
-
`);for(const a of i)e.push({kind:"text",...n,text:a});continue}e.push({kind:"text",...n,text:r});continue}e.push({kind:"text",...n})}return e}function Ve(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Vc(t=[]){return t.map(e=>String(e?.text||"")).join("")}function ka(t){return Array.isArray(t)?Vc(t):String(t||"")}function xa(t,e=40){if(!Array.isArray(t)){const i=String(t||"");return[{text:i.length>e?`${i.slice(0,e-1)}…`:i,color:"white",bold:!0}]}const s=[],n=i=>/^[\s·—-]+$/.test(String(i?.text||""));let r=Math.max(8,e);for(const i of t){if(r<=0)break;if(i?.color==="gray"&&s.length>0&&!n(i))continue;const l=String(i?.text||"");if(!l)continue;if(n(i)&&r<l.length+2)break;const c=l.length>r&&r>1?`${l.slice(0,r-1)}…`:l.slice(0,r);c&&(s.push({...i,text:c}),r-=c.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function Dy(t){typeof document>"u"||(t?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function By(t){const e=ft(t);if(!e||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",e.page.background),s.style.setProperty("--ps-page-foreground",e.page.foreground),s.style.setProperty("--ps-surface",e.tui.surface),s.style.setProperty("--ps-background",e.tui.background),s.style.setProperty("--ps-foreground",e.tui.foreground),s.style.setProperty("--ps-muted",e.tui.gray),s.style.setProperty("--ps-border",e.tui.border||e.tui.gray),s.style.setProperty("--ps-selection-background",e.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",e.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",e.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",e.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",e.page.modalBackdrop),s.style.setProperty("--ps-modal-background",e.page.modalBackground),s.style.setProperty("--ps-modal-border",e.page.modalBorder),s.style.setProperty("--ps-modal-foreground",e.page.modalForeground),s.style.setProperty("--ps-modal-muted",e.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",e.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",e.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",e.page.modalSelectedForeground),s.style.setProperty("--ps-accent",e.tui.cyan),s.style.setProperty("--ps-success",e.tui.green),s.style.setProperty("--ps-warning",e.tui.yellow),s.style.setProperty("--ps-danger",e.tui.red),s.dataset.psTheme=e.id}function Ia(t){const[e,s]=o.useState({width:0,height:0});return o.useLayoutEffect(()=>{const n=t.current;if(!n)return;const r=()=>{s({width:n.clientWidth,height:n.clientHeight})};r();const i=new ResizeObserver(r);return i.observe(n),window.addEventListener("resize",r),()=>{i.disconnect(),window.removeEventListener("resize",r)}},[t]),e}function Hy(t){const e=Math.max(320,t.width||window.innerWidth||1280),s=Math.max(320,t.height||window.innerHeight||800);return{width:Math.max(40,Math.floor(e/Bc)),height:Math.max(18,Math.floor(s/uy))}}function Uy(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function jy(t){return Uy(t)<=jc}function Gy(t,e,s,n=!1){if(!t)return 0;const r=Math.max(0,t.scrollHeight-t.clientHeight);if(n)return Math.max(0,Math.min(t.scrollTop,r));const i=Math.max(0,Number(e)||0)*bt;return s==="bottom"?Math.max(0,r-i):Math.min(r,i)}function Wy(t,e,s,n,r,i,{stickyBottom:a=!1}={}){const l=o.useMemo(()=>je(e),[e]),c=o.useRef(null),d=o.useRef({scrollMode:n,scrollOffset:s}),u=o.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),p=o.useRef({width:null,height:null}),[m,f]=o.useState(0);o.useLayoutEffect(()=>{const E=t.current;if(!E||typeof ResizeObserver>"u")return;p.current={width:E.clientWidth,height:E.clientHeight};const x=new ResizeObserver(()=>{const v={width:E.clientWidth,height:E.clientHeight},P=p.current;v.width===P.width&&v.height===P.height||(p.current=v,f(N=>N+1))});return x.observe(E),()=>x.disconnect()},[t]),o.useLayoutEffect(()=>{const E=t.current;if(!E)return;const x=d.current,v=u.current,P=typeof performance<"u"?performance.now():Date.now(),N=v.touching||P-(v.lastUserScrollAt||0)<hy,_=v.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-v.lastDispatchedOffset)<2;if(N&&n===x?.scrollMode&&(s===x?.scrollOffset||_)){d.current={scrollMode:n,scrollOffset:s};return}const D=a&&n==="top"&&x?.scrollMode==="top"&&x?.scrollOffset===s,L=Gy(E,s,n,D);if(Math.abs(E.scrollTop-L)>ks){const I={target:L};c.current=I,E.scrollTop=L,window.requestAnimationFrame(()=>{c.current===I&&(c.current=null)})}d.current={scrollMode:n,scrollOffset:s}},[l,t,n,s,a,m]);const h=Ky(E=>{i.dispatch({type:"ui/scroll",pane:r,offset:E})}),g=o.useCallback(()=>{const E=t.current;if(!E||!r)return;const x=c.current;if(x){if(Math.abs(E.scrollTop-x.target)<=ks)return;c.current=null}u.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const v=Math.max(0,E.scrollHeight-E.clientHeight);if(v<=0)return;if(a&&typeof i.updatePaneScrollFromViewport=="function"){const N=Math.max(0,E.scrollTop)/bt;u.current.lastDispatchedOffset=N,i.updatePaneScrollFromViewport(r,N,{atBottom:jy(E)});return}const P=n==="bottom"?Math.max(0,v-E.scrollTop):Math.max(0,E.scrollTop);u.current.lastDispatchedOffset=P/bt,h(P/bt),r==="chat"&&n==="bottom"&&E.scrollTop<=ks&&i.armChatTopHistoryLoad?.()},[i,h,r,t,n,a]),b=o.useCallback(E=>{const x=t.current;if(!x||r!=="chat"||n!=="bottom"||E.deltaY>=0||x.scrollTop>ks)return;const v=Math.max(0,x.scrollHeight-x.clientHeight);i.handleChatTopHistoryScrollIntent?.(v/bt)},[i,r,t,n]),y=o.useRef({startY:null,fired:!1}),S=o.useCallback(E=>{u.current.touching=!0,!(r!=="chat"||n!=="bottom")&&(y.current={startY:E.touches?.[0]?.clientY??null,fired:!1})},[r,n]),w=o.useCallback(()=>{u.current.touching=!1,u.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),k=o.useCallback(E=>{const x=t.current,v=y.current;if(!x||r!=="chat"||n!=="bottom"||v.fired||v.startY==null||x.scrollTop>ks)return;const P=E.touches?.[0]?.clientY;if(P==null||P-v.startY<fy)return;v.fired=!0;const N=Math.max(0,x.scrollHeight-x.clientHeight);i.handleChatTopHistoryScrollIntent?.(N/bt+1,{force:!0})},[i,r,t,n]);return{normalizedLines:l,onScroll:g,onWheel:b,onTouchStart:S,onTouchMove:k,onTouchEnd:w}}function ze({runs:t,theme:e}){return o.createElement(o.Fragment,null,(t||[]).map((s,n,r)=>{const i=n>0&&!!En(r[n-1]?.href),a={color:Ve(e,s.color),backgroundColor:Ve(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return o.createElement("span",{key:`${n}:rule`,className:"ps-line-trailing-rule",style:a},s.text||"");const l=String(s?.href||"").trim(),c=/^https?:\/\//i.test(l),d=En(l);if(d)return o.createElement(sd,{key:`${n}:${s.text||""}`,artifactRef:d,style:a});const u=i?Zc(s.text||""):s.text||"";return i&&!u?null:c?o.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:l,target:"_blank",rel:"noreferrer",style:a},u):o.createElement("span",{key:`${n}:${s.text||""}`,style:a},u)}))}function zy({line:t,theme:e}){const s=String(t?.body||"").trim();return o.createElement("details",{className:"ps-system-notice"},o.createElement("summary",{className:"ps-system-notice-summary",style:{color:Ve(e,t?.color)||"var(--ps-muted)"}},o.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?o.createElement("div",{className:"ps-system-notice-body"},o.createElement(Bi,{content:s,theme:e})):null)}function qy({line:t,theme:e}){const s=String(t?.canvasActionPayload||"").trim(),n=t?.canvasActionName||"action",r=String(t?.canvasActionDetail||"").trim(),i=String(t?.canvasActionTime||"").trim();return o.createElement("details",{className:"ps-system-notice ps-canvas-action"},o.createElement("summary",{className:"ps-system-notice-summary ps-canvas-action-summary",style:{color:Ve(e,"gray")||"var(--ps-muted)"}},o.createElement("span",{className:"ps-canvas-action-tag"},"canvas"),o.createElement("span",{className:"ps-system-notice-summary-text"},`${n}${r?` — ${r}`:""}`),i?o.createElement("span",{className:"ps-canvas-action-time"},i):null),s?o.createElement("div",{className:"ps-system-notice-body"},o.createElement("pre",{className:"ps-canvas-action-payload"},s)):null)}function Ky(t){const e=o.useRef(0),s=o.useRef(null),n=o.useRef(t);return n.current=t,o.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),o.useCallback((...r)=>{s.current=r,!e.current&&(e.current=requestAnimationFrame(()=>{e.current=0;const i=s.current;s.current=null,i&&n.current(...i)}))},[])}const We=o.memo(function({line:e,theme:s,className:n=""}){const r=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?o.createElement(zy,{line:e,theme:s}):e.canvasAction?o.createElement(qy,{line:e,theme:s}):e.kind==="runs"?o.createElement("div",{className:r},o.createElement(ze,{runs:e.runs,theme:s})):o.createElement("div",{className:r,style:{color:Ve(s,e.color),backgroundColor:Ve(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):o.createElement("div",{className:r}," ")});function Xe(t){return t?t.kind==="runs"?Vc(t.runs):String(t.text||""):""}function Yc(t,e,s,n){const r=o.useRef(!1);return o.useLayoutEffect(()=>{const i=t.current;if(!i||!s)return;const a=Math.max(0,i.scrollHeight-i.clientHeight),l=Math.min(a,Math.max(0,Number(e)||0)*bt);Math.abs(i.scrollTop-l)>2&&(r.current=!0,i.scrollTop=l,window.requestAnimationFrame(()=>{r.current=!1}))},[t,e,s]),o.useCallback(i=>{if(r.current)return;const a=t.current;!a||!s||i&&i.target!==a||a.scrollHeight<=a.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,a.scrollTop)/bt})},[n,s,t])}const Vy={js:"js",jsx:"js",mjs:"js",cjs:"js",javascript:"js",ts:"js",tsx:"js",typescript:"js",json:"json",jsonc:"json",py:"python",python:"python",sh:"shell",bash:"shell",zsh:"shell",shell:"shell",console:"shell",sql:"sql",postgres:"sql",postgresql:"sql",psql:"sql",rs:"rust",rust:"rust",go:"go",golang:"go",yaml:"yaml",yml:"yaml",css:"css",scss:"css"},Yy=new Set(["diff","patch","udiff"]),Xy=/\.(patch|diff)$/i,$i=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Li=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,Qy={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",bmp:"image/bmp",svg:"image/svg+xml",ico:"image/x-icon"};function Zy(t){const e=/\.([a-z0-9]+)$/i.exec(String(t||""));return e&&Qy[e[1].toLowerCase()]||null}const Jy={js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",json:"json",jsonl:"json",py:"python",rs:"rust",go:"go",java:"java",rb:"ruby",sh:"bash",bash:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",toml:"toml",sql:"sql",css:"css",html:"html",xml:"xml"};function eb(t){const e=String(t||"");if(!/^---[ \t]*\r?\n/.test(e))return e;const s=/\r?\n---[ \t]*(\r?\n|$)/.exec(e.slice(3));return s?e.slice(3+s.index+s[0].length):e}const tb=/\.(html?|xhtml)$/i;function Xc(t,e){return tb.test(String(t||""))?!0:/^(text\/html|application\/xhtml\+xml)$/i.test(String(e||"").trim().split(";")[0])}const sb=/\.(csv|tsv)$/i;function Qc(t,e){return sb.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const ur=2e3;function nb(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function rb({content:t,filename:e}){const[s,n]=o.useState(null),r=o.useRef(null),i=o.useRef(null),a=o.useRef(null);o.useEffect(()=>{let k=!1;return n(null),Dc(()=>import("./papaparse.min-DnG1sqyK.js").then(E=>E.p),[]).then(E=>{if(k)return;const x=E.default||E,v=/\.tsv$/i.test(String(e||""))?" ":"",P=x.parse(String(t||"").trim(),{delimiter:v,skipEmptyLines:"greedy"});n({rows:P.data||[],errors:P.errors||[]})}).catch(()=>{k||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{k=!0}},[t,e]),o.useEffect(()=>{const k=()=>{a.current=null};return window.addEventListener("mouseup",k),()=>window.removeEventListener("mouseup",k)},[]);const l=o.useCallback((k,E)=>{if(!k||!E)return;const x=window.getSelection();if(!x)return;const v=!!(k.compareDocumentPosition(E)&Node.DOCUMENT_POSITION_PRECEDING),P=document.createRange();P.setStartBefore(v?E:k),P.setEndAfter(v?k:E),x.removeAllRanges(),x.addRange(P)},[]),c=k=>k.target?.closest?k.target.closest("td,th"):null,d=o.useCallback(k=>{if(k.button!==0)return;const E=c(k);E&&(k.preventDefault(),r.current?.focus(),a.current=E,l(E,E))},[l]),u=o.useCallback(k=>{if(!a.current||!(k.buttons&1))return;const E=c(k);E&&l(a.current,E)},[l]),p=o.useCallback(k=>{if(!(k.metaKey||k.ctrlKey)||k.altKey||k.key!=="a"&&k.key!=="A")return;const E=i.current,x=window.getSelection();if(!E||!x)return;k.preventDefault(),k.stopPropagation();const v=document.createRange();v.selectNodeContents(E),x.removeAllRanges(),x.addRange(v)},[]),m=o.useCallback(k=>{const E=i.current,x=window.getSelection();if(!E||!x||x.rangeCount===0)return;const v=x.getRangeAt(0),P=new Map;for(const N of E.querySelectorAll("th,td")){if(!v.intersectsNode(N))continue;const _=N.parentElement;P.has(_)||P.set(_,[]),P.get(_).push(nb(N.textContent))}P.size!==0&&(k.clipboardData.setData("text/plain",Array.from(P.values(),N=>N.join(" ")).join(`
|
|
88
|
+
`);for(const a of i)e.push({kind:"text",...n,text:a});continue}e.push({kind:"text",...n,text:r});continue}e.push({kind:"text",...n})}return e}function Ve(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Vc(t=[]){return t.map(e=>String(e?.text||"")).join("")}function ka(t){return Array.isArray(t)?Vc(t):String(t||"")}function xa(t,e=40){if(!Array.isArray(t)){const i=String(t||"");return[{text:i.length>e?`${i.slice(0,e-1)}…`:i,color:"white",bold:!0}]}const s=[],n=i=>/^[\s·—-]+$/.test(String(i?.text||""));let r=Math.max(8,e);for(const i of t){if(r<=0)break;if(i?.color==="gray"&&s.length>0&&!n(i))continue;const l=String(i?.text||"");if(!l)continue;if(n(i)&&r<l.length+2)break;const c=l.length>r&&r>1?`${l.slice(0,r-1)}…`:l.slice(0,r);c&&(s.push({...i,text:c}),r-=c.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function Dy(t){typeof document>"u"||(t?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function By(t){const e=ft(t);if(!e||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",e.page.background),s.style.setProperty("--ps-page-foreground",e.page.foreground),s.style.setProperty("--ps-surface",e.tui.surface),s.style.setProperty("--ps-background",e.tui.background),s.style.setProperty("--ps-foreground",e.tui.foreground),s.style.setProperty("--ps-muted",e.tui.gray),s.style.setProperty("--ps-border",e.tui.border||e.tui.gray),s.style.setProperty("--ps-selection-background",e.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",e.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",e.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",e.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",e.page.modalBackdrop),s.style.setProperty("--ps-modal-background",e.page.modalBackground),s.style.setProperty("--ps-modal-border",e.page.modalBorder),s.style.setProperty("--ps-modal-foreground",e.page.modalForeground),s.style.setProperty("--ps-modal-muted",e.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",e.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",e.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",e.page.modalSelectedForeground),s.style.setProperty("--ps-accent",e.tui.cyan),s.style.setProperty("--ps-success",e.tui.green),s.style.setProperty("--ps-warning",e.tui.yellow),s.style.setProperty("--ps-danger",e.tui.red),s.dataset.psTheme=e.id}function Ia(t){const[e,s]=o.useState({width:0,height:0});return o.useLayoutEffect(()=>{const n=t.current;if(!n)return;const r=()=>{s({width:n.clientWidth,height:n.clientHeight})};r();const i=new ResizeObserver(r);return i.observe(n),window.addEventListener("resize",r),()=>{i.disconnect(),window.removeEventListener("resize",r)}},[t]),e}function Hy(t){const e=Math.max(320,t.width||window.innerWidth||1280),s=Math.max(320,t.height||window.innerHeight||800);return{width:Math.max(40,Math.floor(e/Bc)),height:Math.max(18,Math.floor(s/uy))}}function Uy(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function jy(t){return Uy(t)<=jc}function Gy(t,e,s,n=!1){if(!t)return 0;const r=Math.max(0,t.scrollHeight-t.clientHeight);if(n)return Math.max(0,Math.min(t.scrollTop,r));const i=Math.max(0,Number(e)||0)*bt;return s==="bottom"?Math.max(0,r-i):Math.min(r,i)}function Wy(t,e,s,n,r,i,{stickyBottom:a=!1}={}){const l=o.useMemo(()=>je(e),[e]),c=o.useRef(null),d=o.useRef({scrollMode:n,scrollOffset:s}),u=o.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),p=o.useRef({width:null,height:null}),[m,f]=o.useState(0);o.useLayoutEffect(()=>{const E=t.current;if(!E||typeof ResizeObserver>"u")return;p.current={width:E.clientWidth,height:E.clientHeight};const x=new ResizeObserver(()=>{const v={width:E.clientWidth,height:E.clientHeight},P=p.current;v.width===P.width&&v.height===P.height||(p.current=v,f(N=>N+1))});return x.observe(E),()=>x.disconnect()},[t]),o.useLayoutEffect(()=>{const E=t.current;if(!E)return;const x=d.current,v=u.current,P=typeof performance<"u"?performance.now():Date.now(),N=v.touching||P-(v.lastUserScrollAt||0)<hy,_=v.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-v.lastDispatchedOffset)<2;if(N&&n===x?.scrollMode&&(s===x?.scrollOffset||_)){d.current={scrollMode:n,scrollOffset:s};return}const D=a&&n==="top"&&x?.scrollMode==="top"&&x?.scrollOffset===s,L=Gy(E,s,n,D);if(Math.abs(E.scrollTop-L)>ks){const I={target:L};c.current=I,E.scrollTop=L,window.requestAnimationFrame(()=>{c.current===I&&(c.current=null)})}d.current={scrollMode:n,scrollOffset:s}},[l,t,n,s,a,m]);const h=Ky(E=>{i.dispatch({type:"ui/scroll",pane:r,offset:E})}),g=o.useCallback(()=>{const E=t.current;if(!E||!r)return;const x=c.current;if(x){if(Math.abs(E.scrollTop-x.target)<=ks)return;c.current=null}u.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const v=Math.max(0,E.scrollHeight-E.clientHeight);if(v<=0)return;if(a&&typeof i.updatePaneScrollFromViewport=="function"){const N=Math.max(0,E.scrollTop)/bt;u.current.lastDispatchedOffset=N,i.updatePaneScrollFromViewport(r,N,{atBottom:jy(E)});return}const P=n==="bottom"?Math.max(0,v-E.scrollTop):Math.max(0,E.scrollTop);u.current.lastDispatchedOffset=P/bt,h(P/bt),r==="chat"&&n==="bottom"&&E.scrollTop<=ks&&i.armChatTopHistoryLoad?.()},[i,h,r,t,n,a]),b=o.useCallback(E=>{const x=t.current;if(!x||r!=="chat"||n!=="bottom"||E.deltaY>=0||x.scrollTop>ks)return;const v=Math.max(0,x.scrollHeight-x.clientHeight);i.handleChatTopHistoryScrollIntent?.(v/bt)},[i,r,t,n]),y=o.useRef({startY:null,fired:!1}),S=o.useCallback(E=>{u.current.touching=!0,!(r!=="chat"||n!=="bottom")&&(y.current={startY:E.touches?.[0]?.clientY??null,fired:!1})},[r,n]),w=o.useCallback(()=>{u.current.touching=!1,u.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),k=o.useCallback(E=>{const x=t.current,v=y.current;if(!x||r!=="chat"||n!=="bottom"||v.fired||v.startY==null||x.scrollTop>ks)return;const P=E.touches?.[0]?.clientY;if(P==null||P-v.startY<fy)return;v.fired=!0;const N=Math.max(0,x.scrollHeight-x.clientHeight);i.handleChatTopHistoryScrollIntent?.(N/bt+1,{force:!0})},[i,r,t,n]);return{normalizedLines:l,onScroll:g,onWheel:b,onTouchStart:S,onTouchMove:k,onTouchEnd:w}}function ze({runs:t,theme:e}){return o.createElement(o.Fragment,null,(t||[]).map((s,n,r)=>{const i=n>0&&!!En(r[n-1]?.href),a={color:Ve(e,s.color),backgroundColor:Ve(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return o.createElement("span",{key:`${n}:rule`,className:"ps-line-trailing-rule",style:a},s.text||"");const l=String(s?.href||"").trim(),c=/^https?:\/\//i.test(l),d=En(l);if(d)return o.createElement(sd,{key:`${n}:${s.text||""}`,artifactRef:d,style:a});const u=i?Zc(s.text||""):s.text||"";return i&&!u?null:c?o.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:l,target:"_blank",rel:"noreferrer",style:a},u):o.createElement("span",{key:`${n}:${s.text||""}`,style:a},u)}))}function zy({line:t,theme:e}){const s=String(t?.body||"").trim();return o.createElement("details",{className:"ps-system-notice"},o.createElement("summary",{className:"ps-system-notice-summary",style:{color:Ve(e,t?.color)||"var(--ps-muted)"}},o.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?o.createElement("div",{className:"ps-system-notice-body"},o.createElement(Bi,{content:s,theme:e})):null)}function qy({line:t,theme:e}){const s=String(t?.canvasActionPayload||"").trim(),n=t?.canvasActionName||"action",r=String(t?.canvasActionDetail||"").trim(),i=String(t?.canvasActionTime||"").trim();return o.createElement("details",{className:"ps-system-notice ps-canvas-action"},o.createElement("summary",{className:"ps-system-notice-summary ps-canvas-action-summary",style:{color:Ve(e,"gray")||"var(--ps-muted)"}},o.createElement("span",{className:"ps-canvas-action-tag"},"canvas"),o.createElement("span",{className:"ps-system-notice-summary-text"},`${n}${r?` — ${r}`:""}`),i?o.createElement("span",{className:"ps-canvas-action-time"},i):null),s?o.createElement("div",{className:"ps-system-notice-body"},o.createElement("pre",{className:"ps-canvas-action-payload"},s)):null)}function Ky(t){const e=o.useRef(0),s=o.useRef(null),n=o.useRef(t);return n.current=t,o.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),o.useCallback((...r)=>{s.current=r,!e.current&&(e.current=requestAnimationFrame(()=>{e.current=0;const i=s.current;s.current=null,i&&n.current(...i)}))},[])}const We=o.memo(function({line:e,theme:s,className:n=""}){const r=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?o.createElement(zy,{line:e,theme:s}):e.canvasAction?o.createElement(qy,{line:e,theme:s}):e.kind==="runs"?o.createElement("div",{className:r},o.createElement(ze,{runs:e.runs,theme:s})):o.createElement("div",{className:r,style:{color:Ve(s,e.color),backgroundColor:Ve(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):o.createElement("div",{className:r}," ")});function Xe(t){return t?t.kind==="runs"?Vc(t.runs):String(t.text||""):""}function Yc(t,e,s,n){const r=o.useRef(!1);return o.useLayoutEffect(()=>{const i=t.current;if(!i||!s)return;const a=Math.max(0,i.scrollHeight-i.clientHeight),l=Math.min(a,Math.max(0,Number(e)||0)*bt);Math.abs(i.scrollTop-l)>2&&(r.current=!0,i.scrollTop=l,window.requestAnimationFrame(()=>{r.current=!1}))},[t,e,s]),o.useCallback(i=>{if(r.current)return;const a=t.current;!a||!s||i&&i.target!==a||a.scrollHeight<=a.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,a.scrollTop)/bt})},[n,s,t])}const Vy={js:"js",jsx:"js",mjs:"js",cjs:"js",javascript:"js",ts:"js",tsx:"js",typescript:"js",json:"json",jsonc:"json",py:"python",python:"python",sh:"shell",bash:"shell",zsh:"shell",shell:"shell",console:"shell",sql:"sql",postgres:"sql",postgresql:"sql",psql:"sql",rs:"rust",rust:"rust",go:"go",golang:"go",yaml:"yaml",yml:"yaml",css:"css",scss:"css"},Yy=new Set(["diff","patch","udiff"]),Xy=/\.(patch|diff)$/i,$i=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Li=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,Qy={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",bmp:"image/bmp",svg:"image/svg+xml",ico:"image/x-icon"};function Zy(t){const e=/\.([a-z0-9]+)$/i.exec(String(t||""));return e&&Qy[e[1].toLowerCase()]||null}const Jy={js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",json:"json",jsonl:"json",py:"python",rs:"rust",go:"go",java:"java",rb:"ruby",sh:"bash",bash:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",toml:"toml",sql:"sql",css:"css",html:"html",xml:"xml"};function eb(t){const e=String(t||"");if(!/^---[ \t]*\r?\n/.test(e))return e;const s=/\r?\n---[ \t]*(\r?\n|$)/.exec(e.slice(3));return s?e.slice(3+s.index+s[0].length):e}const tb=/\.(html?|xhtml)$/i;function Xc(t,e){return tb.test(String(t||""))?!0:/^(text\/html|application\/xhtml\+xml)$/i.test(String(e||"").trim().split(";")[0])}const sb=/\.(csv|tsv)$/i;function Qc(t,e){return sb.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const ur=2e3;function nb(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function rb({content:t,filename:e}){const[s,n]=o.useState(null),r=o.useRef(null),i=o.useRef(null),a=o.useRef(null);o.useEffect(()=>{let k=!1;return n(null),Dc(()=>import("./papaparse.min-CzTZ22jn.js").then(E=>E.p),[]).then(E=>{if(k)return;const x=E.default||E,v=/\.tsv$/i.test(String(e||""))?" ":"",P=x.parse(String(t||"").trim(),{delimiter:v,skipEmptyLines:"greedy"});n({rows:P.data||[],errors:P.errors||[]})}).catch(()=>{k||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{k=!0}},[t,e]),o.useEffect(()=>{const k=()=>{a.current=null};return window.addEventListener("mouseup",k),()=>window.removeEventListener("mouseup",k)},[]);const l=o.useCallback((k,E)=>{if(!k||!E)return;const x=window.getSelection();if(!x)return;const v=!!(k.compareDocumentPosition(E)&Node.DOCUMENT_POSITION_PRECEDING),P=document.createRange();P.setStartBefore(v?E:k),P.setEndAfter(v?k:E),x.removeAllRanges(),x.addRange(P)},[]),c=k=>k.target?.closest?k.target.closest("td,th"):null,d=o.useCallback(k=>{if(k.button!==0)return;const E=c(k);E&&(k.preventDefault(),r.current?.focus(),a.current=E,l(E,E))},[l]),u=o.useCallback(k=>{if(!a.current||!(k.buttons&1))return;const E=c(k);E&&l(a.current,E)},[l]),p=o.useCallback(k=>{if(!(k.metaKey||k.ctrlKey)||k.altKey||k.key!=="a"&&k.key!=="A")return;const E=i.current,x=window.getSelection();if(!E||!x)return;k.preventDefault(),k.stopPropagation();const v=document.createRange();v.selectNodeContents(E),x.removeAllRanges(),x.addRange(v)},[]),m=o.useCallback(k=>{const E=i.current,x=window.getSelection();if(!E||!x||x.rangeCount===0)return;const v=x.getRangeAt(0),P=new Map;for(const N of E.querySelectorAll("th,td")){if(!v.intersectsNode(N))continue;const _=N.parentElement;P.has(_)||P.set(_,[]),P.get(_).push(nb(N.textContent))}P.size!==0&&(k.clipboardData.setData("text/plain",Array.from(P.values(),N=>N.join(" ")).join(`
|
|
89
89
|
`)),k.preventDefault())},[]);if(!s)return o.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,String(t||"")));const[f,...h]=s.rows,g=h.reduce((k,E)=>Math.max(k,E.length),f.length),b=Array.from({length:g},(k,E)=>f[E]??""),y=h.length>ur,S=y?h.slice(0,ur):h,w=[];return y&&w.push(`showing first ${ur} of ${h.length} rows`),s.errors.length&&w.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),o.createElement("div",{className:"ps-csv-wrap",ref:r,tabIndex:0,onMouseDown:d,onMouseMove:u,onKeyDown:p,onCopy:m},o.createElement("table",{className:"ps-csv-table",ref:i},o.createElement("thead",null,o.createElement("tr",null,b.map((k,E)=>o.createElement("th",{key:`h${E}`},String(k??""))))),o.createElement("tbody",null,S.map((k,E)=>o.createElement("tr",{key:`r${E}`},b.map((x,v)=>o.createElement("td",{key:`c${v}`},String(k[v]??""))))))),w.length?o.createElement("div",{className:"ps-csv-status"},w.join(" · ")):null)}function Oi(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&Jy[e[1].toLowerCase()]||null}function Fi(t,e){return Xy.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function Zc(t){const e=String(t??"");if(e.startsWith(Ws))return e.slice(Ws.length);const s=Ws.trimStart();return e.startsWith(s)?e.slice(s.length):e}function En(t){const e=/^artifact:\/\/([^/]+)\/(.+)$/i.exec(String(t||"").trim());if(!e)return null;try{return{sessionId:e[1],filename:decodeURIComponent(e[2])}}catch{return{sessionId:e[1],filename:e[2]}}}const Jc=o.createContext(null);function ed(t){const e=String(t||""),s=(/\.([A-Za-z0-9]+)$/.exec(e)?.[1]||"").toLowerCase();return Xc(e)?{kind:"page",type:"HTML",noun:"Page"}:Fi(e)?{kind:"diff",type:s.toUpperCase()||"DIFF",noun:"Diff"}:Li.test(e)?{kind:"image",type:s.toUpperCase(),noun:"Image"}:Qc(e)?{kind:"table",type:s.toUpperCase(),noun:"Table"}:/\.md$/i.test(e)?{kind:"doc",type:"MD",noun:"Document"}:Oi(e)?{kind:"code",type:s.toUpperCase(),noun:"Code"}:{kind:"file",type:s.toUpperCase()||"FILE",noun:"File"}}function td(t){const e=String(t||"").replace(/\.[A-Za-z0-9]+$/,""),n=(e.replace(/[-_ ]?\d{6,8}$/,"")||e).replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):String(t||"Artifact")}function ib({kind:t}){const e={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},s=t==="page"?[o.createElement("rect",{key:"w",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),o.createElement("path",{key:"b",d:"M2.5 7.5h15",...e}),o.createElement("circle",{key:"d",cx:5.2,cy:5.5,r:.7,fill:"currentColor",stroke:"none"})]:t==="image"?[o.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),o.createElement("path",{key:"m",d:"M2.5 13l4-4 4 3.5 3-2.5 3.5 3",...e})]:t==="table"?[o.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),o.createElement("path",{key:"g",d:"M2.5 8h15M8 8v8.5M2.5 12.5h15",...e})]:[o.createElement("path",{key:"p",d:"M5 2.5h6.5L16 7v10.5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-14a1 1 0 0 1 1-1z",...e}),o.createElement("path",{key:"c",d:"M11.5 2.5V7H16",...e}),t==="diff"?o.createElement("path",{key:"t",d:"M7 11h6M10 8.5v5",...e}):o.createElement("path",{key:"t",d:"M7 10.5h6M7 13.5h4",...e})];return o.createElement("svg",{className:"ps-artifact-card-glyph",viewBox:"0 0 20 20","aria-hidden":"true"},s)}function sd({artifactRef:t}){const e=o.useContext(Jc),s=ed(t.filename),n=o.useCallback(r=>{r.preventDefault(),r.stopPropagation(),ob(e,t.sessionId,t.filename)},[e,t.sessionId,t.filename]);return o.createElement("button",{type:"button",className:`ps-artifact-card is-${s.kind}`,onClick:n,title:`Open ${t.filename}`},o.createElement("span",{className:"ps-artifact-card-thumb","aria-hidden":"true"},o.createElement(ib,{kind:s.kind})),o.createElement("span",{className:"ps-artifact-card-text"},o.createElement("span",{className:"ps-artifact-card-title"},td(t.filename)),o.createElement("span",{className:"ps-artifact-card-meta"},`${s.noun} · ${s.type}`)),o.createElement("span",{className:"ps-artifact-card-open"},"Open"))}function ob(t,e,s){if(!t?.revealArtifact)return;const n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n?t.revealArtifact(e,s,{fullscreen:!0}):t.revealArtifact(e,s,{pane:!0})).catch(()=>{})}function nd(t){return Yy.has(String(t||"").trim().toLowerCase())}const ab=/^(?:diff --git |index |--- |\+\+\+ |new file mode|deleted file mode|old mode|new mode|similarity index|dissimilarity index|rename (?:from|to) |copy (?:from|to) |Binary files |GIT binary patch|\\)/;function lb(t){return ab.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const cb={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Di(t,e){return String(t||"").replace(/\n$/,"").split(`
|
|
90
|
-
`).map((n,r)=>{const i=lb(n),a=cb[i],l=i==="add"||i==="del"||i==="context"&&n.startsWith(" "),c=l?n.slice(0,1):"",d=l?n.slice(1):n;return o.createElement("span",{key:`d:${r}`,className:`ps-diff-line is-${i}`,style:a?{color:Ve(e,a)||void 0}:void 0},o.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},c.trim()),o.createElement("span",{className:"ps-diff-text"},d))})}function rd(t){return String(t||"").trim().toLowerCase()==="mermaid"}const Aa={js:new Set(["async","await","break","case","catch","class","const","continue","default","delete","do","else","export","extends","finally","for","from","function","if","import","in","instanceof","let","new","of","return","static","super","switch","this","throw","try","typeof","var","void","while","yield","true","false","null","undefined","interface","type","enum","implements","readonly","public","private","protected"]),python:new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","False","try","while","with","yield","self"]),shell:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","export","local","set","echo","cd","sudo","source"]),sql:new Set(["select","from","where","insert","into","values","update","set","delete","create","table","alter","drop","index","join","left","right","inner","outer","on","group","order","by","having","limit","offset","and","or","not","null","as","distinct","union","all","case","when","then","else","end","with","returning","primary","key","foreign","references","default","constraint","begin","commit","rollback"]),rust:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while"]),go:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","nil","true","false"]),json:new Set(["true","false","null"]),yaml:new Set(["true","false","null","yes","no"]),css:new Set(["important","media","keyframes","import","supports"])};function db(t){const e={type:"comment",re:/#[^\n]*/y},s={type:"comment",re:/\/\/[^\n]*|\/\*[\s\S]*?\*\//y},n={type:"comment",re:/--[^\n]*|\/\*[\s\S]*?\*\//y},r={type:"number",re:/\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][0-9a-fA-F]+\b/y},i={type:"identifier",re:/[A-Za-z_$][\w$]*/y},a={type:"string",re:/"(?:\\.|[^"\\])*"?/y},l={type:"string",re:/'(?:\\.|[^'\\])*'?/y},c={type:"string",re:/`(?:\\.|[^`\\])*`?/y},d={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,d,a,l,r,i];case"shell":return[e,a,l,r,i];case"sql":return[n,l,a,r,i];case"yaml":return[e,a,l,r,i];case"json":return[a,r,i];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},a,l,r,i];default:return[s,a,l,c,r,i]}}const ub={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},pb=2e4,Pt=new Map,mb=120;function fb(t,e){const s=`${e||""}\0${t}`,n=Pt.get(s);if(n)return Pt.delete(s),Pt.set(s,n),n;const r=hb(t,e);return Pt.set(s,r),Pt.size>mb&&Pt.delete(Pt.keys().next().value),r}function hb(t,e){const s=Vy[String(e||"").trim().toLowerCase()]||"default",n=Aa[s]||Aa.js,r=db(s),i=[];let a=0,l=0;const c=d=>{d>l&&i.push({type:"plain",text:t.slice(l,d)})};for(;a<t.length;){let d=null;for(const p of r){p.re.lastIndex=a;const m=p.re.exec(t);if(m&&m.index===a&&m[0].length>0){d={type:p.type,text:m[0]};break}}if(!d){a+=1;continue}let u=d.type;if(u==="identifier")if(n.has(d.text))u="keyword";else{const p=t.slice(a+d.text.length);u=/^\s*\(/.test(p)?"fn":"plain"}if(u==="plain"){a+=d.text.length;continue}c(a),i.push({type:u,text:d.text}),a+=d.text.length,l=a}return c(t.length),i}function us(t,e,s){const n=String(t||"");if(!n||n.length>pb)return n;let r;try{r=fb(n,e)}catch{return n}return r.map((i,a)=>{const l=ub[i.type];return l?o.createElement("span",{key:`t:${a}`,className:`ps-code-token is-${i.type}`,style:{color:Ve(s,l)||void 0}},i.text):o.createElement(o.Fragment,{key:`t:${a}`},i.text)})}let Gs=null;function gb(){return Gs||(Gs=Dc(()=>import("./mermaid.core-
|
|
90
|
+
`).map((n,r)=>{const i=lb(n),a=cb[i],l=i==="add"||i==="del"||i==="context"&&n.startsWith(" "),c=l?n.slice(0,1):"",d=l?n.slice(1):n;return o.createElement("span",{key:`d:${r}`,className:`ps-diff-line is-${i}`,style:a?{color:Ve(e,a)||void 0}:void 0},o.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},c.trim()),o.createElement("span",{className:"ps-diff-text"},d))})}function rd(t){return String(t||"").trim().toLowerCase()==="mermaid"}const Aa={js:new Set(["async","await","break","case","catch","class","const","continue","default","delete","do","else","export","extends","finally","for","from","function","if","import","in","instanceof","let","new","of","return","static","super","switch","this","throw","try","typeof","var","void","while","yield","true","false","null","undefined","interface","type","enum","implements","readonly","public","private","protected"]),python:new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","False","try","while","with","yield","self"]),shell:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","export","local","set","echo","cd","sudo","source"]),sql:new Set(["select","from","where","insert","into","values","update","set","delete","create","table","alter","drop","index","join","left","right","inner","outer","on","group","order","by","having","limit","offset","and","or","not","null","as","distinct","union","all","case","when","then","else","end","with","returning","primary","key","foreign","references","default","constraint","begin","commit","rollback"]),rust:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while"]),go:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","nil","true","false"]),json:new Set(["true","false","null"]),yaml:new Set(["true","false","null","yes","no"]),css:new Set(["important","media","keyframes","import","supports"])};function db(t){const e={type:"comment",re:/#[^\n]*/y},s={type:"comment",re:/\/\/[^\n]*|\/\*[\s\S]*?\*\//y},n={type:"comment",re:/--[^\n]*|\/\*[\s\S]*?\*\//y},r={type:"number",re:/\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][0-9a-fA-F]+\b/y},i={type:"identifier",re:/[A-Za-z_$][\w$]*/y},a={type:"string",re:/"(?:\\.|[^"\\])*"?/y},l={type:"string",re:/'(?:\\.|[^'\\])*'?/y},c={type:"string",re:/`(?:\\.|[^`\\])*`?/y},d={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,d,a,l,r,i];case"shell":return[e,a,l,r,i];case"sql":return[n,l,a,r,i];case"yaml":return[e,a,l,r,i];case"json":return[a,r,i];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},a,l,r,i];default:return[s,a,l,c,r,i]}}const ub={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},pb=2e4,Pt=new Map,mb=120;function fb(t,e){const s=`${e||""}\0${t}`,n=Pt.get(s);if(n)return Pt.delete(s),Pt.set(s,n),n;const r=hb(t,e);return Pt.set(s,r),Pt.size>mb&&Pt.delete(Pt.keys().next().value),r}function hb(t,e){const s=Vy[String(e||"").trim().toLowerCase()]||"default",n=Aa[s]||Aa.js,r=db(s),i=[];let a=0,l=0;const c=d=>{d>l&&i.push({type:"plain",text:t.slice(l,d)})};for(;a<t.length;){let d=null;for(const p of r){p.re.lastIndex=a;const m=p.re.exec(t);if(m&&m.index===a&&m[0].length>0){d={type:p.type,text:m[0]};break}}if(!d){a+=1;continue}let u=d.type;if(u==="identifier")if(n.has(d.text))u="keyword";else{const p=t.slice(a+d.text.length);u=/^\s*\(/.test(p)?"fn":"plain"}if(u==="plain"){a+=d.text.length;continue}c(a),i.push({type:u,text:d.text}),a+=d.text.length,l=a}return c(t.length),i}function us(t,e,s){const n=String(t||"");if(!n||n.length>pb)return n;let r;try{r=fb(n,e)}catch{return n}return r.map((i,a)=>{const l=ub[i.type];return l?o.createElement("span",{key:`t:${a}`,className:`ps-code-token is-${i.type}`,style:{color:Ve(s,l)||void 0}},i.text):o.createElement(o.Fragment,{key:`t:${a}`},i.text)})}let Gs=null;function gb(){return Gs||(Gs=Dc(()=>import("./mermaid.core-Pc4CQtPH.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw Gs=null,t})),Gs}function yb(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let Na=0,Ca=Promise.resolve();function bb(t){const e=Ca.then(t,t);return Ca=e.then(()=>{},()=>{}),e}function id({code:t,theme:e,fallback:s}){const[n,r]=o.useState(null),[i,a]=o.useState(!1),[l,c]=o.useState(""),d=o.useMemo(()=>Ju(e),[e]);return o.useEffect(()=>{let u=!0;const p=String(t||"").trim();if(p)return a(!1),gb().then(m=>bb(async()=>{if(!u)return;yb(m,d),Na+=1;const f=`ps-mermaid-${Na}`;await m.parse(p);const{svg:h}=await m.render(f,p);u&&r(h)})).catch(m=>{u&&(r(null),a(!0),c(String(m?.message||m)))}),()=>{u=!1}},[t,d]),n&&!i?o.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):i&&l?o.createElement("div",{className:"ps-mermaid-failed"},o.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(l).split(`
|
|
91
91
|
`)[0]}`),s):s}function mt(t,e,s="md"){const n=Kr(t);return n.map((r,i)=>{const a=`${s}:${i}`;if(i>0&&n[i-1]?.type==="link"&&En(n[i-1]?.href)){const l=Zc(r.text||"");if(!l)return null;l!==r.text&&(r={...r,text:l})}if(r.type==="code")return o.createElement("code",{key:a,className:"ps-md-inline-code"},r.text);if(r.type==="strong")return o.createElement("strong",{key:a,className:"ps-md-strong"},mt(r.text,e,`${a}:strong`));if(r.type==="em")return o.createElement("em",{key:a,className:"ps-md-em"},mt(r.text,e,`${a}:em`));if(r.type==="link"){const l=En(r.href);return l?o.createElement(sd,{key:a,artifactRef:l}):/^https?:\/\//i.test(String(r.href||"").trim())?o.createElement("a",{key:a,className:"ps-md-link",href:r.href,target:"_blank",rel:"noreferrer",style:{color:Ve(e,"cyan")}},r.text):o.createElement("span",{key:a,style:{color:Ve(e,"cyan")}},r.text)}return o.createElement(o.Fragment,{key:a},r.text)})}function od(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(i=>Fr(i?.[n]||"")).filter(Boolean).join(" / ")||null)}function Ta(t="",e=""){const s=String(t||"");return/^\s*#{1,6}\s+/.test(s)||/^\s*>/.test(s)||/^\s*([-*]|\d+\.)\s+/.test(s)||/^\s*```/.test(s)||s.includes("|")&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(String(e||""))}function Pa(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Sb(t=""){const s=String(t||"").replace(/\r\n?/g,`
|
|
92
92
|
`).split(`
|
|
93
93
|
`),n=[];for(let r=0;r<s.length;){const i=s[r],a=i.trim();if(!a){r+=1;continue}const l=/^```(\S*)\s*$/.exec(a);if(l){const p=l[1]||"",m=[];for(r+=1;r<s.length&&!/^```/.test(s[r].trim());)m.push(s[r]),r+=1;r<s.length&&(r+=1),n.push({type:"code",language:p,content:m.join(`
|
|
94
94
|
`)});continue}const c=/^(#{1,6})\s+(.*)$/.exec(i);if(c){n.push({type:"heading",level:c[1].length,text:c[2].trim()}),r+=1;continue}if(i.includes("|")&&r+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[r+1].trim())){const p=Pa(i);r+=2;const m=[];for(;r<s.length&&s[r].includes("|")&&s[r].trim();)m.push(Pa(s[r])),r+=1;n.push({type:"table",header:p,rows:m});continue}if(/^\s*>/.test(i)){const p=[];for(;r<s.length&&/^\s*>/.test(s[r]);)p.push(s[r].replace(/^\s*>\s?/,"")),r+=1;n.push({type:"blockquote",text:p.join(`
|
|
95
95
|
`).trim()});continue}const d=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(i);if(d){const p=/\d+\./.test(d[2]),m=[];for(;r<s.length;){const f=s[r],h=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(f);if(!h||/\d+\./.test(h[2])!==p)break;const g=[h[3].trim()];for(r+=1;r<s.length&&s[r].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[r])&&!Ta(s[r],s[r+1]||"");)g.push(s[r].trim()),r+=1;if(m.push(g.join(" ")),!s[r]?.trim())break}n.push({type:"list",ordered:p,items:m});continue}const u=[i.trim()];for(r+=1;r<s.length&&s[r].trim()&&!Ta(s[r],s[r+1]||"");)u.push(s[r].trim()),r+=1;n.push({type:"paragraph",text:u.join(" ")})}return n}function Bi({content:t,theme:e}){const s=o.useMemo(()=>Sb(t),[t]);return s.length===0?o.createElement("div",{className:"ps-empty-state"},"No preview content."):o.createElement("div",{className:"ps-markdown-preview"},s.map((n,r)=>{if(n.type==="heading")return o.createElement("div",{key:`block:${r}`,className:`ps-md-heading is-h${n.level}`},mt(n.text,e,`heading:${r}`));if(n.type==="code"){const i=nd(n.language),a=o.createElement("section",{key:`block:${r}`,className:`ps-md-code-block${i?" is-diff":""}`},o.createElement("div",{className:"ps-md-code-header"},n.language||"text"),o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,i?Di(n.content,e):us(n.content,n.language,e))));return rd(n.language)?o.createElement(id,{key:`block:${r}`,code:n.content,theme:e,fallback:a}):a}if(n.type==="blockquote")return o.createElement("blockquote",{key:`block:${r}`,className:"ps-md-quote"},mt(n.text,e,`quote:${r}`));if(n.type==="list"){const i=n.ordered?"ol":"ul";return o.createElement(i,{key:`block:${r}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((a,l)=>o.createElement("li",{key:`item:${l}`,className:"ps-md-list-item"},mt(a,e,`list:${r}:${l}`))))}if(n.type==="table"){const i=Math.max(n.header.length||0,...n.rows.map(h=>h.length)),a=i>0&&i<=6,l=a?Fc([n.header,...n.rows]):null,c=!!l,d=l?l.flexIndex:-1,u=h=>h===d?"is-flex-column":null,p=od([n.header],i),m=`ps-md-table${a?" is-fit-width":""}${c?" has-flex-column":""}`,f=`ps-md-table-wrap${a?" is-fit-width":""}${c?" has-flex-column":""}`;return o.createElement("div",{key:`block:${r}`,className:f},o.createElement("table",{className:m,style:l?.minWidth?{"--ps-table-min-width":l.minWidth}:void 0},l?o.createElement("colgroup",null,l.widths.map((h,g)=>o.createElement("col",{key:`col:${g}`,className:u(g)||void 0,style:{width:h}}))):null,o.createElement("thead",null,o.createElement("tr",null,n.header.map((h,g)=>o.createElement("th",{key:`head:${g}`,className:u(g)||void 0},mt(h,e,`table:${r}:head:${g}`))))),o.createElement("tbody",null,n.rows.map((h,g)=>o.createElement("tr",{key:`row:${g}`},h.map((b,y)=>o.createElement("td",{key:`cell:${g}:${y}`,className:u(y)||void 0,"data-label":p[y]||void 0},o.createElement("span",{className:"ps-table-cell-value"},mt(b,e,`table:${r}:${g}:${y}`)))))))))}return o.createElement("p",{key:`block:${r}`,className:"ps-md-paragraph"},mt(n.text,e,`para:${r}`))}))}function pr({controller:t,title:e,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:a,className:l="",focusRegion:c=null,children:d}){const u=o.useRef(null),p=Yc(u,r,i,t),m=o.useCallback(()=>{const f=Hi(i,c);f&&t?.setFocus&&t.setFocus(f)},[t,i,c]);return o.createElement(At,{title:e,color:s,focused:n,theme:a},o.createElement("div",{ref:u,className:`ps-scroll-panel is-preview ${l}`.trim(),onScroll:p,onMouseDown:m},d))}function vb({controller:t,title:e,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:a,content:l,focusRegion:c=null}){const d=o.useCallback(()=>{const m=Hi(i,c);m&&t?.setFocus&&t.setFocus(m)},[t,i,c]),u=o.useRef(null),p=Yc(u,r,i,t);return o.createElement(At,{title:e,color:s,focused:n,theme:a},o.createElement("div",{ref:u,className:"ps-scroll-panel ps-markdown-scroll",onScroll:p,onMouseDown:d},o.createElement(Bi,{content:l,theme:a})))}function ad(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"Unknown size";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Ma({title:t,color:e,focused:s,theme:n,filename:r,contentType:i,sizeBytes:a,source:l,uploadedAt:c,controller:d=null,sessionId:u=null}){const p=[];i&&p.push(i),a!=null&&p.push(ad(a)),l&&p.push(l);const m=c?new Date(c).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",f=$i.test(String(i||""))||Li.test(String(r||"")),[h,g]=o.useState(null);return o.useEffect(()=>{if(g(null),!f||!d||!u||!r)return;let b=!1;return md(d,u,r).then(y=>{b||g(y)}).catch(()=>{b||g("error")}),()=>{b=!0}},[f,d,u,r]),o.createElement(At,{title:t,color:e,focused:s,theme:n},o.createElement("div",{className:"ps-binary-preview-card"},o.createElement("div",{className:"ps-binary-preview-kicker"},f?"Image artifact":"Binary artifact"),o.createElement("h3",{className:"ps-binary-preview-title"},r||"Artifact"),p.length>0?o.createElement("div",{className:"ps-binary-preview-meta"},p.join(" • ")):null,m?o.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${m}`):null,f&&h&&h!=="error"?o.createElement("img",{className:"ps-binary-preview-image",src:h,alt:r||"artifact image",onClick:()=>{const b=Tn(u,r);if(b)try{window.open(b,"_blank","noopener")}catch{}}}):o.createElement("p",{className:"ps-binary-preview-copy"},f?h==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}const wb=260,Eb=28;function kb(t,e,s,n){const[r,i]=o.useState(null),[a,l]=o.useState(0),c=o.useRef(null),d=o.useRef(0);o.useEffect(()=>{c.current=null,d.current+=1,i(null),l(d.current)},[s]);const u=o.useRef(!0);o.useEffect(()=>{if(u.current){u.current=!1;return}e&&(c.current=null,d.current+=1,l(d.current))},[n,e]),o.useEffect(()=>{const m=t.current;if(!e||!m||typeof ResizeObserver>"u")return;let f=null;const h=new ResizeObserver(g=>{const b=Math.round(g[0]?.contentRect?.width||0);if(b){if(c.current===null){c.current=b;return}Math.abs(b-c.current)<Eb||(f&&clearTimeout(f),f=setTimeout(()=>{f=null,c.current=Math.round(m.getBoundingClientRect().width)||b,d.current+=1,l(d.current)},wb))}});return h.observe(m),()=>{f&&clearTimeout(f),h.disconnect()}},[t,e]);const p=o.useCallback(m=>{const f=()=>{l(h=>h===m?null:h),i(h=>h===m?h:m)};if(typeof requestAnimationFrame!="function"){f();return}requestAnimationFrame(()=>requestAnimationFrame(f))},[]);return{live:r,pending:a,promote:p}}const mr=1024;function ld({fitWidth:t,setFitWidth:e}){return o.createElement(he,{icon:t?"1:1":"⤢",label:t?"Actual size":"Fit page to width",active:t,onClick:()=>e(!t)})}const Mt=[.5,.67,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3];function kn({zoom:t,setZoom:e}){const s=n=>{const r=Mt.findIndex(l=>Math.abs(l-t)<.005),i=r===-1?Mt.indexOf(1):r,a=Mt[Math.min(Mt.length-1,Math.max(0,i+n))];e(a)};return o.createElement("span",{className:"ps-html-zoom",role:"group","aria-label":"Artifact zoom"},o.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(-1),disabled:t<=Mt[0]+.001,title:"Zoom out (artifact only)","aria-label":"Zoom out"},"−"),o.createElement("button",{type:"button",className:"ps-html-zoom-level",onClick:()=>e(1),title:"Reset zoom to 100%","aria-label":`Zoom ${Math.round(t*100)} percent, click to reset`},`${Math.round(t*100)}%`),o.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(1),disabled:t>=Mt[Mt.length-1]-.001,title:"Zoom in (artifact only)","aria-label":"Zoom in"},"+"))}function cd({mode:t,setMode:e}){return o.createElement("span",{className:"ps-html-preview-modes",role:"group","aria-label":"Preview mode"},["rendered","source"].map(s=>o.createElement("button",{key:s,type:"button",className:`ps-html-preview-mode${t===s?" is-active":""}`,"aria-pressed":t===s,onClick:()=>e(s)},s==="rendered"?"Rendered":"Source")))}function dd(t){const[e,s]=o.useState({width:0,height:0});return o.useLayoutEffect(()=>{const n=t.current;if(!n||typeof ResizeObserver>"u")return;const r=()=>{const a=n.getBoundingClientRect();s(l=>{const c=Math.round(a.width)||0,d=Math.round(a.height)||0;return l.width===c&&l.height===d?l:{width:c,height:d}})};r();const i=new ResizeObserver(r);return i.observe(n),()=>i.disconnect()},[t]),e}function ud(t,e,s){const n=t?.transport?.api?.downloadArtifactResponse;return typeof n!="function"?Promise.reject(new Error("artifact download unavailable")):n.call(t.transport.api,e,s).then(async r=>{if(!r?.ok)throw new Error(`download failed (${r?.status})`);const i=await r.arrayBuffer();return URL.createObjectURL(new Blob([i],{type:"text/html;charset=utf-8"}))})}function xb({controller:t,sessionId:e,filename:s,contentType:n,sizeBytes:r,theme:i,color:a="cyan",focused:l=!1,title:c=null,chromeless:d=!1}){const u=ee(t,C=>C.files.htmlViewMode||"rendered"),p=o.useCallback(C=>{t.dispatch({type:"files/htmlViewMode",mode:C})},[t]),[m,f]=o.useState(null),[h,g]=o.useState(null),b=o.useRef(null),y=ee(t,C=>!!C.files.htmlFitWidth),S=o.useCallback(C=>{t.dispatch({type:"files/htmlFitWidth",enabled:C})},[t]),w=dd(b),k=y&&w.width>0&&w.width<mr?w.width/mr:1,E=k<1,x=ee(t,C=>Number(C.files.htmlZoom)||1),v=o.useCallback(C=>{t.dispatch({type:"files/htmlZoom",zoom:C})},[t]),P=E?k*x:x,N=kb(b,u==="rendered"&&!E,`${e}/${s}`,x);o.useEffect(()=>{if(f(null),g(null),u!=="rendered"||!t||!e||!s)return;let C=!1,U=null;return ud(t,e,s).then(B=>{if(U=B,C){URL.revokeObjectURL(B);return}f(B)}).catch(B=>{C||g(B?.message||String(B))}),()=>{C=!0,U&&URL.revokeObjectURL(U)}},[t,e,s,u]);const _=Tn(e,s),D=d?null:o.createElement(o.Fragment,null,o.createElement(cd,{mode:u,setMode:p}),u==="rendered"?o.createElement(ld,{fitWidth:y,setFitWidth:S}):null,u==="rendered"?o.createElement(kn,{zoom:x,setZoom:v}):null,_?o.createElement(he,{icon:"↗",label:"Open in a new tab",onClick:()=>{try{window.open(_,"_blank","noopener")}catch{}}}):null),L=u==="source"?o.createElement(Ib,{controller:t,sessionId:e,filename:s,theme:i}):h?o.createElement("div",{className:"ps-html-preview-status"},o.createElement("p",null,`Could not load ${s}: ${h}`),o.createElement("p",null,"Use Download to save the file and open it locally.")):m?[N.live,N.pending].filter((C,U,B)=>C!==null&&B.indexOf(C)===U).map(C=>o.createElement("iframe",{key:`frame:${C}`,className:`ps-html-preview-frame${C===N.live?"":" is-staging"}`,style:E?{flex:"none",width:`${mr}px`,height:`${Math.max(1,Math.round(w.height/P))}px`,transform:`scale(${P})`,transformOrigin:"top left"}:x!==1&&w.width>0?{flex:"none",width:`${Math.max(1,Math.round(w.width/x))}px`,height:`${Math.max(1,Math.round(w.height/x))}px`,transform:`scale(${x})`,transformOrigin:"top left"}:void 0,src:m,title:s||"HTML artifact",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:()=>N.promote(C)})):o.createElement("div",{className:"ps-html-preview-status"},o.createElement("p",null,`Rendering ${s}…`),r!=null?o.createElement("p",{className:"ps-html-preview-meta"},[n,ad(r)].filter(Boolean).join(" • ")):null),I=u==="rendered"?o.createElement("div",{ref:b,className:`ps-html-preview-host${E||x!==1?" is-fitting":""}`},L):L;return o.createElement(At,{title:c,color:a,focused:l,theme:i,actions:D,className:"ps-html-preview"},I)}function Ib({controller:t,sessionId:e,filename:s,theme:n}){const[r,i]=o.useState(null),[a,l]=o.useState(null);return o.useEffect(()=>{i(null),l(null);const c=t?.transport?.api?.downloadArtifactResponse;if(typeof c!="function"||!e||!s){l("artifact download unavailable");return}let d=!1;return c.call(t.transport.api,e,s).then(async u=>{if(!u?.ok)throw new Error(`download failed (${u?.status})`);return u.text()}).then(u=>{d||i(u)}).catch(u=>{d||l(u?.message||String(u))}),()=>{d=!0}},[t,e,s]),a?o.createElement("div",{className:"ps-html-preview-status"},o.createElement("p",null,`Could not load source: ${a}`)):r==null?o.createElement("div",{className:"ps-html-preview-status"},o.createElement("p",null,"Loading source…")):o.createElement("div",{className:"ps-scroll-panel is-preview ps-diff-preview"},o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,us(r,"html",n))))}function Zs(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function fr(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Ab(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Ps(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Nb(t){const e=String(Xe(t)||"").trim();return Zs(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Cb(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Xe(t);return Ps(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Tb(t=[]){const e=(t||[]).map(s=>({...s}));return e.length===0?e:(e[0].text=String(e[0].text||"").replace(/^\s+/,""),e[e.length-1].text=String(e[e.length-1].text||"").replace(/\s+$/,""),e.filter((s,n)=>String(s.text||"").length>0||e.length===1||n===0))}function _a(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Tb(t.runs.slice(1,-1)):[{text:Xe(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Pb(t){const e=String(t||"").trim();return Ps(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function Mb(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const r=s.slice(-1),i=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(i)||/^[._/\\-]/u.test(i)||/[([{<._/\\-]$/u.test(r)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(i))}function _b(t=[]){const e=(Array.isArray(t)?t:[t]).map(s=>String(s||"").trim()).filter(Boolean);return e.length===0?"":e.slice(1).reduce((s,n)=>Mb(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function Ra(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>_b(t.map(r=>String(r[n]||"").trim()).filter(Boolean)))}function pd(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const i=n.splashVariant||null,a=[];for(;s<t.length&&t[s]?.preserve&&(t[s].splashVariant||null)===i;)a.push(t[s]),s+=1;e.push({type:"preserve",lines:a,splashVariant:i});continue}if(n?.kind==="cardStart"){const i=[];for(s+=1;s<t.length&&t[s]?.kind!=="cardEnd";)i.push(t[s]),s+=1;s<t.length&&(s+=1),s<t.length&&Xe(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:pd(i)});continue}if(n?.kind==="imageAttachments"){e.push({type:"imageAttachments",sessionId:n.sessionId||null,attachments:Array.isArray(n.attachments)?n.attachments:[]}),s+=1;continue}if(n?.kind==="markdownTable"){e.push({type:"table",headerRows:Array.isArray(n.header)&&n.header.length>0?[n.header]:[],bodyRows:Array.isArray(n.rows)?n.rows:[]}),s+=1;continue}const r=Xe(n);if(Zs(r)&&r.includes("┬")){const i=[],a=[];let l=[],c=!0;for(s+=1;s<t.length;){const d=t[s],u=Xe(d);if(fr(u)){if(l.length>0){const p=Ra(l);p.length>0&&(c?i.push(p):a.push(p))}s+=1;break}if(Ab(u)){if(l.length>0){const p=Ra(l);p.length>0&&(c?i.push(p):a.push(p))}l=[],c=!1,s+=1;continue}if(Ps(u)){const p=Pb(u);p.length>0&&l.push(p)}s+=1}e.push({type:"table",headerRows:i,bodyRows:a});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Zs(r)){const i=Nb(n),a=[];for(s+=1;s<t.length;){const l=t[s],c=Xe(l);if(fr(c)){s+=1;break}Ps(c)?a.push(Cb(l)):a.push(Xe(l)),s+=1}s<t.length&&Xe(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:i||"text",content:a.join(`
|
|
96
|
-
`)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Zs(r)){const i=_a(n),a=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],d=Xe(c);if(fr(d)){s+=1;break}Ps(d)?l.push(_a(c)):l.push(c?.kind==="runs"?c.runs:[{text:Xe(c),color:c?.color||null}]),s+=1}s<t.length&&Xe(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:i,bodyLines:l,borderColor:a});continue}e.push({type:"line",line:n}),s+=1}return e}function Rb({lines:t,theme:e,controller:s=null}){const n=o.useMemo(()=>pd((t||[]).filter(r=>!r?.canvasUpdate)),[t]);return o.createElement(fd,{blocks:n,theme:e,controller:s})}const ht=new Map,$b=60;function md(t,e,s){const n=`${e}/${s}`,r=ht.get(n);if(r)return ht.delete(n),ht.set(n,r),r;const i=t?.transport?.api?.downloadArtifactResponse;if(typeof i!="function")return Promise.reject(new Error("artifact download unavailable"));const a=i.call(t.transport.api,e,s).then(async l=>{if(!l?.ok)throw new Error(`download failed (${l?.status})`);const c=await l.blob(),d=Zy(s),u=d&&!$i.test(c.type)?new Blob([c],{type:d}):c;return URL.createObjectURL(u)}).catch(l=>{throw ht.get(n)===a&&ht.delete(n),l});for(ht.set(n,a);ht.size>$b;){const[l,c]=ht.entries().next().value;ht.delete(l),Promise.resolve(c).then(d=>URL.revokeObjectURL(d)).catch(()=>{})}return a}function Lb({controller:t,sessionId:e,attachments:s}){const[n,r]=o.useState({});return o.useEffect(()=>{if(!t||!e)return;let i=!1;for(const a of s){const l=a?.filename;l&&md(t,e,l).then(c=>{i||r(d=>d[l]===c?d:{...d,[l]:c})}).catch(()=>{i||r(c=>c[l]==="error"?c:{...c,[l]:"error"})})}return()=>{i=!0}},[t,e,s]),o.createElement("div",{className:"ps-chat-image-strip"},s.map((i,a)=>{const l=i?.filename||`image-${a}`,c=n[l];return c&&c!=="error"?o.createElement("img",{key:`thumb:${a}:${l}`,className:"ps-chat-image-thumb",src:c,alt:l,title:`${l} — click to view full size`,onClick:()=>{try{window.open(c,"_blank","noopener")}catch{}}}):o.createElement("div",{key:`thumb:${a}:${l}`,className:`ps-chat-image-thumb is-pending${c==="error"?" is-error":""}`,title:l},c==="error"?"⚠":"🖼")}))}function fd({blocks:t,theme:e,controller:s=null}){return o.createElement(o.Fragment,null,(t||[]).map((n,r)=>{if(n.type==="imageAttachments")return o.createElement(Lb,{key:`imageAttachments:${r}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const i=n.splashVariant?` is-splash-${n.splashVariant}`:"";return o.createElement("div",{key:`preserve:${r}`,className:`ps-chat-preserve-block${i}`},n.lines.map((a,l)=>o.createElement(We,{key:`preserve:${r}:${l}`,line:a,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const i=nd(n.language),a=o.createElement("section",{key:`code:${r}`,className:`ps-md-code-block ps-chat-code-block${i?" is-diff":""}`},o.createElement("div",{className:"ps-md-code-header"},n.language||"text"),o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,i?Di(n.content||"",e):us(n.content||"",n.language,e))));return rd(n.language)?o.createElement(id,{key:`code:${r}`,code:n.content||"",theme:e,fallback:a}):a}if(n.type==="card")return o.createElement("section",{key:`card:${r}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":Ve(e,n.borderColor)||"var(--ps-border)"}},o.createElement("header",{className:"ps-chat-card-header"},o.createElement(ze,{runs:n.headerRuns,theme:e})),o.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?o.createElement(fd,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((i,a)=>o.createElement("div",{key:`card:${r}:line:${a}`,className:"ps-chat-card-line"},o.createElement(ze,{runs:i,theme:e})))));if(n.type==="table"){const i=n.headerRows||[],a=n.bodyRows||[],l=Math.max(1,...i.map(b=>b.length),...a.map(b=>b.length)),c=l<=6,d=c?Fc([...i,...a]):null,u=!!d,p=d?d.flexIndex:-1,m=b=>b===p?"is-flex-column":null,f=od(i,l),h=`ps-chat-table${c?" is-fit-width":""}${u?" has-flex-column":""}`,g=`ps-chat-table-wrap${c?" is-fit-width":""}${u?" has-flex-column":""}`;return o.createElement("div",{key:`table:${r}`,className:g},o.createElement("table",{className:h,style:d?.minWidth?{"--ps-table-min-width":d.minWidth}:void 0},d?o.createElement("colgroup",null,d.widths.map((b,y)=>o.createElement("col",{key:`col:${y}`,className:m(y)||void 0,style:{width:b}}))):null,i.length>0?o.createElement("thead",null,i.map((b,y)=>o.createElement("tr",{key:`thead:${y}`},Array.from({length:l},(S,w)=>o.createElement("th",{key:`th:${y}:${w}`,className:m(w)||void 0},mt(b[w]||"",e,`chat-table:${r}:head:${y}:${w}`)))))):null,o.createElement("tbody",null,a.map((b,y)=>o.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(S,w)=>o.createElement("td",{key:`td:${y}:${w}`,className:m(w)||void 0,"data-label":f[w]||void 0},o.createElement("span",{className:"ps-table-cell-value"},mt(b[w]||"",e,`chat-table:${r}:${y}:${w}`)))))))))}return o.createElement(We,{key:`line:${r}`,line:n.line,theme:e})}))}function At({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:r=null,children:i,theme:a,className:l=""}){const c=Ve(a,s),d=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||r);return o.createElement("section",{className:`ps-panel${n?" is-focused":""}${d?"":" is-chromeless"}${l?` ${l}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},d?o.createElement("header",{className:"ps-panel-header"},o.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?o.createElement(ze,{runs:t,theme:a}):ka(t)),e||r?o.createElement("div",{className:"ps-panel-header-right"},e?o.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?o.createElement(ze,{runs:e,theme:a}):ka(e)):null,r?o.createElement("div",{className:"ps-panel-actions"},r):null):null):null,o.createElement("div",{className:"ps-panel-body"},i))}function Ob({lines:t,theme:e,controller:s}){return o.createElement("div",{className:"ps-nodemap"},(t||[]).map((n,r)=>{const i=Array.isArray(n?.runs)?n.runs:Array.isArray(n)?n:[n],a=i.find(d=>d?.nodeSelect)?.nodeSelect||null,l=i.some(d=>d?.nodeSelected),c=o.createElement(ze,{runs:i,theme:e});return a?o.createElement("button",{key:`line:${r}`,type:"button",className:`ps-nodemap__row${l?" is-selected":""}`,onPointerDown:d=>{d.preventDefault(),d.stopPropagation(),s.selectNodeMapNode(a)}},c):o.createElement("div",{key:`line:${r}`,className:"ps-nodemap__line"},c)}))}function Fb({lines:t,theme:e,completionByTurn:s}){const[n,r]=o.useState(()=>new Set),i=o.useCallback(u=>{r(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),m})},[]),a=u=>Number(u||0).toLocaleString("en-US"),l=u=>{const p=Number(u||0);if(!Number.isFinite(p))return"?K";const m=p/1e3,f=Math.abs(m)>=10?1:2;return`${m.toFixed(f)}K`},c=u=>{const p=Number(u||0);return Number.isFinite(p)?`${(p/1e3).toFixed(1)}s`:"?s"},d=u=>{const p=String(u||"").trim();if(!p)return"unknown";const m=p.split(":").filter(Boolean),f=m[m.length-1]||"",h=m.length>1&&yy.has(f.toLowerCase())?m.length-2:m.length-1;return m[Math.max(0,h)]||m[0]||"unknown"};return o.createElement(o.Fragment,null,t.map((u,p)=>{const m=u?.kind==="runs"&&Array.isArray(u.runs)?u.runs.find(v=>v?.completedTurn!=null)?.completedTurn:null,f=m!=null?s.get(Number(m)):null;if(!f)return o.createElement(We,{key:`line:${p}`,line:u,theme:e});const h=f.data||{},g=String(f.seq??`${h.turnIndex??m}:${f.createdAt??p}`),b=n.has(g),y=h.reasoningEffort?`${h.model||"(unknown)"}:${h.reasoningEffort}`:h.model||"(unknown)",S=d(h.model),w=h.durationMs!=null?c(h.durationMs):"duration n/a",k=h.durationMs!=null?`${a(h.durationMs)} ms`:"duration n/a",E=`${l(h.tokensInput)} / ${l(h.tokensOutput)}`,x=[["model",y],["started",h.startedAt?new Date(h.startedAt).toLocaleString():null],["ended",h.endedAt?new Date(h.endedAt).toLocaleString():null],["duration",k],["tokens",`${a(h.tokensInput)} in / ${a(h.tokensOutput)} out`],["cache",`${a(h.tokensCacheRead)} read / ${a(h.tokensCacheWrite)} write`],["tools",`${a(h.toolCalls)} calls / ${a(h.toolErrors)} errors`],["names",Array.isArray(h.toolNames)&&h.toolNames.length?h.toolNames.join(", "):null],["worker",h.workerNodeId||null],["result",h.resultType||null],["error",h.errorMessage||null]].filter(([,v])=>v!=null&&v!=="");return o.createElement(o.Fragment,{key:`seq:${p}`},o.createElement(We,{line:u,theme:e}),o.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>i(g)},o.createElement("span",{className:"ps-sequence-turn-caret"},b?"v":">"),o.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),o.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),o.createElement("span",{className:"ps-sequence-turn-model"},S),o.createElement("span",{className:"ps-sequence-turn-rule"}," ("),o.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),o.createElement("span",{className:"ps-sequence-turn-tokens"},E),o.createElement("span",{className:"ps-sequence-turn-rule"},", "),o.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),o.createElement("span",{className:"ps-sequence-turn-duration"},w),o.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),b?o.createElement("div",{className:"ps-sequence-turn-details"},x.map(([v,P])=>o.createElement("div",{key:v},o.createElement("span",{className:"ps-sequence-turn-detail-label"},`${v}: `),o.createElement("span",null,String(P))))):null)}))}const Db={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Hi(t,e=null){return e||Db[String(t||"")]||null}function _n({title:t,titleRight:e=null,color:s,focused:n,actions:r,lines:i,stickyLines:a=[],bottomStickyLines:l=[],scrollOffset:c=0,scrollMode:d="top",paneKey:u,controller:p,className:m="",panelClassName:f="",topContent:h=null,bottomContent:g=null,structuredBlocks:b=!1,stickyBottom:y=!1,renderBody:S=null,focusRegion:w=null,panelRef:k=null}){const E=ee(p,Y=>Y.ui.themeId),x=ft(E),v=o.useRef(null),P=o.useCallback(Y=>{v.current=Y,typeof k=="function"?k(Y):k&&(k.current=Y)},[k]),N=o.useRef(null),_=o.useRef(!1),{normalizedLines:D,onScroll:L,onWheel:I,onTouchStart:C,onTouchMove:U,onTouchEnd:B}=Wy(v,i,c,d,u,p,{stickyBottom:y}),V=o.useMemo(()=>je(a),[a]),ce=o.useMemo(()=>je(l),[l]),X=m.includes("is-preserve")&&f.includes("has-preserved-sticky"),re=`${u}:${t}`;o.useEffect(()=>{const Y=()=>{v.current&&(v.current.scrollLeft=0),N.current&&(N.current.scrollLeft=0)};Y();const Z=typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{Y()}):null;return()=>{Z!=null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Z)}},[re]);const T=o.useCallback(()=>{const Y=Hi(u,w);Y&&p?.setFocus&&p.setFocus(Y)},[p,u,w]),j=o.useCallback((Y,Z)=>{!Y||!Z||Math.abs((Z.scrollLeft||0)-(Y.scrollLeft||0))<=1||(_.current=!0,Z.scrollLeft=Y.scrollLeft,window.requestAnimationFrame(()=>{_.current=!1}))},[]),[H,W]=o.useState({up:!1,down:!1}),z=o.useCallback(Y=>{if(!Y)return;const Z=Y.scrollHeight-Y.scrollTop-Y.clientHeight>4,de=Y.scrollTop>4;W(ve=>ve.up===Z&&ve.down===de?ve:{up:Z,down:de})},[]),Q=o.useCallback(Y=>{L(),z(Y.currentTarget),!(!X||_.current)&&j(Y.currentTarget,N.current)},[L,X,j,z]);o.useEffect(()=>{z(v.current)});const K=o.useCallback(Y=>{!X||_.current||j(Y.currentTarget,v.current)},[X,j]);return o.createElement(At,{title:t,titleRight:e,color:s,focused:n,actions:r,theme:x,className:f},h,V.length>0?o.createElement("div",{ref:N,className:`ps-panel-sticky${X?" is-scroll-sync":""}`,onScroll:K},V.map((Y,Z)=>o.createElement(We,{key:`sticky:${Z}`,line:Y,theme:x}))):null,o.createElement("div",{ref:P,className:`ps-scroll-panel ${m}${H.down?" is-scrolled-down":""}${H.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":w==="sessions"?"1":void 0,onScroll:Q,onMouseDown:T,onTouchStart:C,onWheel:I,onTouchMove:U,onTouchEnd:B,onTouchCancel:B},typeof S=="function"?S(D,x):b?o.createElement(Rb,{lines:D,theme:x,controller:p}):D.map((Y,Z)=>o.createElement(We,{key:`line:${Z}`,line:Y,theme:x}))),ce.length>0?o.createElement("div",{className:"ps-panel-bottom-sticky"},ce.map((Y,Z)=>o.createElement(We,{key:`bottom-sticky:${Z}`,line:Y,theme:x}))):null,g)}const hr="—";function Bb(t,e){const s=typeof t?.waitReason=="string"&&t.waitReason.trim()?t.waitReason.trim():null;if(!s)return null;const n=String(e||"");return n==="waiting"||n.startsWith("waiting on")||n==="input_required"?s:null}function Hb({session:t,childCount:e=0,pause:s=null,controller:n=null,collapsed:r=!1,onToggle:i=null}){const a=(S,w,k="")=>{const E=w==null||w===""?hr:String(w),x=E===hr;return o.createElement("div",{className:`ps-session-detail-field${k?` ${k}`:""}${x?" is-none":""}`,key:S},o.createElement("span",{className:"ps-session-detail-label"},S),o.createElement("span",{className:"ps-session-detail-value",title:E},E))},l=t?.contextUsage,c=l&&Number.isFinite(l.currentTokens)&&Number.isFinite(l.tokenLimit)&&l.tokenLimit>0,d=c?Math.round(l.currentTokens/l.tokenLimit*100):null,u=c?`${J(l.currentTokens)} / ${J(l.tokenLimit)} · ${d}%`:null;let p=null;t&&!t.isGroup&&(p="off",t.cronActive===!0&&(p=t.cronKind==="wall-clock"?`next ${un(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${Vt(t.cronInterval)}`:"on"));const m=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,f=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,h=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null,g=jp(t),b=Bb(t,g?.status),y=!s&&!b?null:o.createElement("div",{className:`ps-session-detail-pause${s?" is-paused":""}`},o.createElement("span",{className:"ps-session-detail-label"},s?"Paused":"Waiting"),o.createElement("span",{className:"ps-session-detail-why"},s?s.reason:b,s&&s.clears?o.createElement("span",{className:"ps-session-detail-clears"},s.clears):null,s&&n?o.createElement("button",{type:"button",className:"ps-budget-link",title:s.provider?`Open ${s.provider} in Providers & Budgets`:"Open providers and budgets",onClick:()=>n.openBudget(s.provider?{provider:s.provider}:{}).catch(()=>{})},s.provider?`Open ${s.provider}`:"Open providers and budgets"):null));if(r){const S=[];return u&&S.push(o.createElement("span",{key:"context",className:`ps-session-detail-mark${d!=null&&d>=85?" is-hot":d!=null&&d>=70?" is-warm":""}`},d!=null?`${d}%`:u)),g&&S.push(o.createElement("span",{key:"updated",className:"ps-session-detail-mark"},`${g.relative} (${g.status})`)),(s||b)&&S.push(o.createElement("span",{key:"halt",className:`ps-session-detail-mark${s?" is-paused":""}`,title:s?s.reason:b},s?"paused":"waiting")),o.createElement("div",{className:"ps-session-detail-box is-collapsed"},o.createElement("button",{type:"button",className:"ps-session-detail-summary","aria-expanded":!1,title:"Show session details",onClick:i},o.createElement("span",{className:"ps-session-detail-twisty","aria-hidden":"true"},"▸"),o.createElement("span",{className:"ps-session-detail-summary-title"},t?.title||hr),o.createElement("span",{className:"ps-session-detail-marks"},S)),y)}return o.createElement("div",{className:"ps-session-detail-box"},o.createElement("button",{type:"button",className:"ps-session-detail-collapse","aria-expanded":!0,title:"Hide session details",onClick:i},o.createElement("span",{"aria-hidden":"true"},"▾")," Less"),a("Title",t?.title,"is-title"),a("ID",t?.sessionId,"is-id"),a("Owner",t?.owner?hv(t.owner):null),a("Model",m),a("Context",u,d!=null&&d>=85?"is-hot":d!=null&&d>=70?"is-warm":""),a("Cron",p,t?.cronActive===!0?"is-armed":""),a("Agent",t?.agentId),a("Updated",g?`${g.relative} (${g.status})`:null),a("Children",h),a("Access",f),y)}function Ub(){const t="(pointer: coarse)",e=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1,[s,n]=o.useState(e);return o.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(t),i=a=>n(a.matches);return r.addEventListener?.("change",i),()=>r.removeEventListener?.("change",i)},[]),s}const hd=13,gd=11,yd=1.5,jb=7;function Gb(t){return hd+(t-1)*gd+yd/2-jb/2}const Wb=o.memo(function({row:e,theme:s,structuredRows:n,mobile:r,onRowClick:i,setRef:a,drag:l}){const c=Math.max(0,e.depth),d=o.useMemo(()=>{if(c<1)return;const S=Array.from({length:c},(w,k)=>k);return{backgroundImage:S.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:S.map(()=>`${yd}px 100%`).join(", "),backgroundPosition:S.map(w=>`${hd+w*gd}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),u=o.useCallback(S=>a(e.sessionId,S),[a,e.sessionId]),p=o.useCallback(S=>i(S,e),[i,e]),m=e.groupId||null,f=!!(l?.dragging&&l.overGroupId&&m===l.overGroupId),h=f&&!!e.isGroup,g=!!(l?.dragging&&l.insertBeforeId===e.sessionId),b=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===e.sessionId),y=o.useCallback(S=>{if(l?.onPointerDown&&S.button===0){if(S.currentTarget?.setPointerCapture&&S.pointerId!=null)try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}l.onPointerDown(S,e)}},[l,e]);return o.createElement("button",{type:"button",ref:u,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${f?" is-drop-zone":""}${h?" is-drop-target":""}${g?" is-insert-before":""}${b?" is-insert-after":""}${e.depth>0?" is-nested":""}`,style:d,tabIndex:e.active?0:-1,"aria-selected":e.active?"true":"false","data-session-id":e.sessionId,"data-group-row":e.isGroup?"1":void 0,"data-group-id":e.isGroup?e.groupId||"":void 0,"data-drop-group":m||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:y,onClick:p,onContextMenu:S=>{S.ctrlKey&&(S.preventDefault(),i(S,e))}},o.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${Gb(c)}px`:"0px"}},o.createElement(zb,{row:e,theme:s,structured:n,showInlineDetail:r})))});function $a(t,e){if(!Array.isArray(t))return{statusColor:null,rest:t};let s=null;const n=[];for(const r of t)if(r?.role!=="depth"&&r?.role!=="selection"){if(r?.role==="status"){s=Ve(e,r.color)||null;continue}n.push(r)}return{statusColor:s,rest:n}}function La({color:t,node:e=!1}){return o.createElement("span",{className:`ps-session-status-dot${e?" is-node":""}`,style:t?e?{borderColor:t}:{background:t}:void 0})}function Br({badge:t,size:e="sm"}){return t?o.createElement("span",{className:`ps-owner-avatar is-${e}${t.isMine?" is-mine":""}`,"data-owner-hue":String(t.hue??0),title:t.isMine?`${t.name} (you)`:t.name,"aria-label":t.name},t.initials):null}function Oa(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function zb({row:t,theme:e,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(t.titleRuns))){if(!Array.isArray(t.runs))return t.text;const u=$a(Oa(t.runs),e);return o.createElement(o.Fragment,null,u.statusColor?o.createElement(La,{color:u.statusColor,node:t.depth>0}):null,o.createElement(Br,{badge:t.ownerBadge}),o.createElement(Wa,{mark:t.canvasMark}),o.createElement("span",{className:"ps-session-row-title__text"},o.createElement(ze,{runs:u.rest,theme:e})))}const i=$a(Oa(t.titleRuns),e),a=Array.isArray(t.ctxRuns)?t.ctxRuns:[],l=a.length>0,c=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],d=n&&t.active&&c.length>0;return o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-session-row-line"},o.createElement("div",{className:"ps-session-row-title"},i.statusColor?o.createElement(La,{color:i.statusColor,node:t.depth>0}):null,o.createElement(Br,{badge:t.ownerBadge}),o.createElement(Wa,{mark:t.canvasMark}),o.createElement("span",{className:"ps-session-row-title__text"},o.createElement(ze,{runs:i.rest,theme:e}))),l?o.createElement("div",{className:"ps-session-row-ctx"},o.createElement(ze,{runs:a,theme:e})):null),d?o.createElement("div",{className:"ps-session-row-detail"},o.createElement(ze,{runs:c,theme:e})):null)}function qb(t){const e=o.useRef(t),s=o.useRef(null),n=o.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}const Fa=10,Kb=1.6,Da=.05,Vb=.95,Ba=4;function Yb(t,e){return Math.abs(t)<Fa&&Math.abs(e)<Fa?null:Math.abs(t)>Math.abs(e)*Kb?"x":"y"}function Xb(t,e=!0){o.useEffect(()=>{const s=t.current;if(!s||!e)return;let n=0,r=0,i=0,a=0,l=0,c=0,d=null,u=null,p=!1;const m=()=>{u!==null&&(cancelAnimationFrame(u),u=null)},f=()=>typeof performance<"u"?performance.now():Date.now(),h=E=>E==="x"?s.scrollWidth>s.clientWidth+1:s.scrollHeight>s.clientHeight+1,g=E=>{if(p=u!==null,m(),E.targetTouches.length!==1){d="done";return}const x=E.targetTouches[0];n=i=x.clientX,r=a=x.clientY,l=f(),c=0,d=null},b=E=>{if(d==="done"||E.targetTouches.length!==1)return;const x=E.targetTouches[0],v=x.clientX-n,P=x.clientY-r;if(d===null){const U=h("y");if(!U&&!h("x")){d="done";return}if(U&&E.cancelable&&E.preventDefault(),d=Yb(v,P),d===null)return;if(!h(d)||!E.cancelable){d="done";return}i=x.clientX,a=x.clientY,l=f()}E.cancelable&&E.preventDefault();const N=x.clientX-i,_=x.clientY-a,D=f(),L=Math.max(1,D-l),I=d==="x"?N:_;d==="x"?s.scrollLeft-=N:s.scrollTop-=_;const C=Math.max(-Ba,Math.min(Ba,I/L));c=c*.7+C*.3,i=x.clientX,a=x.clientY,l=D},y=E=>{if(Math.abs(c)<Da)return;let x=c;const v=()=>{if(x*=Vb,Math.abs(x)<Da){u=null;return}const P=E==="x"?s.scrollLeft:s.scrollTop;if(E==="x"?s.scrollLeft-=x*16:s.scrollTop-=x*16,(E==="x"?s.scrollLeft:s.scrollTop)===P){u=null;return}u=requestAnimationFrame(v)};u=requestAnimationFrame(v)},S=E=>{if(E.targetTouches.length>0){d="done";return}const x=d;d=null,(x==="x"||x==="y")&&y(x),c=0},w=()=>{d=null,c=0,m()},k=E=>{p&&(p=!1,E.preventDefault(),E.stopPropagation())};return s.addEventListener("touchstart",g,{passive:!0}),s.addEventListener("touchmove",b,{passive:!1}),s.addEventListener("touchend",S,{passive:!0}),s.addEventListener("touchcancel",w,{passive:!0}),s.addEventListener("click",k,!0),()=>{m(),s.removeEventListener("touchstart",g),s.removeEventListener("touchmove",b),s.removeEventListener("touchend",S),s.removeEventListener("touchcancel",w),s.removeEventListener("click",k,!0)}},[t,e])}function Hr({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1,showDetailBox:r=null}){const i=String(s).includes("ps-mobile-session-pane"),a=o.useRef(null),l=Ub(),c=i||l;Xb(a,c);const d=ee(t,R=>R.ui.themeId),u=ft(d),p=ee(t,R=>!!R.ui.sessionDetailCollapsed),m=o.useRef(new Map),f=ee(t,R=>({branding:R.branding,activeSessionId:R.sessions.activeSessionId,sessionsById:R.sessions.byId,sessionsFlat:R.sessions.flat,filterQuery:R.sessions.filterQuery||"",ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,manualOrder:R.sessions.manualOrder,selectedIds:R.sessions.selectedIds,selectMode:R.sessions.selectMode,auth:R.auth,connectionMode:R.connection?.mode||"local",modalOpen:!!R.ui.modal,focused:R.ui.focusRegion==="sessions",listDeselected:!!R.sessions.listDeselected,canvasBySessionId:R.canvas?.bySessionId,canvasPrefs:R.canvas?.prefs,budgetPaused:R.budget?.paused}),Le),h=o.useMemo(()=>ds({sessions:{activeSessionId:f.activeSessionId,byId:f.sessionsById,flat:f.sessionsFlat,filterQuery:f.filterQuery,ownerFilter:f.ownerFilter,pinnedIds:f.pinnedIds,manualOrder:f.manualOrder,selectedIds:f.selectedIds,selectMode:f.selectMode,listDeselected:f.listDeselected},auth:f.auth,connection:{mode:f.connectionMode},branding:f.branding,canvas:{bySessionId:f.canvasBySessionId,prefs:f.canvasPrefs},budget:{paused:f.budgetPaused}}),[f.activeSessionId,f.auth,f.branding,f.budgetPaused,f.canvasBySessionId,f.canvasPrefs,f.connectionMode,f.filterQuery,f.listDeselected,f.ownerFilter,f.pinnedIds,f.manualOrder,f.selectedIds,f.selectMode,f.sessionsById,f.sessionsFlat]),g=qb(h),b=f.activeSessionId&&f.sessionsById[f.activeSessionId]||null,y=f.activeSessionId&&g.find(R=>R.sessionId===f.activeSessionId)||null,[S,w]=o.useState(!1),[k,E]=o.useState(null),x=o.useRef(!1),v=["modelPicker","reasoningEffortPicker","contextTierPicker"],P=ee(t,R=>v.includes(R.ui.modal?.type));o.useEffect(()=>{!P&&x.current&&(x.current=!1,w(!0))},[P]);const N=()=>{x.current=!0,w(!1),t.openSwitchModelPicker(()=>{x.current=!1}).then(()=>{!v.includes(t.getState().ui.modal?.type)&&x.current&&(x.current=!1,w(!0))}).catch(R=>{x.current=!1,w(!0),t.dispatch({type:"ui/status",text:R?.message||String(R)||"Failed to switch model"})})},_=f.auth?.principal||null,D=f.auth?.authorization?.role,L=D==="admin"||D==="anonymous",I=!!(b?.owner&&_&&String(b.owner.provider)===String(_.provider)&&String(b.owner.subject)===String(_.subject)),C=!!(b&&!b.isGroup&&(b.isSystem?L:L||I)),U=Array.isArray(f.selectedIds)?f.selectedIds.length:0,B=U>1,V=!!(b?.isGroup&&!B),ce=!!(b&&!b.isSystem&&(b.isGroup||!b.parentSessionId&&!b.groupId)),X=!!(b&&Array.isArray(f.pinnedIds)&&f.pinnedIds.includes(b.sessionId)),re=!!(b?.isGroup&&Number(b.memberCount||0)===0),T=B?Array.isArray(f.selectedIds)&&f.selectedIds.some(R=>{const F=f.sessionsById[R];return F&&!F.isSystem&&!F.isGroup}):b?.isGroup?!0:!!b,j=U>0,H=!!(b&&!f.listDeselected&&!b.isSystem&&!b.isGroup&&!b.parentSessionId),W=j?f.selectedIds.filter(R=>{const F=f.sessionsById[R];return F&&!F.isSystem&&!F.isGroup&&!F.parentSessionId}):H?[b.sessionId]:[],z=`ps-session-pane${s?` ${s}`:""}`,Q=o.useRef(null);Q.current={rows:g,viewState:f,controller:t};const[K,Y]=o.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),Z=o.useRef(null),de=o.useRef(null),ve=o.useCallback(()=>{de.current!=null&&(cancelAnimationFrame(de.current),de.current=null)},[]),le=o.useCallback(()=>{let R=a.current;for(;R&&R!==document.body;){const F=window.getComputedStyle(R).overflowY;if(/(auto|scroll|overlay)/.test(F)&&R.scrollHeight-R.clientHeight>1)return R;R=R.parentElement}return null},[]),st=o.useCallback((R,F)=>{const q=le();if(!q){ve();return}const te=q.getBoundingClientRect();let se=0;if(F<te.top+48?se=-14*Math.min(1,(te.top+48-F)/48):F>te.bottom-48&&(se=14*Math.min(1,(F-(te.bottom-48))/48)),Z.current&&(Z.current.autoScrollStep=se),!Z.current){ve();return}if(de.current!=null)return;const ue=()=>{const fe=Z.current;if(!fe||!fe.autoScrollStep){ve();return}q.scrollTop+=fe.autoScrollStep,de.current=requestAnimationFrame(ue)};de.current=requestAnimationFrame(ue)},[le,ve]),ye=o.useCallback(R=>{const F=Z.current;if(Z.current=null,ve(),Y({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!R||!F?.started||F.ids.length===0)){if(F.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:F.ids[0],beforeSessionId:F.beforeSessionId});return}F.intent!=="file"&&F.intent!=="unfile"||t.moveSessionsToGroup(F.overGroupId,F.ids).catch(A=>{t.dispatch({type:"ui/status",text:`Move failed: ${A?.message||A}`})})}},[t,ve]),nt=o.useCallback((R,F)=>typeof R!="number"||typeof F!="number"?null:(document.elementFromPoint(R,F)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),Ce=o.useCallback((R,F,A,O)=>{if(typeof R!="number"||typeof F!="number"||A==null)return;const q=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(A)}"][data-orderable="1"]`));if(q.length===0)return;for(const ue of q){const fe=ue.getBoundingClientRect();if(F<fe.top+fe.height/2)return{before:ue.getAttribute("data-session-id")||null,after:null}}const se=q[q.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:se&&se!==O?se:null}},[]),Oe=o.useCallback((R,F,A)=>{const O=nt(R,F);if(A?.isGroup){const ue=A.ids.length===1?Ce(R,F,A.container,A.ids[0]):void 0;return ue===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:ue.before,after:ue.after}}const q=A?.ownGroupId||null;if(O&&O!==q)return{kind:"file",overGroupId:O,before:void 0,after:null};if(!O&&q)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const se=A?.orderable&&A.ids.length===1?Ce(R,F,A.container,A.ids[0]):void 0;return se===void 0?{kind:O?"file":"none",overGroupId:O,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:se.before,after:se.after}},[nt,Ce]);o.useEffect(()=>{if(!K.dragging)return;const R=q=>{const te=Z.current;if(!te)return;const se=Oe(q.clientX,q.clientY,te);te.intent=se.kind,te.overGroupId=se.overGroupId,te.beforeSessionId=se.before,st(q.clientX,q.clientY),document.body.classList.toggle("ps-drop-ok",se.kind==="file"),Y(ue=>({...ue,intent:se.kind,overGroupId:se.overGroupId,insertBeforeId:se.before,insertAfterId:se.after,x:q.clientX,y:q.clientY}))},F=q=>{const te=Z.current;if(te&&typeof q?.clientX=="number"){const se=Oe(q.clientX,q.clientY,te);te.intent=se.kind,te.overGroupId=se.overGroupId,te.beforeSessionId=se.before}ye(!0)},A=()=>ye(!1),O=q=>{q.key==="Escape"&&ye(!1)};return window.addEventListener("pointermove",R),window.addEventListener("pointerup",F),window.addEventListener("pointercancel",A),window.addEventListener("keydown",O),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",F),window.removeEventListener("pointercancel",A),window.removeEventListener("keydown",O),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[K.dragging,ye,Oe,st]);const ut=o.useMemo(()=>({dragging:K.dragging,overGroupId:K.overGroupId,insertBeforeId:K.insertBeforeId,insertAfterId:K.insertAfterId,onPointerDown:(R,F)=>{if(F.isSystem||!F.orderable&&!F.isGroup&&F.depth>0)return;const A=R.clientX,O=R.clientY,q={row:F,startX:A,startY:O,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!F.orderable,container:F.orderContainer??null,isGroup:!!F.isGroup,ownGroupId:F.groupId||null,intent:"none",autoScrollStep:0},te=ue=>{if(q.started||Math.hypot(ue.clientX-A,ue.clientY-O)<5)return;q.started=!0;const fe=Q.current.viewState,Te=Array.isArray(fe.selectedIds)?fe.selectedIds:[],Be=Te.includes(F.sessionId)&&Te.length>1?Te:[F.sessionId],me=fe.sessionsById||{};q.ids=Be,Z.current=q,Y({dragging:!0,ids:Be,titles:Be.map(Ke=>me[Ke]?.title||String(Ke).slice(0,8)).slice(0,3),overGroupId:null,x:ue.clientX,y:ue.clientY})},se=()=>{window.removeEventListener("pointermove",te),window.removeEventListener("pointerup",se)};window.addEventListener("pointermove",te),window.addEventListener("pointerup",se)}}),[K.dragging,K.overGroupId,K.insertBeforeId,K.insertAfterId]),rt=o.useCallback((R,F)=>{const{rows:A,viewState:O,controller:q}=Q.current;if(R.metaKey||R.ctrlKey){R.preventDefault(),O.selectMode||q.dispatch({type:"sessions/selectMode",enabled:!0}),q.dispatch({type:"sessions/selectToggle",sessionId:F.sessionId}),q.setFocus("sessions");return}if(R.shiftKey&&O.activeSessionId){R.preventDefault();const se=A.map(Te=>Te.sessionId),ue=se.indexOf(O.activeSessionId),fe=se.indexOf(F.sessionId);if(ue>=0&&fe>=0){const[Te,Be]=ue<=fe?[ue,fe]:[fe,ue],me=se.slice(Te,Be+1),Ke=Array.from(new Set([...O.selectedIds||[],...me]));q.setSessionSelection(Ke),q.setFocus("sessions");return}}if(F.hasChildren&&F.active){q.dispatch({type:F.collapsed?"sessions/expand":"sessions/collapse",sessionId:F.sessionId}),q.setFocus("sessions");return}O.selectMode&&q.dispatch({type:"sessions/selectClear"}),q.setFocus("sessions"),F.sessionId===O.activeSessionId?q.dispatch({type:"sessions/listReselect"}):F.active||q.loadSession(F.sessionId).catch(()=>{})},[]),G=o.useCallback((R,F)=>{R&&(F?m.current.set(R,F):m.current.delete(R))},[]),oe=o.useRef(null),be=`${f.activeSessionId||""}${f.focused?1:0}${f.modalOpen?1:0}`;o.useEffect(()=>{if(f.modalOpen||!f.focused||!f.activeSessionId){oe.current=null;return}const R=m.current.get(f.activeSessionId);if(!R||oe.current===be)return;oe.current=be;const F=document.activeElement,A=!!(F&&(F.tagName==="INPUT"||F.tagName==="TEXTAREA"||F.tagName==="SELECT"||F.isContentEditable));F!==R&&!A&&R.focus({preventScroll:!0}),R.scrollIntoView({block:"nearest"})},[be,f.activeSessionId,f.focused,f.modalOpen,f.sessionsFlat]);const pe=o.createElement(o.Fragment,null,B?o.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",fontSize:"12px",opacity:.85},title:"Multiple sessions selected. Move to group or cancel selected sessions; click Clear to exit."},`${U} selected`):null,B?o.createElement(he,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(M.CLEAR_SESSION_SELECTION).catch(()=>{})}):o.createElement(he,{className:"ps-mini-button ps-pin-icon",icon:o.createElement(yS),onClick:()=>t.handleCommand(M.PIN_SESSION).catch(()=>{}),disabled:!ce,active:X,label:ce?X?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),o.createElement(he,{className:"ps-mini-button",icon:W.length>1?o.createElement("span",{className:"ps-icon-badge"},o.createElement(ja),o.createElement("span",{className:"ps-icon-badge__count"},String(W.length))):o.createElement(ja),onClick:()=>t.handleCommand(M.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:W.length>1?`Move ${W.length} selected sessions to a group`:W.length===1?"Move this session to a group":"New group"}),o.createElement(he,{className:"ps-mini-button",icon:o.createElement(bd),onClick:()=>{if(b?.isGroup){t.handleCommand(M.OPEN_RENAME_SESSION).catch(()=>{});return}w(!0)},disabled:!C&&!V||B,label:B?"Disabled while multiple sessions are selected":b?.isSystem?"System sessions are managed by administrators":b?.isGroup?"Rename folder":C?"Manage session — rename, switch model, and sharing":"Only this session's owner or an admin can manage it"}),o.createElement(he,{className:"ps-mini-button",icon:o.createElement(gS),onClick:()=>{const R=b?.sessionId;if(!R)return;const F=Wc(R);F&&(Sn(F),E({url:F,warn:!1}),Py(t,R).then(A=>{E(O=>O&&O.url===F?{...O,warn:A}:O)}).catch(()=>{}))},disabled:!b||b.isGroup||B,label:"Copy link — copy a direct link to this session"}),o.createElement(he,{className:"ps-mini-button",icon:o.createElement(b?.isSystem?iS:Ur),onClick:()=>t.handleCommand(b?.isGroup?M.DELETE_SESSION:M.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!T,label:B?`Terminate ${U} selected sessions (Mark Completed, Cancel, or Delete)`:b?.isGroup?re?"Delete this empty group":"This group cannot be deleted yet":b?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),xe=K.dragging?o.createElement("div",{className:"ps-drag-ghost",style:{left:`${K.x}px`,top:`${K.y}px`}},o.createElement("div",{className:`ps-drag-ghost__stack${K.ids.length>1?" is-collection":""}`},K.ids.length>1?o.createElement("span",{className:"ps-drag-ghost__count"},String(K.ids.length)):null,o.createElement("span",{className:"ps-drag-ghost__title"},K.ids.length>1?`${K.ids.length} sessions`:K.titles[0]||"session")),o.createElement("div",{className:"ps-drag-ghost__hint"},K.intent==="file"?"Release to file here":K.intent==="unfile"?"Release to remove from folder":K.intent==="reorder"?"Release to move here":"Release to cancel")):null;return o.createElement(o.Fragment,null,xe,o.createElement(At,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:f.focused,theme:u,actions:pe,className:z},o.createElement("div",{ref:a,className:`ps-action-list ps-session-list${K.dragging?" is-dragging":""}`,onClick:R=>{R.target instanceof Element&&R.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},g.length===0?o.createElement("div",{className:"ps-empty-state"},f.filterQuery?`No sessions matched "@@${f.filterQuery}".`:"No sessions yet."):g.map(R=>o.createElement(Wb,{key:R.sessionId,row:R,theme:u,structuredRows:n,mobile:i,onRowClick:rt,setRef:G,drag:c?null:ut}))),(r===null?!i:r)?o.createElement(Hb,{session:b,childCount:y?.childCount||0,pause:y?.pause||null,controller:t,collapsed:p,onToggle:()=>t.dispatch({type:"ui/sessionDetailCollapsed",collapsed:!p})}):null),S&&b&&!b.isGroup?o.createElement(vS,{controller:t,sessionId:b.sessionId,initialTitle:b.title||"",currentModel:b.model||"",currentReasoningEffort:b.reasoningEffort||"",principal:f.auth?.principal||null,onClose:()=>w(!1),onSwitchModel:N,onChanged:()=>{}}):null,k?o.createElement(Qb,{url:k.url,warn:k.warn,onCopyAgain:()=>{Sn(k.url),t.dispatch({type:"ui/status",text:Ny})},onClose:()=>E(null)}):null)}function Qb({url:t,warn:e,onCopyAgain:s,onClose:n}){const[r,i]=o.useState(""),a=Ai(t,Pn).length>1,l=o.useCallback((d,u)=>{d==="session"&&!a?s?.():navigator?.clipboard?.writeText&&navigator.clipboard.writeText(u).catch(()=>{}),i(d),window.setTimeout(()=>i(""),1500)},[a,s]),c=d=>d.stopPropagation();return o.createElement("div",{className:"ps-share-overlay",onClick:n},o.createElement("div",{className:"ps-link-modal",onClick:c},o.createElement("div",{className:"ps-share-modal-head"},o.createElement("span",null,a?"Session links copied":"Link copied"),o.createElement("button",{className:"ps-modal-close",onClick:n,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-share-section-sub"},a?"All entry-point links were copied. Copy just the one your recipient's network can reach, or take both.":"Copied to your clipboard — anyone with access can open the session from this link."),o.createElement(zc,{url:t,keyPrefix:"session",copied:r,onCopy:l}),e?o.createElement("div",{className:"ps-link-warn"},Ty):null))}const Ha={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Re({children:t}){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},t)}function bd(){return o.createElement(Re,null,o.createElement("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"}))}function Ui(){return o.createElement(Re,null,o.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function Zb(){return o.createElement(Re,null,o.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),o.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Jb(){return o.createElement(Re,null,o.createElement("path",{d:"M3 6h18"}),o.createElement("path",{d:"M8 6V4h8v2"}),o.createElement("path",{d:"M19 6l-1 15H6L5 6"}),o.createElement("path",{d:"M10 11v5"}),o.createElement("path",{d:"M14 11v5"}))}function eS(){return o.createElement(Re,null,o.createElement("circle",{cx:"12",cy:"12",r:"9"}),o.createElement("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor"}))}function tS(){return o.createElement(Re,null,o.createElement("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),o.createElement("path",{d:"M16 3h3a2 2 0 0 1 2 2v3"}),o.createElement("path",{d:"M21 16v3a2 2 0 0 1-2 2h-3"}),o.createElement("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}))}function sS(){return o.createElement(Re,null,o.createElement("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),o.createElement("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),o.createElement("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}),o.createElement("path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}))}function nS(){return o.createElement(Re,null,o.createElement("circle",{cx:"12",cy:"12",r:"3"}),o.createElement("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"}))}function rS(){return o.createElement(Re,null,o.createElement("circle",{cx:"12",cy:"12",r:"9"}),o.createElement("path",{d:"M14.5 9.2a2.6 2.6 0 0 0-2.5-1.6c-1.5 0-2.6.8-2.6 2s1 1.7 2.6 2 2.6.8 2.6 2-1.1 2-2.6 2a2.6 2.6 0 0 1-2.5-1.6"}),o.createElement("path",{d:"M12 6v1.6"}),o.createElement("path",{d:"M12 16.4V18"}))}function iS(){return o.createElement(Re,null,o.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),o.createElement("path",{d:"M21 3v5h-5"}))}function oS(){return o.createElement(Re,null,o.createElement("path",{d:"M12 16V4"}),o.createElement("path",{d:"M7.5 8.5L12 4l4.5 4.5"}),o.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function Sd(){return o.createElement(Re,null,o.createElement("path",{d:"M12 4v12"}),o.createElement("path",{d:"M7.5 11.5L12 16l4.5-4.5"}),o.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function aS(){return o.createElement(Re,null,o.createElement("line",{x1:"4.5",y1:"3",x2:"4.5",y2:"21"}),o.createElement("line",{x1:"19.5",y1:"3",x2:"19.5",y2:"21"}),o.createElement("path",{d:"M4.5 8.5h13"}),o.createElement("path",{d:"M15 6l2.5 2.5-2.5 2.5"}),o.createElement("path",{d:"M19.5 15.5h-13"}),o.createElement("path",{d:"M9 13l-2.5 2.5 2.5 2.5"}))}function Ua(){return o.createElement(Re,null,o.createElement("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),o.createElement("line",{x1:"9.5",y1:"4",x2:"9.5",y2:"20"}),o.createElement("line",{x1:"12.5",y1:"9",x2:"18",y2:"9"}),o.createElement("line",{x1:"12.5",y1:"13",x2:"18",y2:"13"}))}function lS(){return o.createElement(Re,null,o.createElement("path",{d:"M4 17l6-6-6-6"}),o.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function cS(){return o.createElement(Re,null,o.createElement("circle",{cx:"6",cy:"6",r:"2.6"}),o.createElement("circle",{cx:"18",cy:"6",r:"2.6"}),o.createElement("circle",{cx:"12",cy:"18",r:"2.6"}),o.createElement("line",{x1:"8.6",y1:"6",x2:"15.4",y2:"6"}),o.createElement("line",{x1:"7.4",y1:"8.3",x2:"10.6",y2:"15.7"}),o.createElement("line",{x1:"16.6",y1:"8.3",x2:"13.4",y2:"15.7"}))}const dS="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",uS="M15.2 10.1A4.2 4.2 0 0 1 15.2 11.9L14.23 11.69A3.2 3.2 0 0 1 13.8 12.73L14.64 13.26A4.2 4.2 0 0 1 13.36 14.54L12.83 13.7A3.2 3.2 0 0 1 11.79 14.13L12 15.1A4.2 4.2 0 0 1 10.2 15.1L10.41 14.13A3.2 3.2 0 0 1 9.37 13.7L8.84 14.54A4.2 4.2 0 0 1 7.56 13.26L8.4 12.73A3.2 3.2 0 0 1 7.97 11.69L7 11.9A4.2 4.2 0 0 1 7 10.1L7.97 10.31A3.2 3.2 0 0 1 8.4 9.27L7.56 8.74A4.2 4.2 0 0 1 8.84 7.46L9.37 8.3A3.2 3.2 0 0 1 10.41 7.87L10.2 6.9A4.2 4.2 0 0 1 12 6.9L11.79 7.87A3.2 3.2 0 0 1 12.83 8.3L13.36 7.46A4.2 4.2 0 0 1 14.64 8.74L13.8 9.27A3.2 3.2 0 0 1 14.23 10.31ZM12.8 11A1.7 1.7 0 0 0 9.4 11A1.7 1.7 0 0 0 12.8 11Z",pS="M7.23 15.01A5.7 5.7 0 0 1 17.76 14.55L19.11 15.04L15.1 16.57L14.71 13.44L16.06 13.93A3.9 3.9 0 0 0 8.87 14.25Z";function mS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},o.createElement("path",{d:dS,strokeWidth:"1.9",strokeLinejoin:"round"}),o.createElement("path",{d:uS,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),o.createElement("path",{d:pS,fill:"currentColor",stroke:"none"}))}function fS(){return o.createElement(Re,null,o.createElement("path",{d:"M9 2.8h4.2L17 6.6v8.6a1.8 1.8 0 0 1-1.8 1.8H15"}),o.createElement("path",{d:"M4.5 9.4a1.8 1.8 0 0 1 1.8-1.8h4.2l3.8 3.8v8a1.8 1.8 0 0 1-1.8 1.8H6.3a1.8 1.8 0 0 1-1.8-1.8z"}),o.createElement("path",{d:"M10.5 7.6v3.8h3.8"}))}function hS(){return o.createElement(Re,null,o.createElement("rect",{x:"4.2",y:"12",width:"3.6",height:"8",rx:"0.6",fill:"currentColor",stroke:"none"}),o.createElement("rect",{x:"10.2",y:"6.5",width:"3.6",height:"13.5",rx:"0.6",fill:"currentColor",stroke:"none"}),o.createElement("rect",{x:"16.2",y:"9.5",width:"3.6",height:"10.5",rx:"0.6",fill:"currentColor",stroke:"none"}),o.createElement("path",{d:"M3 21h18"}))}function gS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),o.createElement("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}))}function Ur(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M3 6h18"}),o.createElement("path",{d:"M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"}),o.createElement("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),o.createElement("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),o.createElement("line",{x1:"14",y1:"11",x2:"14",y2:"17"}))}function ja(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}))}function yS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M9 3h6"}),o.createElement("path",{d:"M10 3v6l-3 3v2h10v-2l-3-3V3"}),o.createElement("line",{x1:"12",y1:"14",x2:"12",y2:"21"}))}function bS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),o.createElement("path",{d:"M3 3v5h5"}),o.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),o.createElement("path",{d:"M21 21v-5h-5"}))}function SS(t,e,s){const[n,r]=o.useState({access:null,loading:!1}),i=o.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){r({access:null,loading:!1});return}let a=!1;return r(l=>({...l,loading:!0})),t.transport.getSessionAccess(e).then(l=>{a||r({access:l,loading:!1})}).catch(()=>{a||r({access:null,loading:!1})}),()=>{a=!0}},[t,e,s]);return o.useEffect(()=>{let a;const l=setTimeout(()=>{a=i()},Cy);return()=>{clearTimeout(l),typeof a=="function"&&a()}},[i]),{access:n.access,loading:n.loading,reload:i}}function vS({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:r,principal:i,onClose:a,onSwitchModel:l,onChanged:c}){const[d,u]=o.useState("general"),[p,m]=o.useState(null),[f,h]=o.useState(s||""),[g,b]=o.useState([]),[y,S]=o.useState([]),[w,k]=o.useState("private"),[E,x]=o.useState(""),[v,P]=o.useState("write"),[N,_]=o.useState([]),[D,L]=o.useState(!1),[I,C]=o.useState(null);o.useEffect(()=>{let G=!1;return t.transport.getSessionAccess(e).then(oe=>{!G&&oe&&(m(oe),k(oe.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(oe=>{G||_(Array.isArray(oe)?oe:[])}).catch(()=>{}),()=>{G=!0}},[t,e]);const U=o.useCallback(()=>{t.transport.listSessionShares(e).then(G=>{const oe=Array.isArray(G)?G:[];b(oe),S(oe)}).catch(()=>{b([]),S([])})},[t,e]);o.useEffect(()=>{U()},[U]);const B=async G=>{L(!0),C(null);try{await G(),c?.()}catch(oe){C(oe?.message||String(oe))}finally{L(!1)}},V=()=>B(async()=>{await t.transport.renameSession(e,f.trim())}),ce=G=>{const oe=G.trim().toLowerCase();if(!oe)return null;const be=N.find(pe=>pe.displayName&&pe.displayName.toLowerCase()===oe||pe.email&&pe.email.toLowerCase()===oe||pe.subject&&pe.subject.toLowerCase()===oe);return be||{provider:i?.provider||"dev",subject:G.trim(),email:null,displayName:null}},X=G=>`${G.provider}${G.subject}`,re=G=>{const oe=X(G);S(be=>[...be.filter(pe=>X(pe)!==oe),{provider:G.provider,subject:G.subject,email:G.email??null,displayName:G.displayName??null,access:v}]),x("")},T=()=>{const G=ce(E);G&&re(G)},j=G=>{const oe=X(G);S(be=>be.filter(pe=>X(pe)!==oe))},H=new Set(y.map(X)),W=p?.owner?`${p.owner.provider}${p.owner.subject}`:null,z=E.trim().toLowerCase(),Q=z?N.filter(G=>{const oe=X(G);return oe===W||H.has(oe)?!1:G.displayName&&G.displayName.toLowerCase().includes(z)||G.email&&G.email.toLowerCase().includes(z)||G.subject&&G.subject.toLowerCase().includes(z)}).slice(0,25):[],K=!!p?.canManage,Y=p?.visibility||"private",Z=new Set(y.map(G=>`${X(G)}:${G.access}`)),de=new Set(g.map(G=>`${X(G)}:${G.access}`)),ve=Z.size!==de.size||[...Z].some(G=>!de.has(G)),le=K&&(w!==Y||ve),st=()=>B(async()=>{w!==Y&&await t.transport.setSessionVisibility(e,w);const G=new Map(g.map(xe=>[X(xe),xe])),oe=new Map(y.map(xe=>[X(xe),xe]));for(const[xe,R]of oe){const F=G.get(xe);(!F||F.access!==R.access)&&await t.transport.grantSessionShare(e,{provider:R.provider,subject:R.subject,email:R.email??null,displayName:R.displayName??null},R.access)}for(const[xe,R]of G)oe.has(xe)||await t.transport.revokeSessionShare(e,{provider:R.provider,subject:R.subject});const be=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(be)&&(b(be),S(be));const pe=await t.transport.getSessionAccess(e).catch(()=>null);pe&&(m(pe),k(pe.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),ye=l||(()=>{a(),t.openSwitchModelPicker().catch(G=>{t.dispatch({type:"ui/status",text:G?.message||String(G)||"Failed to switch model"})})}),nt=n?r?`${n}:${r}`:n:"—",Ce=[{id:"general",label:"General"},...K?[{id:"access",label:"Access"}]:[]],Oe=Ce.some(G=>G.id===d)?d:"general",ut=typeof t.transport?.regenerateSession=="function",rt=G=>G.stopPropagation();return o.createElement("div",{className:"ps-share-overlay",onClick:a},o.createElement("div",{className:"ps-share-modal",onClick:rt},o.createElement("div",{className:"ps-share-modal-head"},o.createElement("span",null,"Manage session"),o.createElement("button",{className:"ps-modal-close",onClick:a,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-manage-tabs",role:"tablist"},Ce.map(G=>o.createElement("button",{key:G.id,type:"button",role:"tab","aria-selected":Oe===G.id?"true":"false",className:`ps-manage-tab${Oe===G.id?" is-active":""}`,onClick:()=>u(G.id)},G.label))),o.createElement("div",{className:"ps-share-modal-body"},Oe==="general"?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-share-section-label"},"Name"),o.createElement("div",{className:"ps-share-add-row"},o.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:f,disabled:D,onChange:G=>h(G.target.value),onKeyDown:G=>{G.key==="Enter"&&V()}}),o.createElement("button",{className:"ps-mini-button",disabled:D||!f.trim(),onClick:V},"Save")),o.createElement("div",{className:"ps-share-section-label"},"Model"),o.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),o.createElement("div",{className:"ps-share-add-row"},o.createElement("span",{className:"ps-manage-model-current"},nt),o.createElement("button",{className:"ps-mini-button",disabled:D,onClick:ye},"Switch model…")),ut?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-share-section-label"},"Context"),o.createElement("div",{className:"ps-share-section-sub"},"Rebuild this session's working context from its summary. The transcript is archived and the session keeps running — it is not a terminal action."),o.createElement("div",{className:"ps-share-add-row"},o.createElement("button",{className:"ps-mini-button ps-manage-regenerate",disabled:D,onClick:()=>{a(),t.handleCommand(M.REGENERATE_SESSION).catch(()=>{})}},o.createElement(bS),o.createElement("span",null,"Regenerate context…")))):null):null,Oe==="access"&&K?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-share-section-label"},"General access"),o.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(G=>o.createElement("label",{key:G,className:`ps-share-radio${w===G?" is-active":""}`},o.createElement("input",{type:"radio",name:"visibility",checked:w===G,disabled:D,onChange:()=>k(G)}),o.createElement("span",{className:"ps-share-radio-glyph"},Ha[G].glyph),o.createElement("span",null,Ha[G].label),o.createElement("span",{className:"ps-share-radio-hint"},G==="private"?"only you and admins":G==="shared_read"?"everyone here can view":"everyone here can view and send"))),o.createElement("div",{className:"ps-share-section-label"},"Special access"),o.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A grant can only raise someone's access above it, never lower it — to restrict everyone, lower the general level."),y.length===0?o.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(G=>o.createElement("div",{key:`${G.provider}/${G.subject}`,className:"ps-share-grant-row"},o.createElement("span",{className:"ps-share-grant-name"},G.displayName||G.subject),o.createElement("span",{className:"ps-share-grant-access"},`can ${G.access}`),o.createElement("button",{className:"ps-mini-button",disabled:D,onClick:()=>j(G)},"Remove"))),o.createElement("div",{className:"ps-share-add-wrap"},o.createElement("div",{className:"ps-share-add-row"},o.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:E,disabled:D,autoComplete:"off",onChange:G=>x(G.target.value),onKeyDown:G=>{G.key==="Enter"&&T()}}),o.createElement("select",{className:"ps-share-add-select",value:v,disabled:D,onChange:G=>P(G.target.value)},o.createElement("option",{value:"read"},"can read"),o.createElement("option",{value:"write"},"can write")),o.createElement("button",{className:"ps-mini-button",disabled:D||!E.trim(),onClick:T},"Add")),Q.length>0?o.createElement("div",{className:"ps-share-suggestions"},Q.map(G=>o.createElement("button",{key:`${G.provider}/${G.subject}`,type:"button",className:"ps-share-suggestion",disabled:D,onClick:()=>re(G)},o.createElement("span",{className:"ps-share-suggestion-name"},G.displayName||G.subject),G.email?o.createElement("span",{className:"ps-share-suggestion-email"},G.email):null))):null),o.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in.")):null),Oe==="access"&&K?o.createElement("div",{className:"ps-manage-apply-bar is-footer"},o.createElement("span",{className:"ps-share-section-sub"},le?"Unsaved access changes.":"No changes to apply."),o.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:D||!le,onClick:st},"Apply")):null,I?o.createElement("div",{className:"ps-share-error"},I):null))}function jr({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const r=ee(t,C=>C.ui.themeId),i=ft(r),a=ee(t,C=>{const U=C.sessions.activeSessionId,B=Mn(C),V=s||e?B.totalWidth:B.leftWidth,ce=Math.max(20,V-4);return{activeSessionId:U,activeHistory:U&&C.history.bySessionId.get(U)||null,activeOutbox:U&&C.outbox?.bySessionId?.[U]?C.outbox.bySessionId[U]:[],branding:C.branding,connection:C.connection,sessionsById:C.sessions.byId,sessionsFlat:C.sessions.flat,inspectorTab:C.ui.inspectorTab,activeSessionIsGroup:!!(U&&C.sessions.byId[U]?.isGroup),activeSessionStatus:U?String(C.sessions.byId[U]?.status||"").toLowerCase():"",focused:C.ui.focusRegion==="chat",scroll:C.ui.scroll.chat,authPrincipal:C.auth?.principal||null,contentWidth:ce}},Le),l=o.useMemo(()=>({branding:a.branding,connection:a.connection,auth:{principal:a.authPrincipal},sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById,flat:a.sessionsFlat},history:{bySessionId:a.activeSessionId&&a.activeHistory?new Map([[a.activeSessionId,a.activeHistory]]):new Map},outbox:{bySessionId:a.activeSessionId?{[a.activeSessionId]:a.activeOutbox}:{}},ui:{inspectorTab:a.inspectorTab}}),[a.activeHistory,a.activeSessionId,a.activeOutbox,a.authPrincipal,a.branding,a.connection,a.inspectorTab,a.sessionsById,a.sessionsFlat]),[c,d]=Kc(),u=c??a.contentWidth,p=o.useMemo(()=>mc(l,{width:u}),[l,u]),m=sl(!!p.animateTitleRight),f=o.useMemo(()=>nl(p.titleRight,p.animateTitleRight?m:""),[m,p.animateTitleRight,p.titleRight]),[h,g]=o.useState(!1),b=!!(a.activeHistory?.hasOlderEvents&&Number(a.activeHistory?.loadedEventCount||0)>=Or),y=o.useMemo(()=>mi(l,u,{tableMode:"sentinel"}),[l,u]),S=tl(a.activeSessionStatus==="running"),k=o.useMemo(()=>pi(l,{spinnerFrame:S,maxWidth:u}),[l,S,u]),E=o.useMemo(()=>gi(l,u,{tableMode:"sentinel"}),[l,u]),x=o.useMemo(()=>k.length>0?[...E,...k]:E,[E,k]),{access:v}=SS(t,a.activeSessionId,a.activeSessionIsGroup),P=ee(t,am,Le),N=n&&!a.activeSessionIsGroup,_=!!a.sessionsById?.[a.activeSessionId]?.serviceKind,D=_||!!v&&v.canWrite===!1,L=N?o.createElement("div",{className:"ps-chat-composer"},D?o.createElement("div",{className:"ps-composer-readonly"},_?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${v.owner?.displayName||v.owner?.email||"the owner"} for write access to participate.`):o.createElement(_S,{controller:t,mobile:e,active:!0})):null,I=!!(a.activeSessionId&&a.sessionsById[a.activeSessionId]);return P&&!I?o.createElement(At,{title:p.title,color:p.color,focused:a.focused,theme:i,className:"ps-chat-panel"},o.createElement("div",{className:"ps-empty-state ps-nav-error-state"},o.createElement("div",{className:"ps-nav-error-message"},P.message),P.retryable?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(P.sessionId)},"Retry"):null)):o.createElement(_n,{controller:t,title:e?xa(p.title,28):p.title,titleRight:e&&f?xa(f,18):f,actions:null,color:p.color,focused:a.focused,lines:y,bottomStickyLines:x,scrollOffset:a.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",panelRef:d,bottomContent:L,topContent:b?o.createElement("div",{className:"ps-load-older-bar"},o.createElement("button",{type:"button",className:"ps-load-older-button",disabled:h,onClick:()=>{g(!0),t.handleCommand(M.EXPAND_HISTORY).catch(()=>{}).finally(()=>g(!1))}},h?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:null})}function wS({controller:t,onClose:e}){const s=ee(t,g=>g.ui.themeId),n=ft(s),r=ee(t,g=>{const b=g.files.selectedArtifactId||"",y=b.indexOf("/");return{sessionId:y>0?b.slice(0,y):null,filename:y>0?b.slice(y+1):"",canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Le),i=ed(r.filename),a=ee(t,g=>g.files.htmlViewMode||"rendered"),l=ee(t,g=>!!g.files.htmlFitWidth),c=o.useCallback(g=>{t.dispatch({type:"files/htmlFitWidth",enabled:g})},[t]),d=o.useCallback(g=>{t.dispatch({type:"files/htmlViewMode",mode:g})},[t]),u=ee(t,g=>Number(g.files.htmlZoom)||1),p=o.useCallback(g=>{t.dispatch({type:"files/htmlZoom",zoom:g})},[t]),m=o.useCallback(g=>{t.stepArtifactPreview(g).catch(()=>{})},[t]),f=o.useCallback(g=>{if(!(g.metaKey||g.ctrlKey||g.altKey)){if(g.key==="ArrowLeft"||g.key==="["){g.preventDefault(),m(-1);return}if(g.key==="ArrowRight"||g.key==="]"){g.preventDefault(),m(1);return}g.key==="Escape"&&(g.preventDefault(),e())}},[e,m]),h=Tn(r.sessionId,r.filename);return o.createElement("section",{className:"ps-artifact-pane",onKeyDown:f,tabIndex:-1,role:"region","aria-label":`Artifact: ${r.filename||"none"}`},o.createElement("header",{className:"ps-artifact-pane-bar"},i.kind==="page"?o.createElement(cd,{mode:a,setMode:d}):null,i.kind==="page"&&a==="rendered"?o.createElement(ld,{fitWidth:l,setFitWidth:c}):null,i.kind==="page"&&a==="rendered"?o.createElement(kn,{zoom:u,setZoom:p}):null,o.createElement("span",{className:"ps-artifact-pane-heading"},o.createElement("span",{className:"ps-artifact-pane-name",title:r.filename},td(r.filename)||"Artifact"),o.createElement("span",{className:"ps-artifact-pane-type"},i.type)),o.createElement("span",{className:"ps-artifact-pane-actions"},o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canPrev,onClick:()=>m(-1),title:"Previous artifact (←)","aria-label":"Previous artifact"},"‹"),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canNext,onClick:()=>m(1),title:"Next artifact (→)","aria-label":"Next artifact"},"›"),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{h&&(Sn(h),t.dispatch({type:"ui/status",text:Gc}))},disabled:!h,title:"Copy a link that reopens this artifact","aria-label":"Copy link"},"🔗"),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.handleCommand(M.DOWNLOAD_SELECTED_FILE).catch(()=>{}),title:"Download","aria-label":"Download"},o.createElement(Sd)),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn is-close",onClick:e,title:"Close (Esc)","aria-label":"Close artifact"},"✕"))),o.createElement("div",{className:"ps-artifact-pane-body"},o.createElement(Rn,{controller:t,focused:!1,previewOnly:!0,chromeless:!0,theme:n})))}function ES({controller:t,visible:e=!0}){const[s,n]=o.useState(!1),r=o.useCallback(()=>n(i=>!i),[]);return o.useEffect(()=>{e||n(!1)},[e]),o.createElement("div",{className:`ps-mobile-canvas-layer${s?" is-maximized":""}${e?"":" is-hidden"}`,...e?{}:{inert:!0,"aria-hidden":"true"}},o.createElement(wd,{controller:t,mobile:!0,visible:e,focusOnPromote:!0,maximized:s,onToggleMaximized:r}))}function kS({controller:t}){const e=ee(t,a=>{const l=a.files.selectedArtifactId||"";return{filename:l?l.slice(l.indexOf("/")+1):"",origin:a.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Le),s=!!Oi(e.filename)||Fi(e.filename),[n,r]=o.useState(!1);o.useEffect(()=>{r(!1)},[e.filename]);const i=o.useCallback(a=>{t.stepArtifactPreview(a).catch(()=>{})},[t]);return o.createElement("div",{className:"ps-artifact-overlay"},o.createElement("header",{className:"ps-artifact-overlay-bar"},o.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",onClick:()=>t.closeArtifactPreview().catch(()=>{}),"aria-label":e.origin==="chat"?"Close, back to chat":"Close, back to artifacts"},"✕"),o.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?o.createElement("button",{type:"button",className:`ps-artifact-overlay-btn${n?" is-active":""}`,onClick:()=>r(a=>!a),"aria-label":n?"Wrap lines":"Show full lines",title:n?"Wrap to screen width":"Full line width (scroll horizontally)"},n?"⇥":"↔"):null,o.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>i(-1),"aria-label":"Previous artifact"},"‹"),o.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>i(1),"aria-label":"Next artifact"},"›")),o.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},o.createElement(Rn,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}const xS=140;function IS(t,e,s,n){let r=t;!t||Math.abs(e-t.width)>2?r={width:e,height:s}:s>t.height&&(r={width:t.width,height:s});const i=s<=r.height-xS;return{baseline:r,takeover:i&&n}}function AS(t){const[e,s]=o.useState(!1);return o.useEffect(()=>{if(!t||typeof window>"u"||!window.visualViewport){s(!1);return}const n=window.visualViewport;let r={width:n.width,height:n.height},i=0;const a=()=>{i=0;const c=!!document.activeElement?.classList?.contains("ps-prompt-input"),d=IS(r,n.width,n.height,c);r=d.baseline,s(d.takeover)},l=()=>{i||(i=requestAnimationFrame(a))};return a(),n.addEventListener("resize",l),window.addEventListener("focusin",l),window.addEventListener("focusout",l),()=>{i&&cancelAnimationFrame(i),n.removeEventListener("resize",l),window.removeEventListener("focusin",l),window.removeEventListener("focusout",l)}},[t]),t?e:!1}function NS({controller:t,layout:e="split"}){const s=o.createElement(Hr,{controller:t,panelClassName:"ps-mobile-session-pane"});return e==="chat"?o.createElement("div",{className:"ps-mobile-workspace is-chat-only"},o.createElement("div",{className:"ps-mobile-chat-pane"},o.createElement(jr,{controller:t,mobile:!0,fullWidth:!0}))):e==="sessions"?o.createElement("div",{className:"ps-mobile-workspace is-sessions-only"},o.createElement(Hr,{controller:t,panelClassName:"ps-mobile-session-pane",showDetailBox:!0})):o.createElement("div",{className:"ps-mobile-workspace"},s,o.createElement("div",{className:"ps-mobile-chat-pane"},o.createElement(jr,{controller:t,mobile:!0,fullWidth:!0})))}function vd(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:16,height:16,"aria-hidden":"true"},o.createElement("rect",{x:2.5,y:3.5,width:15,height:11,rx:1.5,...t}),o.createElement("path",{d:"M5.5 11.5l3-3.5 2.5 2.5 3.5-4",...t}),o.createElement("path",{d:"M7 17.5h6M10 14.5v3",...t}))}function Ga(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:20,height:20,"aria-hidden":"true"},o.createElement("path",{d:"M6.2 8.6a3.8 3.8 0 0 1 7.6 0v2.9a3.8 3.8 0 0 1-7.6 0z",...t}),o.createElement("path",{d:"M6.2 10.3h7.6",...t}),o.createElement("path",{d:"M7.6 6.5a2.4 2.4 0 0 1 4.8 0",...t}),o.createElement("path",{d:"M8 4.4 6.9 2.9M12 4.4l1.1-1.5",...t}),o.createElement("path",{d:"M6.3 8.6 3.8 7.4M6.2 10.6H3.6M6.3 12.6 3.8 13.9",...t}),o.createElement("path",{d:"M13.7 8.6 16.2 7.4M13.8 10.6h2.6M13.7 12.6l2.5 1.3",...t}))}function Wa({mark:t}){if(t!=="canvas"&&t!=="unseen")return null;const e=t==="unseen",s={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("span",{className:`ps-session-canvas-mark${e?" is-unseen":""}`,title:e?"Canvas updated since you last viewed it":"This session has a canvas","aria-label":e?"Canvas updated":"Has a canvas",role:"img"},o.createElement("svg",{viewBox:"0 0 16 16",width:12,height:12,"aria-hidden":"true"},o.createElement("rect",{x:1.6,y:2.6,width:12.8,height:9.2,rx:1.4,...s}),o.createElement("path",{d:"M6 14.4h4",...s}),e?o.createElement("circle",{cx:12.4,cy:4.6,r:2.4,fill:"currentColor",stroke:"none"}):null))}function za(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:14,height:14,"aria-hidden":"true"},o.createElement("path",{d:"M8.5 11.5l3-3",...t}),o.createElement("path",{d:"M7 13l-1.8 1.8a2.8 2.8 0 01-4-4l3-3a2.8 2.8 0 014 0",...t}),o.createElement("path",{d:"M13 7l1.8-1.8a2.8 2.8 0 014 4l-3 3a2.8 2.8 0 01-4 0",...t}))}const CS=[{id:"session",label:"Session access"},{id:"public",label:"Anyone with link"}];function TS({controller:t,sessionId:e,slot:s,onClose:n}){const[r,i]=o.useState(null),[a,l]=o.useState(null),[c,d]=o.useState(!1),[u,p]=o.useState(""),[m,f]=o.useState(""),[h,g]=o.useState("session"),[b,y]=o.useState(null),[S,w]=o.useState(null),k=t.transport,E=`${window.location.origin}/?session=${encodeURIComponent(e)}&view=canvas&slot=${s}&max=1`,x=(I,C)=>o.createElement(zc,{url:I,keyPrefix:C,copied:m,onCopy:_}),v=o.useCallback(()=>{k.getCanvasShareLink?.(e,s).then(I=>i(I||{exists:!1})).catch(I=>{i({exists:!1}),p(I?.message||String(I))}),typeof k.readCanvasKv=="function"&&k.readCanvasKv(e,s,{limit:1}).then(I=>{y(I?.policy||"owner"),w(I?.me||null)}).catch(()=>{y(null),w(null)})},[k,e,s]);o.useEffect(()=>{v()},[v]);const P=S?.relation==="owner"||S?.relation==="admin",N=I=>{d(!0),p(""),k.setCanvasKvAccess(e,s,I).then(()=>y(I)).catch(C=>p(C?.message||String(C))).finally(()=>d(!1))},_=(I,C)=>{navigator.clipboard?.writeText(C).then(()=>{f(I),window.setTimeout(()=>f(""),1500)}).catch(()=>p("Could not reach the clipboard — copy the link manually."))},D=I=>{d(!0),p(""),k.resetCanvasShareLink(e,s).then(({token:C})=>{l(`${window.location.origin}/?canvasShare=${encodeURIComponent(C)}`),i({exists:!0})}).catch(C=>p(C?.message||String(C))).finally(()=>d(!1))},L=()=>{d(!0),p(""),k.removeCanvasShareLink(e,s).then(()=>{l(null),i({exists:!1})}).catch(I=>p(I?.message||String(I))).finally(()=>d(!1))};return o.createElement("div",{className:"ps-canvas-share-overlay",onClick:n},o.createElement("div",{className:"ps-canvas-share-dialog",onClick:I=>I.stopPropagation(),role:"dialog","aria-label":"Share canvas"},o.createElement("div",{className:"ps-canvas-share-title"},"Share this canvas",o.createElement("button",{type:"button",className:"ps-mini-button",onClick:n,"aria-label":"Close"},"✕")),o.createElement("div",{className:"ps-manage-tabs",role:"tablist"},CS.map(I=>o.createElement("button",{key:I.id,type:"button",role:"tab","aria-selected":h===I.id?"true":"false",className:`ps-manage-tab${h===I.id?" is-active":""}`,onClick:()=>g(I.id)},I.label))),o.createElement("div",{className:"ps-canvas-share-panels"},o.createElement("div",{className:`ps-canvas-share-panel${h==="session"?" is-active":""}`,role:"tabpanel","aria-hidden":h==="session"?void 0:"true"},o.createElement("div",{className:"ps-canvas-share-sub"},"Opens the portal signed in, canvas full screen. Session visibility rules apply."),x(E,"session"),b!==null?o.createElement("div",{className:"ps-canvas-share-policy"},o.createElement("label",{className:"ps-canvas-share-sub",htmlFor:"ps-canvas-kv-policy"},"Who can edit inside this app"),o.createElement("select",{id:"ps-canvas-kv-policy",className:"ps-canvas-slot-select",value:b,disabled:c||!P,onChange:I=>N(I.target.value)},o.createElement("option",{value:"owner"},"Only people who can edit the session"),o.createElement("option",{value:"readers"},"Anyone who can open the session"),o.createElement("option",{value:"link"},"Anyone who can open the session, plus link viewers")),o.createElement("div",{className:"ps-canvas-share-sub"},b==="owner"?"You, admins, and anyone you shared the session with as “write”. People with view-only access can watch the app but not change anything in it.":b==="link"?"Your view-only people can edit inside the app. Anyone holding the share link can watch it — link holders can never edit.":"Adds your view-only people: they can edit inside the app. It does not let them message the agent."),P?null:o.createElement("div",{className:"ps-canvas-share-sub"},"Only the session owner or an admin can change this.")):null),o.createElement("div",{className:`ps-canvas-share-panel${h==="public"?" is-active":""}`,role:"tabpanel","aria-hidden":h==="public"?void 0:"true"},o.createElement("div",{className:"ps-canvas-share-sub"},"View only, live, no sign-in. One link at a time — resetting makes the previous link stop working immediately."),r===null?o.createElement("div",{className:"ps-canvas-share-sub"},"Checking…"):a?o.createElement(o.Fragment,null,x(a,"public"),o.createElement("div",{className:"ps-canvas-share-sub is-warn"},"Copy it now — the link is shown only this once.")):r.exists?o.createElement("div",{className:"ps-canvas-share-sub"},`A link exists${r.createdAt?` (created ${new Date(r.createdAt).toLocaleString()})`:""}. For safety it cannot be re-shown — Reset to get a new one.`):o.createElement("div",{className:"ps-canvas-share-sub"},"No public link yet."),o.createElement("div",{className:"ps-canvas-share-actions"},o.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:()=>D(r?.exists)},r?.exists?"Reset link":"Create link"),r?.exists?o.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:L},"Remove link"):null))),u?o.createElement("div",{className:"ps-canvas-share-error"},u):null))}function gr({controller:t,view:e,compact:s=!1}){const n=Array.isArray(e.slots)?e.slots:[];if(n.length<=1)return null;const r=n.map(c=>c.slot),i=Math.max(0,r.indexOf(e.slot)),a=c=>{const d=r[(i+c+r.length)%r.length];t.dispatch({type:"ui/canvasSlot",slot:d})},l=c=>(c.name?c.name:`canvas ${c.slot}`)+(c.unseen?" •":"");return o.createElement("span",{className:`ps-canvas-slot-controls${s?" is-compact":""}`},o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>a(-1),title:"Previous canvas","aria-label":"Previous canvas"},"‹"),o.createElement("select",{className:"ps-canvas-slot-select",value:e.slot,onChange:c=>t.dispatch({type:"ui/canvasSlot",slot:Number(c.target.value)}),"aria-label":"Choose canvas",title:"Choose canvas"},n.map(c=>o.createElement("option",{key:c.slot,value:c.slot},l(c)))),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>a(1),title:"Next canvas","aria-label":"Next canvas"},"›"))}function qa(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,"aria-hidden":"true"},o.createElement("rect",{x:2.2,y:3.4,width:3.6,height:13.2,rx:1,...t}),o.createElement("rect",{x:8.2,y:3.4,width:9.6,height:13.2,rx:1,...t}))}function Ka(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},o.createElement("path",{d:"M8 3H3v5M12 3h5v5M12 17h5v-5M8 17H3v-5",...t}))}function Va(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},o.createElement("path",{d:"M3 8h5V3M17 8h-5V3M17 12h-5v5M3 12h5v5",...t}))}function PS({controller:t,sessionId:e,slot:s=1,latestRev:n,zoom:r,visible:i=!0,focusOnPromote:a=!1,dataRev:l=0,dataPayload:c=null,dataPatch:d=null}){const[u,p]=o.useState(null),[m,f]=o.useState(null),[h,g]=o.useState(null),[b,y]=o.useState(0),S=o.useRef({live:null,staging:null}),w=o.useRef({rev:0,used:!1}),k=o.useRef(null),E=o.useRef(null),x=o.useRef(null),v=dd(k),P=o.useRef(null),N=o.useRef(r);N.current=r;const _=o.useRef(i);_.current=i,o.useEffect(()=>{if(!t||!e)return;const I=C=>{const U=E.current,B=C.data;if(!B||typeof B!="object"||!C.source)return;const V=!!(U&&C.source===U.contentWindow),ce=!!(x.current&&C.source===x.current.contentWindow);if(!(!V&&!ce)){if(B.type==="canvas-action"){if(!V)return;t.submitCanvasAction(e,B).then(X=>{X&&X.ok===!1&&typeof console<"u"&&console.warn(`canvas action rejected: ${X.reason}`)}).catch(()=>{});return}if(B.type==="canvas-kv"){const X=B.id,re=t.transport,T=C.source,j=z=>{try{T.postMessage(z,"*")}catch{}},H=(z,Q="ERROR")=>j({type:"canvas-kv-result",id:X,ok:!1,error:String(z?.message||z||"failed"),code:z?.code||Q});if(typeof re?.readCanvasKv!="function"){H("the canvas KV store is not available on this deployment","UNAVAILABLE");return}const W=String(B.op||"");if(!V&&(W==="put"||W==="delete")){H("the canvas is still loading; retry the write in a moment","NOT_READY");return}if(W==="ready"||W==="list"){re.readCanvasKv(e,s,{prefix:B.prefix??null,limit:B.limit??null,after:B.after??null}).then(z=>j({type:W==="ready"?"canvas-kv-ready":"canvas-kv-result",id:X,ok:!0,entries:z?.entries??[],nextAfter:z?.nextAfter??null,me:z?.me??null,canWrite:!!z?.me?.canWrite,policy:z?.policy??"owner"})).catch(H);return}if(W==="get"){re.readCanvasKv(e,s,{key:B.key}).then(z=>j({type:"canvas-kv-result",id:X,ok:!0,entry:z?.entries?.[0]??null})).catch(H);return}if(W==="put"||W==="delete"){const z=W==="put"?{op:"put",key:B.key,value:B.value,...B.ifMatch!=null?{ifMatch:B.ifMatch}:{}}:{op:"delete",key:B.key,...B.ifMatch!=null?{ifMatch:B.ifMatch}:{}};re.writeCanvasKv(e,s,[z]).then(Q=>{const K=Q?.results?.[0]??{ok:!1,error:"no result"};j({type:"canvas-kv-result",id:X,ok:!!K.ok,key:K.key,rev:K.rev,capped:K.capped,error:K.error,code:K.code})}).catch(H);return}H(`unknown canvas-kv op ${W}`,"INVALID_REQUEST")}}};return window.addEventListener("message",I),()=>window.removeEventListener("message",I)},[t,e,s]),o.useEffect(()=>{if(!(!t||!e||typeof t.subscribeCanvasKv!="function"))return t.subscribeCanvasKv(e,I=>{if(!I||Number(I.slot)!==Number(s))return;const C=E.current?.contentWindow;if(!C)return;const U=B=>{try{C.postMessage({type:"canvas-kv-change",key:I.key,rev:I.rev,op:I.op,...B?{v:B.v,by:B.by,at:B.at}:{}},"*")}catch{}};if(I.op==="delete"){U(null);return}if(I.value&&typeof I.value=="object"){U({v:I.value.v,by:I.value.by,at:I.value.at});return}t.transport?.readCanvasKv?.(e,s,{key:I.key}).then(B=>U(B?.entries?.[0]??null)).catch(()=>{})})},[t,e,s]),o.useEffect(()=>{if(!t||!e||!n)return;let I=!1,C=null;return ud(t,e,s<=1?"canvas.html":`canvas${s}.html`).then(U=>{if(I){URL.revokeObjectURL(U);return}S.current.staging&&S.current.staging!==S.current.live&&URL.revokeObjectURL(S.current.staging),S.current.staging=U,g(null),f({url:U,rev:n})}).catch(()=>{if(!I){if(w.current.rev!==n&&(w.current={rev:n,used:!1}),!w.current.used){w.current.used=!0,C=setTimeout(()=>{I||y(U=>U+1)},1500);return}g({rev:n})}}),()=>{I=!0,C&&clearTimeout(C)}},[t,e,s,n,b]),o.useEffect(()=>()=>{S.current.staging&&S.current.staging!==S.current.live&&URL.revokeObjectURL(S.current.staging),S.current.live&&URL.revokeObjectURL(S.current.live),S.current={live:null,staging:null},p(null),f(null),g(null)},[e]);const D=o.useCallback(I=>{if(!I||S.current.staging!==I.url)return;const C=S.current.live;S.current.live=I.url,S.current.staging=null,C&&C!==I.url&&URL.revokeObjectURL(C),p(I),f(B=>B&&B.url===I.url?null:B);const U=k.current;if(U){const B=U.getBoundingClientRect(),V=N.current||1;P.current={w:Math.round(B.width/V),h:Math.round(B.height/V)}}if(t&&e&&_.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:I.rev}),a&&_.current)try{E.current?.focus({preventScroll:!0})}catch{}},[t,e,a]);o.useEffect(()=>{if(!(!u||!l||c===null)){try{E.current?.contentWindow?.postMessage({type:"canvas-data",data:c,dataRev:l},"*"),d&&E.current?.contentWindow?.postMessage({type:"canvas-patch",patch:d,dataRev:l},"*")}catch{}t&&e&&_.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,dataRev:l})}},[u,l,c,d,t,e]),o.useEffect(()=>{if(i&&u&&t&&e&&(t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:u.rev,...l?{dataRev:l}:{}}),a))try{E.current?.focus({preventScroll:!0})}catch{}},[i,u,t,e,a,l]),o.useEffect(()=>{if(!u||!i)return;const I=r||1,C=Math.round((v.width||0)/I),U=Math.round((v.height||0)/I);if(!C||!U)return;const B=P.current;if(B){if(!(B.w<220||B.h<170))return;const X=Math.abs(B.w-C),re=Math.abs(B.h-U);if(X<=2&&re<=2||X<=2&&re/Math.max(1,B.h)<.15)return}const V=setTimeout(()=>{P.current={w:C,h:U},y(ce=>ce+1)},350);return()=>clearTimeout(V)},[v.width,v.height,r,u,i]);const L=r!==1&&v.width>0?{flex:"none",width:`${Math.max(1,Math.round(v.width/r))}px`,height:`${Math.max(1,Math.round(v.height/r))}px`,transform:`scale(${r})`,transformOrigin:"top left"}:void 0;return o.createElement("div",{ref:k,className:"ps-html-preview-host is-fitting"},[u,m].filter(Boolean).map(I=>o.createElement("iframe",{key:`canvas:${I.rev}:${I.url}`,ref:I===u?(C=>{E.current=C}):(C=>{x.current=C}),className:`ps-html-preview-frame${I===u?"":" is-staging"}`,style:L,src:I.url,title:"Session canvas",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:I===m?()=>D(I):void 0})),h?o.createElement("div",{className:"ps-canvas-load-error"},o.createElement("span",null,u?`Couldn't load rev ${h.rev} — showing rev ${u.rev}.`:`Couldn't load rev ${h.rev}.`),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{w.current={rev:0,used:!1},g(null),y(I=>I+1)}},"Retry")):null)}const MS=160;function wd({controller:t,mobile:e=!1,visible:s=!0,focusOnPromote:n=!1,maximized:r=!1,onToggleMaximized:i=null}){const a=ee(t,fi,Le),l=ee(t,b=>Number(b.files.htmlZoom)||1),c=o.useCallback(b=>{t.dispatch({type:"files/htmlZoom",zoom:b})},[t]);o.useEffect(()=>{if(!s||!a.sessionId)return;const b=setTimeout(()=>{t.ensureCanvasSnapshot(a.sessionId).catch(()=>{})},MS);return()=>clearTimeout(b)},[t,a.sessionId,s]);const d=ee(t,b=>b?.ui?.canvasZen===!0),[u,p]=o.useState(!1),[m,f]=o.useState(null);o.useEffect(()=>{if(!r){f(null);return}let b=0;const y=()=>{const S=document.getElementById("ps-toolbar-canvas-slot");S?f(S):b=requestAnimationFrame(y)};return y(),()=>cancelAnimationFrame(b)},[r]),o.useCallback(()=>{t.dispatch({type:"ui/canvasOpen",open:!1,sessionId:a.sessionId,manual:!0})},[t,a.sessionId]);const h=e&&(a.exists||r),g=e?h?o.createElement("header",{className:"ps-artifact-pane-bar is-rev-strip"},o.createElement("span",{className:"ps-artifact-pane-type",title:a.note||void 0},a.exists?`${a.name?`${a.name} · `:""}rev ${a.latestRev}`:""),o.createElement(gr,{controller:t,view:a,compact:!0}),a.exists?o.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:()=>p(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},o.createElement(za)):null,i?o.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:i,title:r?"Back to the inset canvas":"Maximize — cover the whole screen","aria-label":r?"Restore canvas":"Maximize canvas"},o.createElement(r?Va:Ka)):null):null:r?m?Wr.createPortal(o.createElement(o.Fragment,null,a.exists?o.createElement("span",{className:"ps-toolbar-canvas-rev"},`${a.name?`${a.name} · `:""}rev ${a.latestRev}`):null,o.createElement(gr,{controller:t,view:a,compact:!0}),a.exists?o.createElement(kn,{zoom:l,setZoom:c}):null,o.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>{t.dispatch({type:"ui/canvasMaximized",on:!1}),t.dispatch({type:"ui/canvasZen",on:!d})},title:d?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":d?"Leave zen mode":"Zen mode"},o.createElement(qa)),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn ps-toolbar-canvas-restore",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!1}),title:"Back to the workspace","aria-label":"Restore canvas"},o.createElement(Va))),m):null:o.createElement("header",{className:"ps-artifact-pane-bar"},o.createElement("span",{className:"ps-artifact-pane-heading"},o.createElement("span",{className:"ps-artifact-pane-name ps-canvas-pane-glyph",title:a.note||"Canvas"},o.createElement(vd)),a.exists?o.createElement("span",{className:"ps-artifact-pane-type",title:a.note||void 0},`${a.name?`${a.name} · `:""}rev ${a.latestRev}`):null,o.createElement(gr,{controller:t,view:a})),o.createElement("span",{className:"ps-artifact-pane-actions"},a.exists?o.createElement(kn,{zoom:l,setZoom:c}):null,a.exists?o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>p(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},o.createElement(za)):null,o.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>t.dispatch({type:"ui/canvasZen"}),title:d?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":d?"Leave zen mode":"Zen mode"},o.createElement(qa)),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!0}),title:"Full screen — hide chat and sessions","aria-label":"Full screen canvas"},o.createElement(Ka))));return o.createElement("section",{className:"ps-artifact-pane ps-canvas-pane",role:"region","aria-label":"Session canvas"},g,o.createElement("div",{className:"ps-artifact-pane-body"},a.exists?o.createElement(PS,{key:`slot:${a.slot}`,controller:t,sessionId:a.sessionId,slot:a.slot,latestRev:a.latestRev,zoom:l,visible:s,focusOnPromote:n,dataRev:a.latestDataRev,dataPayload:a.dataPayload,dataPatch:a.dataPatch}):o.createElement("div",{className:"ps-canvas-blank"},o.createElement("p",{className:"ps-canvas-blank-title"},"Nothing on the canvas yet."),o.createElement("p",null,"Ask the agent to draw — a dashboard, a chart, a diagram — or it will draw when it has something worth showing."))),u&&a.exists?o.createElement(TS,{controller:t,sessionId:a.sessionId,slot:a.slot,onClose:()=>p(!1)}):null)}function Ed({activeTab:t,controller:e}){const s=o.useMemo(()=>Mi(e),[e]);return o.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>o.createElement(he,{key:n,icon:wa[n]?o.createElement(wa[n]):"•",label:vy[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Rn({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:r=!1,chromeless:i=!1}){const a=ee(t,C=>C.ui.themeId),l=ft(a),c=o.useRef(null),d=ee(t,C=>{const U=C.sessions.activeSessionId,B=Mn(C),V=s||C.files.fullscreen?C.ui.layout?.viewportWidth??120:B.rightWidth;return{activeSessionId:U,sessionsById:C.sessions.byId,sessionsFlat:C.sessions.flat,filesBySessionId:C.files.bySessionId,filesFilter:C.files.filter,selectedArtifactId:C.files.selectedArtifactId,markedIds:C.files.markedIds||[],previewOrigin:C.files.previewOrigin||null,focused:e,previewScroll:C.ui.scroll.filePreview,fullscreen:!!C.files.fullscreen,contentWidth:Math.max(20,V-4),canBrowserUpload:Ey(t),canPathUpload:ky(t),canDeleteArtifacts:Iy(t),canOpenLocally:Ay(t)}},Le),u=o.useMemo(()=>({sessions:{activeSessionId:d.activeSessionId,byId:d.sessionsById,flat:d.sessionsFlat},files:{bySessionId:d.filesBySessionId,selectedArtifactId:d.selectedArtifactId,filter:d.filesFilter,fullscreen:d.fullscreen},ui:{scroll:{filePreview:d.previewScroll}}}),[d.activeSessionId,d.filesBySessionId,d.filesFilter,d.fullscreen,d.previewScroll,d.selectedArtifactId,d.sessionsById,d.sessionsFlat]),p=o.useMemo(()=>Si(u,{listWidth:Math.max(18,d.contentWidth-4),previewWidth:Math.max(18,d.contentWidth-4),showHints:!1}),[u,d.contentWidth]),m=o.useMemo(()=>Rt(u),[u]),f=m.length>0,h=o.useCallback(C=>{const U=Array.isArray(C)?C.filter(Boolean):[];U.length!==0&&t.uploadArtifactFiles(U).catch(()=>{})},[t]),g=o.useCallback(()=>{if(d.canBrowserUpload&&c.current){c.current.click();return}d.canPathUpload&&t.handleCommand(M.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,d.canBrowserUpload,d.canPathUpload]),b=o.useMemo(()=>new Set(d.markedIds||[]),[d.markedIds]),y=o.createElement(o.Fragment,null,b.size>0?o.createElement(o.Fragment,null,o.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",opacity:.85},title:"Cmd/Ctrl-click to mark, Shift-click for a range"},`${b.size} marked`),d.canDeleteArtifacts?o.createElement(he,{icon:o.createElement(Ur),label:`Delete ${b.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,o.createElement(he,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,o.createElement("input",{ref:c,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:C=>{h(Array.from(C.currentTarget.files||[])),C.currentTarget.value=""}}),o.createElement(he,{icon:o.createElement(oS),label:"Upload",onClick:g,disabled:!d.canBrowserUpload&&!d.canPathUpload}),o.createElement(he,{icon:o.createElement(Sd),label:"Download",onClick:()=>t.handleCommand(M.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),o.createElement(he,{icon:"🔗",label:"Copy link to this artifact",onClick:()=>{const C=Tn(p.selectedSessionId,p.selectedFilename);C&&(Sn(C),t.dispatch({type:"ui/status",text:Gc}))},disabled:!f||!p.selectedFilename}),d.canDeleteArtifacts?o.createElement(he,{icon:o.createElement(Ur),label:"Delete",onClick:()=>t.handleCommand(M.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,d.canOpenLocally?o.createElement(he,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(M.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,o.createElement(he,{icon:o.createElement(Ui),label:"Filter",onClick:()=>t.handleCommand(M.OPEN_FILES_FILTER).catch(()=>{})}),o.createElement(he,{icon:o.createElement(d.fullscreen?sS:tS),label:d.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(M.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),S=o.useRef(null);o.useEffect(()=>{const C=S.current;C&&typeof C.scrollIntoView=="function"&&C.scrollIntoView({block:"nearest"})},[p.selectedIndex,d.selectedArtifactId]);const w=m.length===0?je(p.listBodyLines||[]).map((C,U)=>o.createElement(We,{key:`empty:${U}`,line:C,theme:l})):m.map((C,U)=>o.createElement("button",{key:C.id,type:"button",ref:U===p.selectedIndex?S:null,className:`ps-list-button${U===p.selectedIndex?" is-selected":""}`+(b.has(C.id)?" is-marked":""),onClick:B=>{if(t.setFocus("inspector"),B.metaKey||B.ctrlKey){t.toggleArtifactMark(C);return}if(B.shiftKey){t.markArtifactRange(C);return}t.clearArtifactMarks(),t.selectFileBrowserItem(C).then(()=>{s&&t.handleCommand(M.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},o.createElement(We,{line:je([p.listBodyLines?.[U]])[0],theme:l}))),k=!p.previewLoading&&!p.previewError,E=k&&Fi(p.selectedFilename,p.previewContentType)&&!p.previewIsBinary&&!!p.previewContent,x=k&&($i.test(String(p.previewContentType||""))||Li.test(String(p.selectedFilename||""))),v=k&&!p.previewIsBinary&&!E&&p.previewRenderMode!=="markdown"&&p.previewContent?Oi(p.selectedFilename):null,P=n?"activity":null,N=r?null:"filePreview",_=k&&!p.previewIsBinary&&Qc(p.selectedFilename,p.previewContentType)&&!!p.previewContent,L=k&&!p.previewIsBinary&&Xc(p.selectedFilename,p.previewContentType)?o.createElement(xb,{controller:t,sessionId:p.selectedSessionId,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,theme:l,color:"cyan",focused:!1,title:null,chromeless:i}):_?o.createElement(pr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:N,scrollOffset:d.previewScroll,className:"ps-csv-preview",focusRegion:P},o.createElement(rb,{content:p.previewContent,filename:p.selectedFilename})):x?o.createElement(Ma,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):v?o.createElement(pr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:N,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:P},o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,us(p.previewContent,v,l)))):E?o.createElement(pr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:N,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:P},o.createElement("pre",{className:"ps-md-code-pre is-diff"},o.createElement("code",null,Di(p.previewContent,l)))):p.previewRenderMode==="markdown"&&!p.previewLoading&&!p.previewError?o.createElement(vb,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:d.previewScroll,paneKey:N,theme:l,focusRegion:P,content:eb(p.previewContent||"")}):p.previewIsBinary&&!p.previewLoading&&!p.previewError?o.createElement(Ma,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):o.createElement(_n,{controller:t,title:null,color:"cyan",focused:!1,lines:p.previewLines,scrollOffset:d.previewScroll,scrollMode:"top",paneKey:N,focusRegion:P,className:"is-preview is-wrapped"}),I=d;return n?L:o.createElement(At,{title:I.fullscreen?p.fullscreenTitle:s&&p.panelTitleMobile?p.panelTitleMobile:p.panelTitle,color:"magenta",focused:I.focused,actions:y,theme:l},o.createElement(Ed,{activeTab:"files",controller:t}),I.fullscreen?L:o.createElement("div",{className:"ps-files-grid is-list-only"},o.createElement("div",{className:"ps-action-list ps-files-list"},w)))}function xs({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const r=ee(t,b=>{const y=Mn(b),S=b.ui.inspectorTab,w=e?b.ui.layout?.viewportWidth??120:y.rightWidth;return{inspectorTab:S,statsViewMode:b.ui.statsViewMode,adminWorkers:b.admin?.workers,nodeMapSelectedNode:b.ui.nodeMapSelectedNode,activeSessionId:b.sessions.activeSessionId,sessionsById:b.sessions.byId,sessionsFlat:b.sessions.flat,historyBySessionId:b.history.bySessionId,sessionStats:b.sessionStats,fleetStats:b.fleetStats,connection:b.connection,orchestrationBySessionId:b.orchestration.bySessionId,executionHistoryBySessionId:b.executionHistory?.bySessionId||{},executionHistoryFormat:b.executionHistory?.format||"pretty",logs:b.logs,files:b.files,focused:b.ui.focusRegion==="inspector",scroll:b.ui.scroll.inspector,followBottom:b.ui.followBottom?.inspector!==!1,logsTailing:b.logs.tailing,filesFullscreen:!!b.files.fullscreen,contentWidth:Fy(w,S,e)}},Le),i=o.useMemo(()=>({sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},history:{bySessionId:r.historyBySessionId},sessionStats:r.sessionStats,fleetStats:r.fleetStats,connection:r.connection,admin:{workers:r.adminWorkers},ui:{inspectorTab:r.inspectorTab,statsViewMode:r.statsViewMode,nodeMapSelectedNode:r.nodeMapSelectedNode,scroll:{inspector:r.scroll}},logs:r.logs,files:r.files,orchestration:{bySessionId:r.orchestrationBySessionId},executionHistory:{bySessionId:r.executionHistoryBySessionId,format:r.executionHistoryFormat}}),[r.activeSessionId,r.adminWorkers,r.connection,r.executionHistoryBySessionId,r.executionHistoryFormat,r.fleetStats,r.nodeMapSelectedNode,r.files,r.historyBySessionId,r.inspectorTab,r.sessionStats,r.statsViewMode,r.logs,r.orchestrationBySessionId,r.scroll,r.sessionsById,r.sessionsFlat]),[a,l]=Kc(),c=a??r.contentWidth,d=o.useMemo(()=>It(i,{width:c}),[i,c]),u=o.useMemo(()=>{const b=r.activeSessionId&&r.historyBySessionId?.get(r.activeSessionId)||null,y=new Map;for(const S of b?.events||[]){if(S?.eventType!=="session.turn_completed")continue;const w=Number(S?.data?.turnIndex??S?.data?.iteration);Number.isFinite(w)&&y.set(w,S)}return y},[r.activeSessionId,r.historyBySessionId]),p=o.useCallback((b,y)=>o.createElement(Fb,{lines:b,theme:y,completionByTurn:u}),[u]),m=o.useCallback((b,y)=>o.createElement(Ob,{lines:b,theme:y,controller:t}),[t]);o.useEffect(()=>{if(r.inspectorTab!=="nodes")return;t.ensureInspectorData("nodes");const b=window.setInterval(()=>{t.ensureInspectorData("nodes")},1e4);return()=>window.clearInterval(b)},[t,r.inspectorTab]);const f=o.useRef(null);if(o.useEffect(()=>{if(e)return f.current=requestAnimationFrame(()=>{try{const b=document.querySelector(".ps-mobile-pane-fill .ps-inspector-pane .ps-scroll-panel"),y=b?b.querySelector(".ps-line"):null;if(!b||!y)return;const S=window.getComputedStyle(y),w=document.createElement("span");w.style.cssText="position:absolute;visibility:hidden;white-space:pre;",w.style.fontFamily=S.fontFamily,w.style.fontSize=S.fontSize,w.style.fontWeight=S.fontWeight,w.style.letterSpacing=S.letterSpacing,w.textContent="0".repeat(100),y.parentElement.appendChild(w);const k=w.getBoundingClientRect().width/100||8;w.remove();const E=window.getComputedStyle(b),x=b.clientWidth-(parseFloat(E.paddingLeft)||0)-(parseFloat(E.paddingRight)||0);if(!(x>50))return;const P=Math.floor(x/k)+6,N=t.getState().ui.layout?.viewportWidth??120;if(Math.abs(P-N)<=2)return;t.dispatch({type:"ui/viewport",width:P,height:null})}catch{}}),()=>{f.current&&cancelAnimationFrame(f.current)}},[t,e,r.inspectorTab,r.activeSessionId]),r.inspectorTab==="files"&&!d.disabled)return o.createElement(Rn,{controller:t,focused:r.focused,mobile:e});const h=[];if(r.inspectorTab==="logs")h.push(o.createElement(he,{key:"tail",icon:r.logsTailing?"■":"⇣",label:r.logsTailing?"Stop tailing":"Tail (follow)",active:r.logsTailing,onClick:()=>t.handleCommand(M.TOGGLE_LOG_TAIL).catch(()=>{})})),h.push(o.createElement(he,{key:"filter",icon:o.createElement(Ui),label:"Filter",onClick:()=>t.handleCommand(M.OPEN_LOG_FILTER).catch(()=>{})}));else if(r.inspectorTab==="history")h.push(o.createElement(he,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(M.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),h.push(o.createElement(he,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(M.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(r.inspectorTab==="stats"){const b={session:"◉",fleet:"⬢",users:"⚇"};for(const y of["session","fleet","users"])h.push(o.createElement(he,{key:`stats-view:${y}`,icon:b[y],label:`${y.replace(/^./u,S=>S.toUpperCase())} stats`,active:r.statsViewMode===y,onClick:()=>t.setStatsViewMode(y)}))}const g=n?h.concat(n):h;return o.createElement(_n,{controller:t,title:d.title,color:"magenta",focused:r.focused,actions:g,topContent:o.createElement(Ed,{activeTab:d.activeTab,controller:t}),stickyLines:d.stickyLines||[],lines:d.lines,renderBody:d.activeTab==="sequence"?p:d.activeTab==="nodes"?m:null,scrollOffset:r.scroll,scrollMode:d.activeTab==="sequence"||d.activeTab==="logs"&&r.followBottom?"bottom":"top",stickyBottom:d.activeTab==="logs",paneKey:"inspector",panelRef:l,className:d.activeTab==="history"||d.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${d.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function yr({controller:t,panelClassName:e="",extraActions:s=null}){const n=ee(t,l=>{const c=l.sessions.activeSessionId,d=Mn(l),u=Math.max(3,d.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&l.sessions.byId[c]||null,activeHistory:c&&l.history.bySessionId.get(c)||null,focused:l.ui.focusRegion==="activity",scroll:l.ui.scroll.activity,followBottom:l.ui.followBottom?.activity!==!1,maxLines:u,nodeMapSelectedNode:l.ui.nodeMapSelectedNode,adminWorkers:l.admin?.workers,branding:l.branding,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,historyBySessionId:l.history.bySessionId,inspectorTab:l.ui.inspectorTab}},Le),r=n.inspectorTab==="nodes",i=o.useMemo(()=>({branding:n.branding,admin:{workers:n.adminWorkers},ui:{nodeMapSelectedNode:n.nodeMapSelectedNode},sessions:{activeSessionId:n.activeSessionId,byId:r?n.sessionsById:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{},flat:n.sessionsFlat},history:{bySessionId:r?n.historyBySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[r,n.activeHistory,n.activeSession,n.activeSessionId,n.adminWorkers,n.branding,n.historyBySessionId,n.nodeMapSelectedNode,n.sessionsById,n.sessionsFlat]),a=o.useMemo(()=>r?fc(i):bi(i,n.maxLines),[r,i,n.maxLines]);return o.createElement(_n,{controller:t,title:a.title,color:"gray",focused:n.focused,actions:s,lines:a.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:`ps-activity-pane${e?` ${e}`:""}`})}const Ya=Object.freeze([]);function Xa(t){const e=Number(t)||0;return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function _S({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const r=ee(t,v=>{const P=v.sessions.activeSessionId,N=P&&v.sessions.byId[P]||null,_=P&&v.outbox?.bySessionId?.[P]?v.outbox.bySessionId[P]:[];return{value:v.ui.prompt,cursor:v.ui.promptCursor,focused:v.ui.focusRegion==="prompt",modalOpen:!!v.ui.modal,answerMode:!!N?.pendingQuestion?.question,canStopTurn:ac(N),hasOutbox:_.length>0,hasPendingOutbox:_.some(D=>D?.phase==="pending"),pendingCount:_.filter(D=>D?.phase==="pending").length,editingPending:v.ui.promptEdit?.sessionId===P,selectedOutboxPhase:v.ui.promptEdit?.sessionId===P&&v.ui.promptEdit?.phase||null,promptAttachments:v.ui.promptAttachments||Ya}},Le),i=o.useRef(null),a=o.useRef(null),[l,c]=o.useState(!1),d=o.useCallback(()=>{const v=i.current;v&&(v.style.height="0px",v.style.height=`${v.scrollHeight+2}px`)},[]);o.useLayoutEffect(()=>{d()},[d,r.value]),o.useEffect(()=>(window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)),[d]);const u=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",p=u?r.promptAttachments.filter(v=>v?.kind==="image"):Ya,m=o.useRef(new Map);o.useEffect(()=>{const v=m.current,P=new Set(p.map(N=>N.file));for(const[N,_]of v)P.has(N)||(URL.revokeObjectURL(_),v.delete(N));for(const N of p)if(N.file&&!v.has(N.file))try{v.set(N.file,URL.createObjectURL(N.file))}catch{}},[p]),o.useEffect(()=>()=>{for(const v of m.current.values())URL.revokeObjectURL(v);m.current.clear()},[]);const f=o.useCallback(v=>{if(!u)return 0;const P=Array.from(v||[]).filter(_=>_&&typeof _.type=="string"&&_.type.startsWith("image/"));return P.length===0?0:t.addPendingImageFiles(P)?.accepted||0},[t,u]);o.useEffect(()=>{const v=i.current;if(!(!s||r.modalOpen||!r.focused||!v)){if(document.activeElement!==v){if(e)return;try{v.focus({preventScroll:!0})}catch{v.focus()}}v.value===r.value&&v.selectionStart!==r.cursor&&v.setSelectionRange(r.cursor,r.cursor)}},[s,e,r.cursor,r.value,r.focused,r.modalOpen]);const h=o.useCallback(()=>{t.handleCommand(M.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[g,b]=o.useState(!1),y=o.useCallback(()=>{b(!0),t.handleCommand(M.STOP_TURN).catch(()=>{}).finally(()=>b(!1))},[t]),S=o.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),w=r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"⇪":r.hasOutbox?"+":"❯",k=r.selectedOutboxPhase==="queued",E=r.selectedOutboxPhase==="cancelling",x=k||E;return o.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${l?" is-drag-over":""}`,...u?{onDragOver:v=>{v.dataTransfer?.types?.includes?.("Files")&&(v.preventDefault(),c(!0))},onDragLeave:v=>{v.currentTarget.contains(v.relatedTarget)||c(!1)},onDrop:v=>{c(!1),v.dataTransfer?.files?.length&&(v.preventDefault(),f(v.dataTransfer.files))}}:{}},p.length>0?o.createElement("div",{className:"ps-prompt-attachments"},p.map((v,P)=>{const N=v.file?m.current.get(v.file):null;return o.createElement("div",{key:`attach:${P}:${v.filename}`,className:"ps-attach-chip",title:`${v.filename} · ${Xa(v.sizeBytes)}`},N?o.createElement("img",{className:"ps-attach-thumb",src:N,alt:v.filename}):o.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),o.createElement("div",{className:"ps-attach-size"},Xa(v.sizeBytes)),o.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${v.filename}`,"aria-label":`Remove attachment ${v.filename}`,onClick:()=>t.removePendingImageAttachment(P)},"✕"))})):null,(()=>{const v=r.answerMode?"answer":E?"cancelling":k?"queued":r.editingPending?"pending":"you";return o.createElement("label",{className:`ps-prompt-label${v==="you"?" is-default":""}`},v)})(),o.createElement("textarea",{ref:i,className:"ps-prompt-input",rows:1,value:r.value,readOnly:x,placeholder:r.answerMode?"Type an answer and press Enter":r.editingPending?E?"Cancellation requested":k?"Queued message selected":"Edit the pending message, then send or cancel it":r.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:e?"enter":"send",onFocus:()=>t.setFocus("prompt"),onSelect:v=>t.setPromptCursor(v.currentTarget.selectionStart||0),onChange:v=>t.setPrompt(v.currentTarget.value,v.currentTarget.selectionStart||v.currentTarget.value.length),onPaste:u?v=>{const N=Array.from(v.clipboardData?.items||[]).filter(_=>_.kind==="file"&&_.type.startsWith("image/")).map(_=>_.getAsFile()).filter(Boolean);N.length>0&&f(N)>0&&v.preventDefault()}:void 0,onKeyDown:v=>{if(v.key==="Tab"&&!v.shiftKey&&t.acceptPromptReferenceAutocomplete()){v.preventDefault();return}if(v.key==="Escape"&&r.editingPending){if(v.preventDefault(),x){t.exitPendingPromptEdit({restoreDraft:!0});return}S();return}v.key==="Enter"&&!v.shiftKey&&!v.metaKey&&!e&&(v.preventDefault(),h())}}),o.createElement("div",{className:"ps-prompt-actions"},u?o.createElement(o.Fragment,null,o.createElement("input",{ref:a,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:v=>{f(v.currentTarget.files),v.currentTarget.value=""}}),o.createElement("button",{type:"button",className:"ps-mini-button ps-attach-button",title:"Attach images (or paste / drop them into the composer)","aria-label":"Attach images",onPointerDown:v=>v.preventDefault(),onClick:()=>a.current?.click()},"📎")):null,r.editingPending&&!E?o.createElement("button",{type:"button",className:"ps-mini-button",title:k?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":k?"Delete selected queued prompt":"Cancel selected pending prompt",onPointerDown:v=>v.preventDefault(),onClick:S},k?"Delete":"Cancel"):null,r.canStopTurn||g?o.createElement("button",{type:"button",className:`ps-stop-button${g?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:g,onPointerDown:v=>v.preventDefault(),onClick:y},"■"):null,o.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"Send all queued prompts":r.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"Send queued prompts":r.hasOutbox?"Queue prompt":"Send prompt",onPointerDown:v=>v.preventDefault(),onClick:h},w)))}const RS=1e3;function he({icon:t,label:e,onClick:s,disabled:n=!1,active:r=!1,className:i="ps-toolbar-button"}){const[a,l]=o.useState(null),c=o.useRef(null),d=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useLayoutEffect(()=>{if(!a||!d.current||typeof window>"u")return;const v=d.current.offsetWidth/2,P=6,N=Math.max(v+P,Math.min(a.x,window.innerWidth-v-P));d.current.style.left=`${N}px`},[a]);const m=(v=!1)=>{const P=c.current;if(!P||typeof window>"u")return;const N=P.getBoundingClientRect(),_=v?N.top-44<0:N.bottom+44<window.innerHeight;l({x:N.left+N.width/2,y:_?N.bottom+6:N.top-6,placement:_?"below":"above"})},f=o.useRef(null),h=o.useRef(null),g=v=>{v.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(f.current),u.current=setTimeout(m,RS))},b=v=>{v.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(f.current),l(null))},y=v=>{v.pointerType!=="mouse"&&(p.current=!1,h.current={x:v.clientX,y:v.clientY},clearTimeout(u.current),clearTimeout(f.current),u.current=setTimeout(()=>{p.current=!0,m(!0)},450))},S=v=>{if(v.pointerType==="mouse"||!h.current)return;const P=v.clientX-h.current.x,N=v.clientY-h.current.y;P*P+N*N>100&&(h.current=null,clearTimeout(u.current),l(null))},w=v=>{v.pointerType!=="mouse"&&(h.current=null,clearTimeout(u.current),p.current?(clearTimeout(f.current),f.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{p.current=!1},250)):l(null))};o.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(f.current)},[]);const k=v=>{if(p.current){p.current=!1,v.preventDefault?.();return}n||s?.(v)},E=v=>{v.preventDefault?.()},x=a&&typeof document<"u"&&document.body?Wr.createPortal(o.createElement("span",{ref:d,className:`ps-icon-tooltip is-${a.placement}`,role:"tooltip",style:{left:`${a.x}px`,top:`${a.y}px`}},e),document.body):null;return o.createElement("button",{ref:c,type:"button",className:`${i} ps-icon-button${r?" is-active":""}`,onClick:k,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:b,onPointerDown:y,onPointerMove:S,onPointerUp:w,onPointerCancel:w,onContextMenu:E},o.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),x)}function $S({controller:t,mobile:e,canvasPaneOpen:s=!1,onToggleCanvasPane:n=null,mobilePane:r="workspace",onSelectMobilePane:i=null,mobileMainLayout:a="split"}){const[l,c]=o.useState(null);o.useEffect(()=>{typeof document>"u"||c(e?null:document.getElementById("ps-header-toolbar-slot"))},[e]);const d=ee(t,I=>!!I.admin?.visible),u=ee(t,I=>!!(I.admin?.profile?.isAdmin||I.auth?.authorization?.role==="admin")),p=u?"admin console":"settings",m=ee(t,I=>!!I.ui?.budgetOpen),f=ee(t,fi,Le),h=ee(t,I=>I?.ui?.diagnosticsOpen===!0),g=ee(t,I=>I?.ui?.canvasMaximized===!0),b=ee(t,I=>!!(I?.files?.paneOpen&&I?.files?.selectedArtifactId)),y=[{key:"new",icon:o.createElement(Zb),label:"New session — choose model and agent",onClick:()=>t.handleCommand(M.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:o.createElement(Ui),label:"Filter sessions",onClick:()=>t.handleCommand(M.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:o.createElement(eS),label:"Theme",onClick:()=>t.handleCommand(M.OPEN_THEME_PICKER).catch(()=>{})},{key:"canvas",icon:o.createElement(vd),label:(e?s:f.mode==="canvas"&&!b)?"Hide the canvas":"Show canvas",onClick:()=>{if(e){n&&n();return}t.dispatch({type:"ui/canvasOpen",open:f.mode!=="canvas",sessionId:f.sessionId,manual:!0})},active:e?s:f.mode==="canvas"&&!b,badge:e?f.exists&&(f.latestRev>(f.lastViewedRev||0)||(f.latestDataRev||0)>(f.lastViewedDataRev||0))&&!s:f.unseen,loadedDot:f.exists},{key:"budget",icon:o.createElement(rS),label:m?"Close budget":"Budget — providers, limits and usage",onClick:()=>{m?t.closeBudget():t.openBudget().catch(()=>{})},active:m},...e?[]:[{key:"diagnostics",icon:o.createElement(Ga),label:h?"Hide diagnostics":"Show diagnostics (inspector and activity)",onClick:()=>t.dispatch({type:"ui/diagnosticsOpen"}),active:h}],...e?[]:[{key:"admin",icon:o.createElement(nS),label:d?`Close ${p}`:u?"Admin console":"Settings",onClick:()=>t.handleCommand(d?M.CLOSE_ADMIN_CONSOLE:M.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:d}],...e?[]:[{key:"workspace",icon:o.createElement(Ua),label:"Workspace — sessions, chat and panels",onClick:()=>t.handleCommand(M.OPEN_WORKSPACE).catch(()=>{}),active:!d&&!m}]],S=I=>{const C=o.createElement(he,{key:I.badge?void 0:I.key,icon:I.icon,label:I.label,onClick:I.onClick,disabled:!!I.disabled,active:!!I.active});return I.badge||I.loadedDot?o.createElement("span",{key:I.key,className:"ps-canvas-toggle"},C,I.loadedDot?o.createElement("span",{className:"ps-canvas-loaded-dot","aria-hidden":"true"}):null,I.badge?o.createElement("span",{className:"ps-canvas-badge","aria-hidden":"true"}):null):C};if(e){const I={split:"Main — sessions and chat (tap for chat only)",chat:"Main — chat only (tap for sessions only)",sessions:"Main — sessions only (tap for both)"},C=r==="inspector"||r==="activity",U=r==="inspector"?"activity":"inspector",B=[{id:"workspace",icon:Ua,label:I[a]||I.split,focus:"chat"},{id:U,icon:Ga,active:C,label:C?r==="inspector"?"Diagnostics — inspector (tap for activity)":"Diagnostics — activity (tap for inspector)":"Diagnostics — inspector and activity",focus:U}];return o.createElement("div",{className:"ps-toolbar is-mobile"},o.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},o.createElement("div",{className:"ps-toolbar-row-actions"},y.map(S)),o.createElement("div",{className:"ps-toolbar-row-actions is-panes"},B.map(V=>o.createElement(he,{key:V.id==="workspace"?"workspace":"diagnostics",icon:o.createElement(V.icon),label:V.label,active:V.active??r===V.id,onClick:()=>{i&&i(V.id,V.focus)}})))))}const w=d?"admin":m?"budget":"workspace",k=["new","filter"],E=["canvas","diagnostics"],x=["workspace","budget","admin"],v=I=>!g||I.key==="canvas"?I:{...I,onClick:(...C)=>(t.dispatch({type:"ui/canvasMaximized",on:!1}),I.onClick?.(...C))},P=I=>I.map(C=>y.find(U=>U.key===C)).filter(Boolean).map(v).map(S),N=I=>o.createElement("span",{key:I,className:"ps-toolbar-divider","aria-hidden":"true"}),_=w==="workspace"?[...P(k),...P(E)]:[],D=[...P(x),N("mode-divider"),...P(["theme"])],L=o.createElement("div",{className:"ps-toolbar"},o.createElement("div",{className:"ps-toolbar-side is-left"},g?_:null),o.createElement("div",{className:"ps-toolbar-actions"},g?null:_),o.createElement("div",{className:"ps-toolbar-side is-right"},o.createElement("span",{className:"ps-toolbar-meta-slot",id:"ps-toolbar-meta-slot"}),g?o.createElement("span",{className:"ps-toolbar-canvas-slot",id:"ps-toolbar-canvas-slot"}):null,g?o.createElement("span",{className:"ps-toolbar-divider","aria-hidden":"true"}):null,o.createElement("div",{className:"ps-toolbar-actions is-tools"},D),o.createElement("span",{className:"ps-toolbar-signout-slot",id:"ps-toolbar-signout-slot"})));return l?Wr.createPortal(L,l):L}function hs(t){try{t.currentTarget?.setPointerCapture?.(t.pointerId)}catch{}}function LS({controller:t,paneAdjust:e=0}){const s=o.useRef(null),[n,r]=o.useState(!1);return o.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")};let a=0,l=0;const c=()=>{a=0;const u=s.current;if(!u)return;const p=Math.round((l-u.startX)/Bc),m=p-u.appliedCells;m&&(t.adjustPaneSplit(m),u.appliedCells=p)},d=u=>{s.current&&(l=u.clientX,!a&&(a=requestAnimationFrame(c)))};return window.addEventListener("pointermove",d),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{a&&(cancelAnimationFrame(a),a=0),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),o.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown:i=>{i.button===0&&(i.preventDefault(),hs(i),s.current={startX:i.clientX,appliedCells:0},r(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:i=>{if(i.key==="ArrowLeft"){i.preventDefault(),t.handleCommand(M.GROW_RIGHT_PANE).catch(()=>{});return}i.key==="ArrowRight"&&(i.preventDefault(),t.handleCommand(M.GROW_LEFT_PANE).catch(()=>{}))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function OS({controller:t,portalSessionColumnAdjust:e=0}){const s=o.useRef(null),[n,r]=o.useState(!1);return o.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")},a=l=>{const c=s.current;if(!c)return;const d=rs(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:d})};return window.addEventListener("pointermove",a),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),o.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:i=>{if(i.button!==0)return;i.preventDefault(),hs(i);const a=i.currentTarget.closest(".ps-workspace-main-grid"),l=Dr(a?.getBoundingClientRect?.().width);s.current={startX:i.clientX,startAdjust:Number(e)||0,minAdjust:l.minAdjust,maxAdjust:l.maxAdjust},r(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:i=>{const a=i.currentTarget.closest(".ps-workspace-main-grid"),l=Dr(a?.getBoundingClientRect?.().width),c=d=>{const u=rs((Number(e)||0)+d,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};if(i.key==="ArrowLeft"){i.preventDefault(),c(-24);return}i.key==="ArrowRight"&&(i.preventDefault(),c(24))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function FS({controller:t,canvasPaneAdjust:e=0,diagnosticsPaneAdjust:s=0}){const n=o.useRef(null),[r,i]=o.useState(!1),a=(c,d)=>({canvas:_i+(Number(c)||0),diag:Ri+(Number(d)||0)}),l=(c,d)=>{const u=a(c,d);if(u.canvas<Qs||u.diag<Qs){t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0}),t.dispatch(u.canvas<Qs?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:c}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:d})};return o.useEffect(()=>{if(!r)return;const c=u=>{const p=n.current;if(!p)return;const m=u.clientX-p.startX;t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:p.startCanvas+m}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:p.startDiag-m})},d=()=>{const u=n.current;if(n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),u){const p=t.getState()?.ui?.layout||{};l(p.canvasPaneAdjust??0,p.diagnosticsPaneAdjust??0)}};return window.addEventListener("pointermove",c),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d),()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d)}},[t,r]),o.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to trade width between the canvas and diagnostics. Drag one away to close it. Double-click to reset.","aria-label":"Resize canvas and diagnostics columns",onPointerDown:c=>{c.button===0&&(c.preventDefault(),hs(c),n.current={startX:c.clientX,startCanvas:Number(e)||0,startDiag:Number(s)||0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0})},onKeyDown:c=>{if(c.key!=="ArrowLeft"&&c.key!=="ArrowRight")return;c.preventDefault();const d=c.key==="ArrowRight"?24:-24;l((Number(e)||0)+d,(Number(s)||0)-d)}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function DS({controller:t,sessionId:e,railPx:s=380}){const n=o.useRef(null),[r,i]=o.useState(!1);return o.useEffect(()=>{if(!r)return;const a=c=>{const d=n.current;d&&t.dispatch({type:"canvas/zenRail",sessionId:e,px:d.start+(c.clientX-d.startX)})},l=()=>{n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};return window.addEventListener("pointermove",a),window.addEventListener("pointerup",l),window.addEventListener("pointercancel",l),()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l)}},[t,r,e]),o.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to resize chat against the canvas (remembered for this session)","aria-label":"Resize the zen chat rail",onPointerDown:a=>{a.button===0&&(a.preventDefault(),hs(a),n.current={startX:a.clientX,start:s},i(!0),document.body.classList.add("is-resizing-pane-x"))},onKeyDown:a=>{a.key!=="ArrowLeft"&&a.key!=="ArrowRight"||(a.preventDefault(),t.dispatch({type:"canvas/zenRail",sessionId:e,px:s+(a.key==="ArrowRight"?24:-24)}))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function BS({controller:t,target:e,adjust:s=0}){const n=o.useRef(null),[r,i]=o.useState(!1),a=e==="canvas"?"ui/canvasPaneAdjust":"ui/diagnosticsPaneAdjust",l=e==="canvas"?"canvasPaneAdjust":"diagnosticsPaneAdjust",c=e==="canvas"?_i:Ri,d=u=>{if(c+u<Qs){t.dispatch({type:a,[l]:0}),t.dispatch(e==="canvas"?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:a,[l]:u})};return o.useEffect(()=>{if(!r)return;const u=m=>{const f=n.current;if(!f)return;const h=f.startAdjust-(m.clientX-f.startX);t.dispatch({type:a,[l]:Math.min(h,f.maxAdjust)})},p=()=>{const m=n.current;n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),m&&d((t.getState()?.ui?.layout||{})[l]??0)};return window.addEventListener("pointermove",u),window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p)}},[t,r,a,l]),o.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to resize. Drag the column away to close it. Double-click to reset.","aria-label":"Resize the right column",onPointerDown:u=>{if(u.button!==0)return;u.preventDefault(),hs(u);const p=document.querySelector(".ps-workspace-main-grid > .ps-workspace-pane-slot:last-child"),m=p?p.getBoundingClientRect().width:Number.POSITIVE_INFINITY,f=Number(s)||0;n.current={startX:u.clientX,startAdjust:f,maxAdjust:f+Math.max(0,m-Pi)},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>t.dispatch({type:a,[l]:0}),onKeyDown:u=>{u.key!=="ArrowLeft"&&u.key!=="ArrowRight"||(u.preventDefault(),d((Number(s)||0)-(u.key==="ArrowRight"?24:-24)))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function HS({controller:t,splitAdjust:e=0}){const s=o.useRef(null),[n,r]=o.useState(!1);return o.useEffect(()=>{if(!n)return;const i=l=>{const c=s.current;if(!c)return;const d=rs(c.start+(l.clientY-c.startY),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:d})},a=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-y")};return window.addEventListener("pointermove",i),window.addEventListener("pointerup",a),window.addEventListener("pointercancel",a),()=>{window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",a),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),o.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector and activity panes. Double-click to reset.","aria-label":"Resize the inspector and activity panes",onPointerDown:i=>{if(i.button!==0)return;i.preventDefault(),hs(i);const a=i.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,a?.getBoundingClientRect?.().height||0),c=Math.max(0,i.currentTarget.getBoundingClientRect().height||0),{minAdjust:d,maxAdjust:u}=lo(l,c);s.current={startY:i.clientY,start:rs(Number(e)||0,d,u),minAdjust:d,maxAdjust:u},r(!0),document.body.classList.add("is-resizing-pane-y")},onDoubleClick:()=>t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:0}),onKeyDown:i=>{if(i.key!=="ArrowUp"&&i.key!=="ArrowDown")return;i.preventDefault();const a=i.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,a?.getBoundingClientRect?.().height||0),c=Math.max(0,i.currentTarget.getBoundingClientRect().height||0),{minAdjust:d,maxAdjust:u}=lo(l,c);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:rs((Number(e)||0)+(i.key==="ArrowDown"?c:-c),d,u)})}},o.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}const US=[{value:"day",label:"Daily"},{value:"week",label:"Weekly"},{value:"month",label:"Monthly"}],Qa={day:"Daily",week:"Weekly",month:"Monthly"},jS={plain:"",amber:" warn",red:" over",idle:""};function GS(t){const e=Math.abs(Number(t)||0),[s,n]=e>=1e9?["B",1e9]:e>=1e6?["M",1e6]:e>=1e3?["K",1e3]:["",1],r=e/n,i=s===""||r>=100?0:r>=10?1:2;return a=>{const l=Number(a);return Number.isFinite(l)?l===0?"0":`${(l/n).toFixed(i)}${s}`:"—"}}function WS(t){const e=String(t??"").trim().replace(/[,_\s]/g,"").toUpperCase();if(!e)return null;const s=/^(\d+(?:\.\d+)?)([KMB])?$/.exec(e);if(!s)return null;const n=s[2]==="K"?1e3:s[2]==="M"?1e6:s[2]==="B"?1e9:1;if(!s[2]&&/\./.test(s[1]))return null;const r=Math.round(Number(s[1])*n);return Number.isSafeInteger(r)&&Number.isFinite(r)&&r>0?r:null}function Gr(t){return t?`resets ${t}`:"no reset recorded"}function zS(t,e,s){return`${t} ${t===1?e:s}`}function qS(t,e){return e?.typeId?t.filter(s=>s.providerId===e.typeId).map(s=>({qualifiedName:`${e.name}:${s.modelName}`,modelName:s.modelName})):[]}function KS(t){return(Array.isArray(t)?t:Array.isArray(t?.providers)?t.providers:Array.isArray(t?.models)?t.models:[]).flatMap(n=>Array.isArray(n?.models)?n.models.map(r=>({...r,providerId:r.providerId||n.providerId})):[n]).filter(n=>n&&(n.modelName||n.qualifiedName)).map(n=>({modelName:n.modelName||String(n.qualifiedName).split(":").pop(),providerId:n.providerId||"",providerType:n.providerType||n.providerId||""}))}function kd({title:t,subtitle:e,children:s,footNote:n,confirmLabel:r,danger:i=!1,busy:a=!1,disabled:l=!1,error:c=null,onCancel:d,onConfirm:u=null,cancelLabel:p="Cancel"}){const m=o.useRef(null);return o.useEffect(()=>{const f=m.current;if(!f)return;const h=()=>[...f.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')];f.contains(document.activeElement)||(h()[0]||f).focus();const g=b=>{if(b.key!=="Tab")return;const y=h();if(!y.length)return;const S=y[0],w=y[y.length-1];b.shiftKey&&document.activeElement===S?(b.preventDefault(),w.focus()):!b.shiftKey&&document.activeElement===w&&(b.preventDefault(),S.focus())};return f.addEventListener("keydown",g),()=>f.removeEventListener("keydown",g)},[]),o.useEffect(()=>{const f=h=>{h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),d())};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[d]),o.createElement("div",{className:"ps-budget-sheet-backdrop",onMouseDown:f=>{f.target===f.currentTarget&&(f.preventDefault(),d())}},o.createElement("div",{className:"ps-budget-sheet",role:"dialog","aria-modal":"true","aria-label":t,ref:m,tabIndex:-1},o.createElement("div",{className:"ps-budget-sheet-top"},o.createElement("div",{className:"ps-budget-sheet-title"},t),e?o.createElement("div",{className:"ps-budget-sheet-sub"},e):null),o.createElement("div",{className:"ps-budget-sheet-body"},s,c?o.createElement("div",{className:"ps-budget-sheet-error",role:"alert"},c):null),o.createElement("div",{className:"ps-budget-sheet-foot"},o.createElement("span",{className:"ps-budget-sheet-note"},n||""),o.createElement("div",{className:"ps-budget-sheet-actions"},o.createElement("button",{type:"button",className:"ps-mini-button",onClick:d,disabled:a},p),u?o.createElement("button",{type:"button",className:`ps-mini-button ${i?"is-danger":"is-primary"}`,onClick:u,disabled:a||l},a?"…":r):null))))}function Ge({label:t,hint:e,children:s}){return o.createElement("div",{className:"ps-budget-field",role:"group","aria-label":t},o.createElement("span",{className:"ps-budget-label"},t),s,e?o.createElement("span",{className:"ps-budget-field-hint"},e):null)}function $t({value:t,options:e,onChange:s,label:n=null}){return o.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":n||void 0},e.map(r=>o.createElement("button",{key:r.value,type:"button","aria-pressed":t===r.value?"true":"false",className:`ps-budget-seg-btn${t===r.value?" is-on":""}`,onClick:()=>s(r.value)},r.label)))}function VS(t){const e=t.known?jS[t.tone]||"":" idle";return o.createElement(o.Fragment,null,o.createElement("span",{className:`ps-budget-pct${e}`},t.usedLabel),t.providerExhausted?o.createElement("span",{className:"ps-budget-blocked",title:"The provider's own limit is spent."}," ⏻"):null," ",o.createElement("span",{className:`ps-budget-q ps-budget-sub${t.uncapped?" is-inf":""}`},`/ ${t.quotaLabel}`))}function YS(t){if(!t.split)return o.createElement("span",{className:"ps-budget-split"},"—");const e="Parts of the input, not additions to it: the total is input + output.";return o.createElement("span",{className:"ps-budget-split"},o.createElement("span",null,"in ",J(t.split.input)),o.createElement("span",null,"out ",J(t.split.output)),o.createElement("span",{title:e},"cache r ",J(t.split.cacheRead)),o.createElement("span",{title:e},"w ",J(t.split.cacheWrite)))}function XS(t,e,s){const n=t.kind==="model"?`${t.providerName} · ${t.label}`:t.providerName,r=s.uncapped?"no limit for this period":`${s.usedLabel} of ${s.quotaLabel}${s.pct==null?"":` (${s.pct}%)`}`,i=s.providerExhausted?" The provider's own limit for this period is spent, so nothing runs against it whatever your share says.":"",a=s.splitText?` Made of ${s.splitText}.`:"";return`${n} · ${e.label} — ${r}. It ${Gr(s.resetsLabel)}.${i}${a}`}function QS({controller:t,view:e,defaults:s=null}){const n=o.useCallback((l,c="*")=>{t.selectBudgetProvider(l,c).catch(()=>{})},[t]),r=l=>l.kind==="model"?o.createElement("td",{className:"ps-budget-grid-name is-model"},o.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":l.selected?"true":"false",onClick:()=>n(l.providerName,l.scope)},o.createElement("span",{className:"ps-budget-grid-mname"},l.label),o.createElement("span",{className:"ps-budget-sub"}," · model"))):o.createElement("td",{className:"ps-budget-grid-name"},o.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":l.selected?"true":"false","aria-expanded":l.modelRowCount>0?l.expanded?"true":"false":void 0,onClick:()=>n(l.providerName)},o.createElement("span",{className:"ps-budget-grid-pname"},l.label),l.ownerLabel?o.createElement("span",{className:"ps-budget-grid-owner"},`(${l.ownerLabel})`):null,l.classLabel?o.createElement("span",{className:`ps-budget-chip is-${l.class}`,title:l.class==="shared"?"Shared: anyone may spend from it. An administrator manages its limits.":l.ownedByMe===!1?"A user provider belonging to another user.":"Your own provider. Only you see it or spend from it."},l.classLabel):null,s?.mine?.provider===l.providerName?o.createElement("span",{className:"ps-budget-chip"},"my default"):null,s?.cluster?.provider===l.providerName?o.createElement("span",{className:"ps-budget-chip"},"cluster default"):null,s?.system?.provider===l.providerName?o.createElement("span",{className:"ps-budget-chip"},"system default"):null,l.hold?o.createElement("span",{className:"ps-budget-chip is-hold",title:`It ${l.hold.label}.`},"on hold"):null,l.allowanceLabel?o.createElement("span",{className:"ps-budget-grid-allow"},l.allowanceLabel):null,l.expandLabel?o.createElement("span",{className:"ps-budget-grid-teaser"},l.expandLabel):null)),i=l=>o.createElement("tr",{key:l.key,className:`ps-budget-grid-row${l.kind==="model"?" is-model":""}${l.selected?" is-on":""}`,onClick:c=>{c.target?.closest?.("button")||n(l.providerName,l.kind==="model"?l.scope:"*")}},r(l),e.columns.map(c=>o.createElement("td",{key:c.id,className:"ps-budget-grid-num","data-period":c.label,title:XS(l,c,l.cells[c.id])},VS(l.cells[c.id])))),a=l=>o.createElement("tr",{key:`${l.key}:split`,className:`ps-budget-grid-split${l.kind==="model"?" is-model":""}`,"aria-label":`What ${l.kind==="model"?l.label:l.providerName} spent, by kind of token`},o.createElement("td",{className:"ps-budget-grid-split-name"}),e.columns.map(c=>o.createElement("td",{key:c.id,className:"ps-budget-grid-num is-split","data-period":c.label},YS(l.cells[c.id]))));return o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-budget-table-head"},o.createElement("span",{className:"ps-budget-label"},`Providers${e.providerCount>0?` · ${e.providerCount}`:""}`),o.createElement("label",{className:"ps-budget-toggle"},o.createElement("input",{type:"checkbox",checked:e.overall,onChange:()=>t.setBudgetOverall()}),o.createElement("span",null,e.overallLabel))),e.empty?o.createElement("div",{className:"ps-budget-empty"},"No provider exists yet. Add one in Admin Console → Model Providers to start spending."):o.createElement("table",{className:"ps-budget-grid"},o.createElement("thead",null,o.createElement("tr",null,o.createElement("th",{className:"ps-budget-grid-h is-name",rowSpan:2,scope:"col"},"Provider"),o.createElement("th",{className:"ps-budget-grid-h is-span",colSpan:3,scope:"colgroup"},e.usageHeading)),o.createElement("tr",null,e.columns.map(l=>o.createElement("th",{key:l.id,className:"ps-budget-grid-h is-num",scope:"col"},l.label)))),o.createElement("tbody",null,e.rows.flatMap(l=>l.selected?[i(l),a(l)]:[i(l)]))))}function ZS({controller:t,view:e}){const s=e.series,n=e.selected,r={className:"ps-budget-chart-pane","data-range-days":String(e.rangeDays)},[i,a]=o.useState(null),[l,c]=o.useState(0);o.useEffect(()=>{if(!i||typeof ResizeObserver>"u")return;const w=()=>{const E=Math.round(i.getBoundingClientRect().width);c(x=>Math.abs(E-x)<1?x:E)},k=new ResizeObserver(w);return k.observe(i),w(),()=>k.disconnect()},[i]);const d=s.days,u=d.length,p=o.useMemo(()=>{const E=l-(u-1)*5,x=l>0?Math.floor(E/30):7,v=Math.max(1,Math.min(7,x)),P=Math.max(1,Math.ceil(u/v)),N=new Set;for(let _=u-1;_>=0;_-=P)N.add(_);return N},[l,u]),m=o.createElement("div",{className:"ps-budget-chart-head"},o.createElement("span",{className:"ps-budget-chart-title"},o.createElement("strong",null,n.subject),o.createElement("span",{className:"ps-budget-sub"},` · ${e.usageHeading.toLowerCase()}, by day`)),o.createElement("div",{className:"ps-budget-chart-range"},o.createElement($t,{value:e.rangeDays,options:e.rangeOptions,label:"Chart range",onChange:w=>t.setBudgetRangeDays(w).catch(()=>{})}),o.createElement("span",{className:"ps-budget-sub"},s.rangeLabel)));if(s.failed)return o.createElement("div",r,m,o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,`The daily usage for ${n.subject} could not be read.`),o.createElement("div",{className:"ps-budget-sub"},s.error)));if(s.loading&&!s.loaded)return o.createElement("div",r,m,o.createElement("div",{className:"ps-budget-empty"},"Reading the daily usage…"));const f=s.scaleMax,h=[1,.75,.5,.25,0],g=GS(f),b=d.filter(w=>w.tokens>0).length,y=s.quotaPct==null?null:Math.max(0,Math.min(96,100-s.quotaPct)),S=o.createElement("div",{className:"ps-budget-xaxis"},o.createElement("div",{className:"ps-budget-xaxis-spacer"}),o.createElement("div",{className:"ps-budget-tl-x",ref:a},d.map((w,k)=>o.createElement("span",{key:w.dayUtc,className:p.has(k)?"is-tick":void 0},p.has(k)?w.label:""))));return o.createElement("div",r,m,s.mixedScope?o.createElement("div",{className:"ps-budget-note is-warn"},"The bars are what the whole fleet spent on this provider each day. The dashed line is YOUR share of the daily limit, not the limit itself. Tick “Show overall usage” to read both as the provider's."):null,s.stale?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"These figures are from an earlier read. The most recent read failed."),o.createElement("div",{className:"ps-budget-sub"},s.error)):null,o.createElement("div",{className:"ps-budget-chart"},o.createElement("div",{className:"ps-budget-yaxis-title"},"tokens"),o.createElement("div",{className:"ps-budget-plotwrap"},o.createElement("div",{className:"ps-budget-yaxis"},f>0?h.map(w=>o.createElement("div",{key:`t${w}`,className:"ps-budget-ytick",style:{top:`${(1-w)*100}%`}},g(f*w))):null),o.createElement("div",{className:"ps-budget-plot"},f>0?h.map(w=>o.createElement("div",{key:`g${w}`,className:"ps-budget-gridline",style:{top:`${(1-w)*100}%`}})):null,y==null?null:o.createElement("div",{className:"ps-budget-tl-median",style:{top:`${y}%`}},o.createElement("span",null,`the Day limit · ${s.quotaLabel} a day`)),o.createElement("div",{className:"ps-budget-bars"},d.map(w=>o.createElement("div",{key:w.dayUtc,className:`ps-budget-tl-col${w.tokens===0?" is-idle":""}${s.quotaTokens!=null&&w.tokens>s.quotaTokens?" is-over":""}`,title:`${w.label} · ${w.tokens?`${w.tokens.toLocaleString("en-US")} tokens · ${zS(w.turns,"turn","turns")}`:"no usage"}`},o.createElement("div",{className:"ps-budget-tl-bar",style:{height:w.tokens===0?"2px":`${Math.max(1,w.pct)}%`}})))),s.empty?o.createElement("div",{className:"ps-budget-noaxis"},`No token usage on ${n.subject} in this range.`):null)),S,o.createElement("div",{className:"ps-budget-xaxis-title"},`Daily totals · UTC · ${s.rangeLabel.toLowerCase()}`),o.createElement("div",{className:"ps-budget-legend"},o.createElement("span",null,`Peak ${s.peakLabel} tokens/day`),o.createElement("span",null,`${b} of ${u} days used`),s.quotaTokens!=null?o.createElement("span",null,`Dashed line: ${s.quotaLabel} a day`):o.createElement("span",null,"No daily limit, so no line"))))}function JS({view:t}){const e=t.systemSpend;if(!e)return null;const s=n=>String(n||"").startsWith(`${t.selectedProvider}:`)?String(n).slice(t.selectedProvider.length+1):String(n||"Unknown model");return o.createElement("section",{className:"ps-budget-system-spend","aria-label":"System spend"},o.createElement("div",{className:"ps-budget-chart-head"},o.createElement("span",{className:"ps-budget-chart-title"},o.createElement("strong",null,"System spend")),o.createElement("span",{className:"ps-budget-sub"},e.rangeLabel)),e.loading&&!e.loaded?o.createElement("div",{className:"ps-budget-empty"},"Reading system spend…"):null,e.error?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},e.error):null,e.loaded?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-budget-system-stats"},o.createElement("div",{className:"ps-budget-system-stat"},o.createElement("strong",null,e.tokensLabel),o.createElement("span",null,"tokens")),o.createElement("div",{className:"ps-budget-system-stat"},o.createElement("strong",null,J(e.turns)),o.createElement("span",null,e.turns===1?"turn":"turns")),e.turns>0?o.createElement("div",{className:"ps-budget-system-stat"},o.createElement("strong",null,J(Math.round(e.tokens/e.turns))),o.createElement("span",null,"tokens / turn")):null),e.models.length?o.createElement("table",{className:"ps-budget-system-models"},o.createElement("thead",null,o.createElement("tr",null,o.createElement("th",{scope:"col"},"Model"),o.createElement("th",{scope:"col",className:"is-num"},"Tokens"),o.createElement("th",{scope:"col",className:"is-share"},"Share"),o.createElement("th",{scope:"col",className:"is-num"},"Turns"))),o.createElement("tbody",null,e.models.map(n=>{const r=e.tokens>0?n.tokens/e.tokens:0,i=Math.round(r*100);return o.createElement("tr",{key:n.key},o.createElement("td",{className:"ps-budget-system-model-name"},s(n.label)),o.createElement("td",{className:"is-num"},n.tokensLabel),o.createElement("td",{className:"is-share"},o.createElement("span",{className:"ps-budget-system-bar",role:"img","aria-label":`${i}% of system spend`},o.createElement("span",{className:"ps-budget-system-bar-fill",style:{width:`${Math.max(r>0?1:0,r*100)}%`}})),o.createElement("span",{className:"ps-budget-system-pct"},`${i}%`)),o.createElement("td",{className:"is-num"},J(n.turns)))}))):o.createElement("div",{className:"ps-budget-sub"},"No system spend in this range.")):null)}function ev({row:t,rawRows:e,models:s,isAdmin:n,busy:r,error:i,onCancel:a,onRun:l,initialPeriod:c="day",initialScope:d="*"}){const u=t.class==="shared",p=t.manageable===!0,m=[...p?[{value:"limit",label:"Limits"}]:[],...p&&n&&u?[{value:"allowance",label:"Allowance"}]:[],...p&&n?[{value:"hold",label:"Hold"}]:[]],[f,h]=o.useState("limit"),[g,b]=o.useState(c),[y,S]=o.useState(d==="*"?"all":"model"),[w,k]=o.useState(d==="*"?"":d),[E,x]=o.useState("");o.useEffect(()=>{!w&&s[0]&&k(s[0].qualifiedName)},[s,w]);const v=e.find(O=>O.providerName===t.providerName&&O.rowKind!=="model")||null,P=y==="model"?w||s[0]?.qualifiedName||"":null,N=y==="model"?e.find(O=>O.providerName===t.providerName&&O.rowKind==="model"&&O.scope===P)||null:v,_=N?.periods?.[g]||null,D=_?.quotaTokens??null,L=N?Number(_?.usedTokens)||0:null,I=L!=null,C=t.cells[g]?.resetsLabel||null,U=Qa[g]||g,B=P||"all models";o.useEffect(()=>{x(D==null?"":Number(D).toLocaleString("en-US"))},[D,g,P]);const V=WS(E),ce=!!V&&(y!=="model"||!!P),X=D!=null,re=Number.isFinite(t.allowancePct)?t.allowancePct:100,T=V==null||re>=100?V:Math.max(1,Math.floor(V*re/100)),j=Number(_?.yourUsedTokens),H=I&&V!==null&&L>=V,W=!H&&V!==null&&T!==V&&Number.isFinite(j)&&j>=T,z=Number.isFinite(t.allowancePct)?t.allowancePct:100,[Q,K]=o.useState(String(z)),Y=Number(String(Q).trim()),Z=Number.isFinite(Y)&&Y>=1&&Y<=100&&Math.floor(Y)===Y,de=["day","week","month"].map(O=>({id:O,label:Qa[O],tokens:v?.periods?.[O]?.quotaTokens??null})).filter(O=>O.tokens!=null),ve=!!t.hold,[le,st]=o.useState(ve?"release":"forever"),[ye,nt]=o.useState(""),Ce=(()=>{if(le!=="until"||!ye)return null;const O=new Date(ye);return Number.isNaN(O.getTime())?null:O.toISOString()})(),Oe=!!Ce&&Date.parse(Ce)<=Date.now(),ut=le!=="until"||!!Ce&&!Oe,rt=le!=="until"?null:Oe?"That time has already passed. A hold has to end in the future.":ye&&!Ce?"That is not a time this can read.":null,G={limit:"Limits",allowance:"Allowance",hold:"Hold"},oe={limit:X?"Replace limit":"Save limit",allowance:"Save allowance",hold:le==="release"?"Release hold":"Place hold"},be={limit:"Limits are enforced.",allowance:"Applies to everyone.",hold:"Stops new turns."},pe=f==="limit"?ce:f==="allowance"?Z:f==="hold"?ut:!0,xe=()=>{f==="limit"?ce&&l("limit",{period:g,model:P,tokens:V}):f==="allowance"?Z&&l("allowance",{pct:Y}):f==="hold"&&l("hold",le==="release"?{release:!0,untilUtc:null}:{release:!1,untilUtc:Ce})},R=o.createElement(o.Fragment,null,o.createElement(Ge,{label:"Time period",hint:"One limit per period and scope."},o.createElement($t,{value:g,onChange:b,options:US,label:"Time period"})),o.createElement(Ge,{label:"Applies to"},o.createElement($t,{value:y,onChange:S,label:"Applies to",options:[{value:"all",label:"all models"},{value:"model",label:"one model"}]}),y==="model"?o.createElement("select",{className:"ps-budget-input","aria-label":"Model this limit applies to",value:w,onChange:O=>k(O.target.value)},s.length===0?o.createElement("option",{value:""},"No models are listed for this provider's type"):s.map(O=>o.createElement("option",{key:O.qualifiedName,value:O.qualifiedName},O.qualifiedName))):null),o.createElement(Ge,{label:"Tokens",hint:V?`= ${V.toLocaleString("en-US")} tokens.`:E.trim()?"A whole number of tokens: 20,000,000 or 20M.":"Remove the limit to uncap."},o.createElement("input",{className:`ps-budget-input${E&&!V?" is-invalid":""}`,value:E,"aria-label":"Tokens",placeholder:"20,000,000 or 20M",onChange:O=>x(O.target.value),onKeyDown:O=>{O.key==="Enter"&&xe()}})),o.createElement("div",{className:"ps-budget-consequences"},o.createElement("div",null,`${U} · ${B} — `,I?o.createElement(o.Fragment,null,o.createElement("strong",null,`${L.toLocaleString("en-US")} tokens`),u?" spent by users this period.":" spent this period."):o.createElement(o.Fragment,null,o.createElement("strong",null,"not measured yet"),". Current spend will count.")),C?o.createElement("div",{className:"ps-budget-sub"},`Resets ${C}.`):null),X?o.createElement("div",{className:"ps-budget-note is-warn"},`Replaces the existing ${J(D)} token limit.`):null,o.createElement("div",{className:`ps-budget-note${H||W?" is-warn":""}`},"Current spend counts. Saving does not reset usage.",H?` ${L.toLocaleString("en-US")} already meets ${V.toLocaleString("en-US")}, so sessions on ${t.providerName} pause on their next turn${C?` — until this period ${Gr(C)}`:""}.`:W?` At ${re}% each that is ${T.toLocaleString("en-US")} per person, which you have already spent — so sessions pause on their next turn${C?` — until this period ${Gr(C)}`:""}.`:""),X?o.createElement("div",null,o.createElement("button",{type:"button",className:"ps-mini-button is-danger",disabled:r,onClick:()=>l("removeLimit",{period:g,model:P})},`Remove the ${U} · ${B} limit`),o.createElement("div",{className:"ps-budget-note"},"Usage history is kept.")):null),F=o.createElement(o.Fragment,null,o.createElement(Ge,{label:"Share per person",hint:Z?Y>=100?"100% removes the per-person ceiling.":`Each person may use up to ${Y}% of each limit, per period.`:"A whole number from 1 to 100."},o.createElement("input",{className:`ps-budget-input${Q&&!Z?" is-invalid":""}`,value:Q,"aria-label":"Share per person, as a percentage",inputMode:"numeric",placeholder:"20",onChange:O=>K(O.target.value),onKeyDown:O=>{O.key==="Enter"&&Z&&xe()}})),o.createElement("div",{className:"ps-budget-consequences"},de.length===0?o.createElement("div",{className:"ps-budget-note is-warn"},"No limits yet. The allowance applies when one is added."):o.createElement(o.Fragment,null,de.map(O=>o.createElement("div",{key:O.id},`${O.label} · ${J(O.tokens)} → `,o.createElement("strong",null,Z?`${J(Math.floor(O.tokens*Y/100))} per person`:"—"))),o.createElement("div",{className:"ps-budget-note"},"The provider limit still caps total spend.")),Z&&Y<z?o.createElement("div",{className:"ps-budget-note is-warn"},"Users already past the new ceiling pause on their next turn."):null)),A=o.createElement(o.Fragment,null,o.createElement(Ge,{label:"What to do"},o.createElement($t,{value:le,onChange:st,label:"What to do",options:[...ve?[{value:"release",label:"release it"}]:[],{value:"forever",label:"hold until released"},{value:"until",label:"hold until a time"}]})),le==="until"?o.createElement(Ge,{label:"Ends at",hint:rt||"Sessions resume at this time."},o.createElement("input",{className:`ps-budget-input${ye&&!ut?" is-invalid":""}`,"aria-label":"The hold ends at",type:"datetime-local",value:ye,onChange:O=>nt(O.target.value)})):null,ve?o.createElement("div",{className:"ps-budget-consequences"},o.createElement("div",null,`This provider is on hold: it ${t.hold.label}.`)):null,o.createElement("div",{className:`ps-budget-note${le==="release"?"":" is-warn"}`},le==="release"?`Releasing wakes every session waiting on ${t.providerName}. A session still over a limit stays paused for that reason instead.`:`Every session on ${t.providerName} pauses on its next turn. Messages sent to them are kept and answered when the hold lifts.`));return o.createElement(kd,{title:G[f],subtitle:`${t.providerName}${u?" · shared":""}`,confirmLabel:oe[f]||"",danger:f==="hold"&&le==="release",busy:r,disabled:!pe,error:i,onCancel:a,onConfirm:oe[f]?xe:null,cancelLabel:oe[f]?"Cancel":"Done",footNote:be[f]},m.length>1?o.createElement(Ge,{label:"What to change"},o.createElement($t,{value:f,onChange:h,options:m,label:"What to change"})):null,f==="limit"?R:null,f==="allowance"?F:null,f==="hold"?A:null)}function tv({types:t,existingNames:e,isAdmin:s,busy:n,error:r,onDirty:i,onCancel:a,onConfirm:l,initialName:c="",initialShared:d=!1,initialType:u="",updateProvider:p=null}){const m=!!p,[f,h]=o.useState(c),[g,b]=o.useState(u||t[0]?.id||""),[y,S]=o.useState(""),[w,k]=o.useState(""),[E,x]=o.useState(s&&d),v=o.useRef(null);o.useEffect(()=>{v.current?.focus()},[]),o.useEffect(()=>{!g&&t[0]&&b(t[0].id)},[t,g]);const P=f.trim(),N=!m&&e.some(X=>X.toLowerCase()===P.toLowerCase()),_=P!==""&&!/^[A-Za-z0-9._-]+$/.test(P),D=P.length>64,L=t.find(X=>X.id===g)?.usesWorkloadIdentity===!0,I=L,C=I?!0:E,U=!!P&&!N&&!_&&!D&&!!g&&(L||!!y.trim())&&(!I||s),B=/github/i.test(g),V=()=>{if(!U)return;const X={name:P,type:g,shared:C,credentials:L?{kind:"workloadIdentity"}:B?{githubToken:y.trim()}:{apiKey:y.trim()},baseUrl:w.trim()||null};S(""),l(X)},ce=()=>{S(""),a()};return o.createElement(kd,{title:m?`Update key for ${P}`:B?"Add GitHub Copilot provider":"Add model provider",subtitle:C?"Shared":"Personal",confirmLabel:m?"Update key":"Add provider",busy:n,disabled:!U,error:r,onCancel:ce,onConfirm:V,footNote:m?"Only the key changes. The name, type, base URL, defaults, system-session routing and usage history all stay as they are.":""},o.createElement(Ge,{label:"Name",hint:N?"A provider with that name already exists, and names are unique across the cluster.":D?`Too long: ${P.length} characters, and a name may be at most 64.`:_?'Letters, numbers, dot, dash and underscore only — no colon, no spaces, no accents: a session refers to it as "<provider>:<model>".':m?"Not changing. Sessions keep referring to it as provider:model.":"Permanent. Used in provider:model."},o.createElement("input",{ref:v,className:`ps-budget-input${m?" is-static":""}${(N||_||D)&&P?" is-invalid":""}`,"aria-label":"Provider name",value:f,placeholder:"azure-prod",disabled:m,onChange:X=>{i?.(),h(X.target.value)},onKeyDown:X=>{X.key==="Enter"&&U&&V()}})),o.createElement(Ge,{label:"Type",hint:m?"Not changing.":"Backend and model catalog."},o.createElement("select",{className:`ps-budget-input${m?" is-static":""}`,"aria-label":"Provider type",value:g,disabled:m,onChange:X=>{i?.(),b(X.target.value)}},t.length===0?o.createElement("option",{value:""},"No provider types are listed on this deployment"):t.map(X=>o.createElement("option",{key:X.id,value:X.id},X.id)))),L?o.createElement(Ge,{label:"Authentication",hint:"Nothing is stored. The worker mints a short-lived token for each request."},o.createElement("div",{className:"ps-budget-input is-static",role:"note"},"Use the Workload Identity configured in the worker")):o.createElement(Ge,{label:m?B?"New GitHub Copilot token":"New API key":B?"GitHub Copilot token":"API key",hint:m?"Replaces the current one. The existing key is never shown.":"Paste the token value."},o.createElement("input",{className:"ps-budget-input",type:"password",autoComplete:"off","aria-label":m?B?"New GitHub Copilot token":"New API key":B?"GitHub Copilot token":"API key",value:y,placeholder:"Paste token",onChange:X=>{i?.(),S(X.target.value)},onKeyDown:X=>{X.key==="Enter"&&U&&V()}})),m?null:o.createElement(Ge,{label:"Base URL",hint:"Optional."},o.createElement("input",{className:"ps-budget-input",value:w,placeholder:"https://…","aria-label":"Base URL",onChange:X=>k(X.target.value)})),I&&!m?o.createElement(Ge,{label:"Access",hint:"It runs on the worker's own identity, which belongs to the organization, so it cannot be personal."},o.createElement("div",{className:"ps-budget-input is-static",role:"note"},"Shared")):s&&!m?o.createElement(Ge,{label:"Access"},o.createElement($t,{value:E?"shared":"mine",onChange:X=>x(X==="shared"),label:"Access",options:[{value:"shared",label:"Shared"},{value:"mine",label:"Only me"}]})):null)}function sv(t){const e=t.budget||{};return[!!t.ui?.budgetOpen,e.loading,e.refreshing,e.loaded,e.error,e.grid,e.paused,e.overall,e.selectedProvider,e.selectedScope,e.missingProvider,e.series,e.tab,e.summary,t.auth?.authorization?.role,t.admin?.profile]}const nv=[14,30,90],rv=[{id:"all",label:"All providers"},{id:"shared",label:"Shared providers"},{id:"users",label:"User providers"}];function iv(t){if(t.preset==="all")return"All providers";if(t.preset==="shared")return"Shared providers";if(t.preset==="users")return"User providers";const e=t.selectedProviders.length;return e===0?"No providers":e===1?t.selectedProviders[0]:`${e} providers`}function ov({view:t,onChange:e}){const[s,n]=o.useState(!1),r=o.useRef(null);o.useEffect(()=>{if(!s)return;const d=p=>{r.current&&!r.current.contains(p.target)&&n(!1)},u=p=>{p.key==="Escape"&&n(!1)};return document.addEventListener("pointerdown",d),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",d),document.removeEventListener("keydown",u)}},[s]);const i=d=>d==="all"?[]:t.providers.filter(u=>d==="shared"?u.class==="shared":u.class!=="shared").map(u=>u.name),a=new Set(t.preset==="all"?t.providers.map(d=>d.name):t.preset==="custom"?t.selectedProviders:i(t.preset)),l=d=>{e({preset:d,providers:i(d)}),n(!1)},c=d=>{const u=new Set(a);u.has(d)?u.delete(d):u.add(d),e({preset:"custom",providers:Array.from(u)})};return o.createElement("div",{className:"ps-summary-picker",ref:r},o.createElement("button",{type:"button",className:`ps-mini-button ps-summary-picker__button${s?" is-open":""}`,"aria-haspopup":"listbox","aria-expanded":s,"aria-label":"Providers filter",onClick:()=>n(d=>!d)},iv(t)," ",o.createElement("span",{"aria-hidden":"true"},"▾")),s?o.createElement("div",{className:"ps-summary-picker__menu",role:"listbox","aria-label":"Providers"},rv.map(d=>o.createElement("button",{key:d.id,type:"button",role:"option","aria-selected":t.preset===d.id,className:`ps-summary-picker__preset${t.preset===d.id?" is-on":""}`,onClick:()=>l(d.id)},d.label)),o.createElement("div",{className:"ps-summary-picker__rule","aria-hidden":"true"}),o.createElement("button",{type:"button",className:"ps-summary-picker__preset is-clear",onClick:()=>e({preset:"custom",providers:[]})},"Clear all"),t.providers.length===0?o.createElement("div",{className:"ps-summary-picker__empty"},"No providers to choose from."):t.providers.map(d=>o.createElement("label",{key:d.name,className:"ps-summary-picker__row"},o.createElement("input",{type:"checkbox",checked:a.has(d.name),onChange:()=>c(d.name),"aria-label":`Include ${d.name}`}),o.createElement("span",{className:"ps-summary-picker__name"},d.name),o.createElement("span",{className:`ps-scope-badge is-${d.class}`},d.class==="shared"?"shared":"user")))):null)}function _e(t){return J(Number(t)||0)}function xd(t){const e=t.map(i=>i.total),s=Math.max(0,...e),n=e.filter(i=>i>0).sort((i,a)=>i-a),r=n.length?n[Math.floor(n.length/2)]:0;return r>0&&s>r*10}function av({series:t}){const a=t.map(S=>S.total),l=Math.max(0,...a),c=xd(t),d=S=>c?Math.log10(1+S):S,u=d(l)||1,p=160,m=S=>p-d(S)/u*p,f=Math.max(1,t.length),h=662/f,g=Math.max(3,h*.66),b=c?[0,...Array.from({length:Math.floor(Math.log10(Math.max(10,l)))},(S,w)=>Math.pow(10,w+1))].filter(S=>S<=l||S===0).map(S=>({f:d(S)/u,label:_e(S)})):[0,.25,.5,.75,1].map(S=>({f:S,label:_e(S*l)})),y=f>40?10:f>20?5:1;return o.createElement("svg",{className:"ps-summary-chart",viewBox:"0 0 720 190",role:"img","aria-label":`Tokens per day, ${t.length} days${c?", log scale":""}`},b.map(S=>o.createElement("g",{key:S.label+S.f},o.createElement("line",{x1:58,x2:720,y1:8+p-S.f*p,y2:8+p-S.f*p,className:"ps-summary-chart__grid"}),o.createElement("text",{x:52,y:8+p-S.f*p+3,className:"ps-summary-chart__tick",textAnchor:"end"},S.label))),t.map((S,w)=>{const k=58+w*h+(h-g)/2,E=Math.min(S.input,S.cacheRead),x=Math.min(S.input-E,S.cacheWrite),v=S.input-E-x,P=v+E,N=S.input,_=N+S.output,D=8+p,L=8+m(v),I=8+m(P),C=8+m(N),U=8+m(_),B=`${S.day}: ${_e(S.total)} tokens · in ${_e(S.input)} (cache r ${_e(S.cacheRead)} · w ${_e(S.cacheWrite)}) · out ${_e(S.output)} · ${S.turns} turns`;return o.createElement("g",{key:S.day,className:"ps-summary-chart__bar"},o.createElement("title",null,B),o.createElement("rect",{x:k,y:L,width:g,height:Math.max(0,D-L),className:"is-in"}),o.createElement("rect",{x:k,y:I,width:g,height:Math.max(0,L-I),className:"is-cache"}),o.createElement("rect",{x:k,y:C,width:g,height:Math.max(0,I-C),className:"is-cache-w"}),o.createElement("rect",{x:k,y:U,width:g,height:Math.max(0,C-U),className:"is-out"}),w%y===0||w===f-1?o.createElement("text",{x:k+g/2,y:184,className:"ps-summary-chart__day",textAnchor:"middle"},S.day.slice(5)):null)}))}function lv({values:t}){const e=Math.max(0,...t);return o.createElement("span",{className:"ps-summary-spark","aria-hidden":"true",style:{gridAutoColumns:t.length>30?"2px":"4px"}},t.map((s,n)=>o.createElement("i",{key:n,style:{height:`${e>0?Math.max(s>0?8:0,s/e*100):0}%`}})))}function br({label:t,w:e}){return o.createElement("div",{className:"ps-summary-kpi"},o.createElement("div",{className:"ps-summary-kpi__label"},t),o.createElement("div",{className:"ps-summary-kpi__value"},_e(e.total)),o.createElement("div",{className:"ps-summary-kpi__split",title:"Total is input + output. Cache read and write are parts of the input, not additions to it."},o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-in"}),"in ",_e(e.input)),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-cache"}),"cache r ",_e(e.cacheRead)),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-cache-w"}),"w ",_e(e.cacheWrite)),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-out"}),"out ",_e(e.output)),o.createElement("span",null,`· ${e.turns} turns`)))}function cv(t){const e=t.budget?.summary||{};return[e.loading,e.error,e.fetchedAt,e.days,e.preset,(e.providers||[]).join(","),(t.budget?.grid||[]).length]}function dv({controller:t}){const e=ee(t,cv,Le),s=o.useMemo(()=>mf(t.getState()),[t,e]);o.useEffect(()=>{!s.loaded&&!s.loading&&!s.error&&t.loadUsageSummary().catch(()=>{})},[t]);const n=l=>t.setUsageSummaryFilter({days:l}).catch(()=>{}),r=({preset:l,providers:c})=>t.setUsageSummaryFilter({preset:l,providers:c}).catch(()=>{}),i=s.classes.filter(l=>l.total>0),a=`last ${s.days} days`;return o.createElement("div",{className:`ps-summary${s.loading?" is-loading":""}`},o.createElement("div",{className:"ps-summary__filters"},o.createElement(ov,{view:s,onChange:r}),o.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":"Window"},nv.map(l=>o.createElement("button",{key:l,type:"button",className:`ps-budget-seg__button${s.days===l?" is-on":""}`,"aria-pressed":s.days===l,"aria-label":`Last ${l} days`,onClick:()=>n(l)},`${l}d`))),o.createElement("span",{className:"ps-summary__scope"},s.scope==="cluster"?"Whole cluster, system sessions included":"Your own turns")),s.error?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"The summary could not be read. "),o.createElement("div",{className:"ps-budget-sub"},s.error)):null,o.createElement("div",{className:"ps-summary__kpis"},o.createElement(br,{label:"Today (UTC)",w:s.windows.day}),o.createElement(br,{label:"Last 7 days",w:s.windows.week}),o.createElement(br,{label:"Last 30 days",w:s.windows.month})),o.createElement("div",{className:"ps-summary__card"},o.createElement("div",{className:"ps-summary__card-head"},o.createElement("b",null,"Tokens per day"),o.createElement("span",{className:"ps-summary__legend"},o.createElement("span",{title:"Prompt tokens that were neither served from nor written to the cache"},o.createElement("i",{className:"ps-summary-dot is-in"}),"input"),o.createElement("span",{title:"The part of the input served from the cache"},o.createElement("i",{className:"ps-summary-dot is-cache"}),"cache read"),o.createElement("span",{title:"The part of the input written to the cache"},o.createElement("i",{className:"ps-summary-dot is-cache-w"}),"cache write"),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-out"}),"output")),o.createElement("span",{className:"ps-summary__muted"},`${a} · ${_e(s.windowTotal)} tokens`),xd(s.series)?o.createElement("span",{className:"ps-summary__tag",title:"One day is more than ten times the median, so the axis is log10 — otherwise every other day is a hairline."},"log scale"):null),s.windowTotal>0||s.loaded?o.createElement(av,{series:s.series}):null,i.length>1?o.createElement("div",{className:"ps-summary__muted"},"By charge: ",i.map((l,c)=>`${c?" · ":""}${l.chargeClass} ${_e(l.total)}`).join("")):null),o.createElement("div",{className:"ps-summary__card"},o.createElement("div",{className:"ps-summary__card-head"},o.createElement("b",null,"By model"),o.createElement("span",{className:"ps-summary__muted"},`${a} · across providers, efforts and context tiers`)),s.models.length===0?o.createElement("div",{className:"ps-budget-empty"},s.loaded?"No token usage in this window.":s.loading?"Reading…":""):o.createElement("div",{className:"ps-summary__table-wrap"},o.createElement("table",{className:"ps-summary__table"},o.createElement("thead",null,o.createElement("tr",null,[["Model"],["Turns"],["Providers","Distinct provider names in the ledger for this window — including providers since deleted"],["Input","Prompt tokens, including what was served from and written to the cache"],["Output"],["Cache read","The part of Input served from the cache"],["Cache write","The part of Input written to the cache"],["Total","Input + Output"],["Share"],["Trend"]].map(([l,c])=>o.createElement("th",{key:l,title:c},l)))),o.createElement("tbody",null,s.models.map(l=>o.createElement("tr",{key:l.model},o.createElement("td",{className:"is-model"},l.model),o.createElement("td",null,l.turns),o.createElement("td",null,l.providers),o.createElement("td",null,_e(l.input)),o.createElement("td",null,_e(l.output)),o.createElement("td",null,_e(l.cacheRead)),o.createElement("td",null,_e(l.cacheWrite)),o.createElement("td",{className:"is-total"},_e(l.total)),o.createElement("td",{className:"is-share"},o.createElement("i",{className:"ps-summary-share",style:{width:`${Math.max(1,Math.round(l.share*100))}px`}}),`${(l.share*100).toFixed(l.share<.1?1:0)}%`),o.createElement("td",null,o.createElement(lv,{values:l.sparkline})))))))))}function uv({controller:t}){const e=ee(t,sv,Le),s=o.useMemo(()=>ff(t.getState()),[t,e]),n=o.useMemo(()=>t.getState().budget?.grid||[],[t,e]),[r,i]=o.useState([]),[a,l]=o.useState(new Map),[c,d]=o.useState(null),u=o.useCallback(()=>{typeof t.transport.getDefaults=="function"&&Promise.resolve(t.transport.getDefaults()).then(L=>d(L||null)).catch(()=>{})},[t]);o.useEffect(()=>{let L=!0;return typeof t.transport.listModels=="function"&&Promise.resolve(t.transport.listModels()).then(I=>{L&&i(KS(I))}).catch(()=>{}),typeof t.transport.listProviders=="function"&&Promise.resolve(t.transport.listProviders()).then(I=>{if(!L)return;const C=new Map;for(const U of I?.providers||[])C.set(U.name,U.typeId||"");l(C)}).catch(()=>{}),u(),()=>{L=!1}},[t,u]),o.useEffect(()=>{const L=t.getState().budget||{};!L.loaded&&!L.loading&&!L.error&&t.loadProviderTable().catch(()=>{})},[t]),o.useEffect(()=>{const L=setInterval(()=>{t.refreshProviderTable().catch(()=>{})},6e4);return()=>clearInterval(L)},[t]),o.useEffect(()=>{const L=I=>{if(I.key!=="Escape")return;const C=I.target,U=C&&C.tagName;U==="SELECT"||U==="INPUT"||U==="TEXTAREA"||t.getState().ui.modal||document.querySelector(".ps-budget-sheet")||(I.preventDefault(),I.stopPropagation(),t.closeBudget())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[t]);const[p,m]=o.useState(null),[f,h]=o.useState(!1),[g,b]=o.useState(null),y=o.useRef(null),S=L=>{y.current=typeof document<"u"?document.activeElement:null,b(null),h(!1),m(L)},w=o.useCallback(()=>{m(null),b(null),h(!1);const L=y.current;y.current=null,L&&typeof L.focus=="function"&&document.contains(L)&&L.focus()},[]),k=async(L,{keepOpen:I=!1,onDone:C=null}={})=>{h(!0),b(null);const U=await L();if(h(!1),!U||U.ok!==!0){b(U?.error||"The change was refused.");return}I||w(),C&&C(U.result||null)},E=L=>t.dispatch({type:"ui/status",text:L}),x=s.selected,v=s.selectedProviderRow,P=x?qS(r,{name:x.providerName,typeId:a.get(x.providerName)||""}):[];let N=null;p?.kind==="edit"&&v&&(N=o.createElement(ev,{row:v,rawRows:n,models:P,isAdmin:s.isAdmin,initialPeriod:p.period||"day",initialScope:p.scope||"*",busy:f,error:g,onCancel:w,onRun:(L,I)=>{const C=x.providerName;if(L==="limit")return k(()=>t.setProviderLimit({provider:C,...I}),{onDone:U=>{const B=Number(U?.seededTokens)||0;E(B>0?`Limit saved. This period had already spent ${J(B)} tokens, and they count against it.`:"Limit saved. This period has spent nothing against it yet.")}});if(L==="removeLimit")return k(()=>t.removeProviderLimit({provider:C,...I}),{onDone:()=>E(`That period no longer caps ${C}.`)});if(L==="allowance")return k(()=>t.setProviderAllowance({provider:C,pct:I.pct}),{onDone:()=>E(I.pct>=100?`Everyone shares the whole of ${C} again.`:`Each person may now use up to ${I.pct}% of each of ${C}'s limits.`)});if(L==="hold")return k(()=>t.setProviderHold({provider:C,...I}),{onDone:()=>{if(I.release){E(`The hold on ${C} is released. Sessions waiting on it wake up.`);return}const U=(t.getState().budget?.grid||[]).find(V=>V.providerName===C&&V.rowKind!=="model"),B=U?.holdIndefinite===!0||(U?.holdUntilUtc?Date.parse(U.holdUntilUtc)>Date.now():!1);E(B?`${C} is on hold. No new turn runs against it until it is released.`:`${C} is NOT on hold: the time given has already passed.`)}})}}));const _=o.createElement("div",{className:"ps-budget-head"},o.createElement("div",{className:"ps-budget-headline"},o.createElement("span",{className:"ps-budget-coin","aria-hidden":"true"},"◎"),o.createElement("h2",{className:"ps-budget-h"},"Providers & Budgets"),o.createElement("span",{className:"ps-budget-sub"},"Usage and limits")),o.createElement("div",{className:"ps-budget-head-actions"},o.createElement(he,{icon:"↻",label:"Refresh providers and budgets",className:"ps-mini-button",disabled:s.loading||s.refreshing,onClick:()=>t.refreshProviderTable().catch(()=>{})})));let D;return s.failed?D=o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"Providers and budgets could not be read. ",o.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>t.loadProviderTable().catch(()=>{})},"Try again")),o.createElement("div",{className:"ps-budget-sub"},s.error)):s.loading&&!s.loaded?D=o.createElement("div",{className:"ps-budget-empty"},"Reading providers and budgets…"):D=o.createElement(o.Fragment,null,s.stale?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"These figures are from an earlier read. The most recent read failed."),o.createElement("div",{className:"ps-budget-sub"},s.error)):null,s.paused.count>0?o.createElement("div",{className:`ps-budget-waiting${s.paused.stale?" is-stale":""}`,role:"status"},s.paused.sentence," ",s.paused.provider?o.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>{s.selectedProvider!==s.paused.provider&&t.selectBudgetProvider(s.paused.provider).catch(()=>{})}},`Open ${s.paused.provider}`):null,s.paused.stale?o.createElement("span",{className:"ps-budget-sub"}," This line is from an earlier read — the last one failed."):null):null,s.paused.count===0&&s.paused.error?o.createElement("div",{className:"ps-budget-waiting is-stale",role:"status"},"The list of waiting sessions could not be read. The figures below were read successfully."):null,s.missing?o.createElement("div",{className:"ps-budget-waiting is-missing",role:"status"},s.missing.sentence," ",o.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>{t.closeBudget(),t.openAdminConsole()}},"Open Model Providers")):null,o.createElement("div",{className:`ps-budget-body${s.refreshing?" is-refreshing":""}`},o.createElement(QS,{controller:t,view:s,defaults:c}),o.createElement("div",{className:"ps-budget-actions"},o.createElement(he,{icon:o.createElement(bd),label:"Edit usage policy",className:"ps-mini-button",disabled:!v||!v.manageable,onClick:()=>S({kind:"edit",scope:x?.kind==="model"?x.scope:"*"})}),o.createElement("span",{className:"ps-budget-sub"},x?x.providerName:"No provider selected")),o.createElement("div",{className:"ps-budget-foot ps-budget-sub"},"Manage providers and defaults in Admin Console."),x?o.createElement(ZS,{controller:t,view:s}):null,x?o.createElement(JS,{view:s}):null)),o.createElement("div",{className:"ps-budget-surface"},_,o.createElement("div",{className:"ps-budget-tabs",role:"tablist"},[["providers","Providers"],["summary","Cluster summary"]].map(([L,I])=>o.createElement("button",{key:L,type:"button",role:"tab","aria-selected":(t.getState().budget?.tab||"providers")===L,className:`ps-budget-tab${(t.getState().budget?.tab||"providers")===L?" is-on":""}`,onClick:()=>t.setBudgetTab(L)},I))),(t.getState().budget?.tab||"providers")==="summary"?o.createElement("div",{className:"ps-budget"},o.createElement(dv,{controller:t})):o.createElement("div",{className:"ps-budget"},D),N)}function pv({controller:t}){const e=ee(t,y=>y.ui.themeId),s=ee(t,y=>!!y.ui.touchScale),n=ft(e),r=ee(t,y=>({rawModal:y.ui.modal,themePicker:Sh(y),modelPicker:zf(y),reasoningEffortPicker:Kf(y),contextTierPicker:Vf(y),sessionAgentPicker:qf(y),sessionGroupPicker:Yf(y),sessionGroupName:Qf(y),artifactPicker:sh(y),logFilter:eh(y),filesFilter:th(y),historyFormat:bh(y),renameSession:Xf(y),sessionOwnerFilter:Jf(y),artifactUpload:Zf(y),confirm:vh(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),Le),i=r.rawModal,a=o.useRef(null),l=o.useRef(null),c=o.useRef(null),[d,u]=o.useState(""),p=i?.type==="sessionOwnerFilter";if(o.useEffect(()=>{p||u("")},[p]),o.useEffect(()=>{if(i?.type!=="renameSession"||!r.renameSession)return;const y=a.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(r.renameSession.cursorIndex,r.renameSession.cursorIndex)}},[i?.type,r.renameSession?.cursorIndex,r.renameSession?.value]),o.useEffect(()=>{if(i?.type!=="sessionGroupName"||!r.sessionGroupName)return;const y=l.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(r.sessionGroupName.cursorIndex,r.sessionGroupName.cursorIndex)}},[i?.type,r.sessionGroupName?.cursorIndex,r.sessionGroupName?.value]),o.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const y=c.current;if(!y)return;const S=y.querySelector(".ps-list-button.is-selected");S&&typeof S.scrollIntoView=="function"&&S.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,r.themePicker?.selectedRowIndex,r.modelPicker?.selectedRowIndex,r.reasoningEffortPicker?.selectedRowIndex,r.contextTierPicker?.selectedRowIndex,r.sessionAgentPicker?.selectedRowIndex,r.sessionGroupPicker?.selectedRowIndex,r.artifactPicker?.selectedRowIndex,r.sessionOwnerFilter?.selectedRowIndex,r.logFilter?.selectedRowIndex,r.filesFilter?.selectedRowIndex,r.historyFormat?.selectedRowIndex]),!i)return null;const m=()=>t.handleCommand(M.CLOSE_MODAL).catch(()=>{}),f=()=>o.createElement("label",{className:"ps-modal-toggle",title:"Larger type and bigger hit targets, for phones and touch screens."},o.createElement("input",{type:"checkbox",checked:s,onChange:y=>t.dispatch({type:"ui/touchScale",enabled:y.target.checked})}),o.createElement("span",null,"Mobile")),h=(y,S="Apply",w=null,k=null)=>{const E=Array.isArray(y.rows)?y.rows:[],x=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,v=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",P=x&&x.length===E.length?E.map((N,_)=>{const D=x[_],L=Array.isArray(N)?N:je([N])[0]?.runs||[{text:N?.text||"",color:N?.color}];if(D==null||D<0)return o.createElement("div",{key:`row:${_}`,className:"ps-line ps-modal-list-heading-line"},o.createElement(ze,{runs:L,theme:n}));const I=i.items?.[D];return o.createElement("button",{key:I?.id||`row:${_}`,type:"button",className:`ps-list-button ps-modal-list-button${D===i.selectedIndex?" is-selected":""}${v?" is-hanging":""}${I?.disabled?" is-disabled":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:D})}},o.createElement("div",{className:"ps-line ps-modal-list-line"},o.createElement(ze,{runs:L,theme:n})))}):(i.items||[]).flatMap((N,_,D)=>{const L=o.createElement("button",{key:N.id||_,type:"button",className:`ps-list-button ps-modal-list-button${_===i.selectedIndex?" is-selected":""}${v?" is-hanging":""}${N?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:_})},o.createElement("div",{className:"ps-line ps-modal-list-line"},o.createElement(ze,{runs:Array.isArray(E?.[_])?E[_]:je([E?.[_]])[0]?.runs||[{text:E?.[_]?.text||"",color:E?.[_]?.color}],theme:n})));return N?.group&&N.group!==D[_-1]?.group?[o.createElement("div",{key:`group:${N.group}`,className:"ps-modal-list-group","aria-hidden":"true"},N.group),L]:[L]});return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:`ps-modal is-list${i.type==="themePicker"?" is-theme-picker":""}`,onClick:N=>N.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},y.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),k,o.createElement("div",{className:"ps-modal-grid"},o.createElement("div",{ref:c,className:"ps-modal-list"},P),o.createElement("div",{className:"ps-modal-details"},o.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),je(y.detailsLines||[]).map((N,_)=>o.createElement(We,{key:`detail:${_}`,line:N,theme:n,className:"ps-modal-detail-line"})))),o.createElement("div",{className:"ps-modal-footer"},w,o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},S))))};if(i.type==="confirm"&&r.confirm){const y=!!i.alert,S=!y&&i.action==="deleteSession",w=i.action==="regenerateSession",k=i.extras||{};return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:E=>E.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.confirm.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},o.createElement("p",{style:{color:"#94a3b8",margin:0}},r.confirm.message)),w?o.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},o.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",o.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:k.distillMode||"llm",onChange:E=>t.updateConfirmExtras({distillMode:E.currentTarget.value})},o.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),o.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(k.distillMode||"llm")==="llm"?o.createElement(mv,{controller:t,extras:k}):null,(k.distillMode||"llm")==="llm"?o.createElement("textarea",{className:"ps-modal-input",style:{width:"100%",minHeight:"64px",resize:"vertical",fontFamily:"inherit",fontSize:"13px"},placeholder:'Distilling instructions (optional) — e.g. "preserve every SQL snippet verbatim"',value:k.instructions||"",maxLength:4e3,onChange:E=>t.updateConfirmExtras({instructions:E.currentTarget.value})}):null):null,o.createElement("div",{className:"ps-modal-footer"},y?null:o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:`ps-modal-button ${S?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},r.confirm.confirmLabel))))}if(i.type==="themePicker"&&r.themePicker)return h(r.themePicker,"Apply Theme",f());const g=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&r.modelPicker)return h(r.modelPicker,g);if(i.type==="reasoningEffortPicker"&&r.reasoningEffortPicker)return h(r.reasoningEffortPicker,g);if(i.type==="contextTierPicker"&&r.contextTierPicker)return h(r.contextTierPicker,g);if(i.type==="sessionAgentPicker"&&r.sessionAgentPicker){const y=[["used","Most used","Ordered by how often YOU have started each agent"],["name","Name","Alphabetical by agent name"],["package","Package","Grouped by package name, then agent name"]],S=o.createElement("div",{className:"ps-agent-picker-toolbar"},o.createElement("input",{type:"search",className:"ps-agent-picker-search","data-modal-search":"true",placeholder:"Search agents, packages, tools…",value:i.query||"",autoFocus:!0,"aria-label":"Search agents",onChange:w=>t.setAgentPickerQuery(w.target.value),onKeyDown:w=>{["ArrowUp","ArrowDown","Enter","Escape","Tab"].includes(w.key)||w.stopPropagation()}}),o.createElement("div",{className:"ps-agent-picker-sorts",role:"group","aria-label":"Sort agents"},y.map(([w,k,E])=>o.createElement("button",{key:w,type:"button",className:`ps-agent-picker-sort${(i.sort||"used")===w?" is-on":""}`,title:E,"aria-pressed":(i.sort||"used")===w?"true":"false",onClick:()=>t.setAgentPickerSort(w)},k))));return h(r.sessionAgentPicker,"Create Session",null,S)}if(i.type==="sessionGroupPicker"&&r.sessionGroupPicker)return h(r.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&r.artifactPicker)return h(r.artifactPicker,r.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&r.sessionOwnerFilter){const y=r.sessionOwnerFilter,S=Array.isArray(y.rows)?y.rows:[],w=d.trim().toLowerCase(),k=x=>{const v=S?.[x];return(Array.isArray(v)?v:je([v])[0]?.runs||[]).map(N=>N?.text||"").join("")||String(v?.text||"")},E=(i.items||[]).map((x,v)=>v).filter(x=>{if(!w)return!0;const v=(i.items||[])[x]||{};return`${k(x)} ${v.label||""} ${v.description||""}`.toLowerCase().includes(w)});return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-list",onClick:x=>x.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},y.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{className:"ps-modal-input ps-modal-search","data-modal-search":"true",value:d,placeholder:"Search people…",autoFocus:!0,onChange:x=>u(x.currentTarget.value),onKeyDown:x=>{x.key==="Escape"&&d&&(x.stopPropagation(),u(""))}}),o.createElement("div",{className:"ps-modal-grid"},o.createElement("div",{ref:c,className:"ps-modal-list"},E.length===0?o.createElement("div",{className:"ps-empty-state"},`No one matches "${d}".`):null,E.map(x=>(v=>o.createElement("button",{key:v.id||x,type:"button",className:`ps-list-button ps-modal-list-button${x===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(x)},o.createElement("div",{className:"ps-line ps-modal-list-line"},o.createElement(ze,{runs:Array.isArray(S?.[x])?S[x]:je([S?.[x]])[0]?.runs||[{text:S?.[x]?.text||"",color:S?.[x]?.color}],theme:n}))))((i.items||[])[x]||{}))),o.createElement("div",{className:"ps-modal-details"},o.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),je(y.detailsLines||[]).map((x,v)=>o.createElement(We,{key:`detail:${v}`,line:x,theme:n,className:"ps-modal-detail-line"})))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:m},"Done"))))}if(i.type==="renameSession"&&r.renameSession)return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.renameSession.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{ref:a,className:"ps-modal-input",value:r.renameSession.value,placeholder:r.renameSession.placeholder,onChange:y=>t.setRenameSessionValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),o.createElement("div",{className:"ps-modal-details"},je(r.renameSession.helpLines||[]).map((y,S)=>o.createElement(We,{key:`help:${S}`,line:y,theme:n,className:"ps-modal-detail-line"}))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&r.sessionGroupName)return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.sessionGroupName.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{ref:l,className:"ps-modal-input",value:r.sessionGroupName.value,placeholder:r.sessionGroupName.placeholder,onChange:y=>t.setSessionGroupNameValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),o.createElement("div",{className:"ps-modal-details"},je(r.sessionGroupName.helpLines||[]).map((y,S)=>o.createElement(We,{key:`help:${S}`,line:y,theme:n,className:"ps-modal-detail-line"}))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},r.sessionGroupName.mode==="rename"?"Rename":"Create and Move"))));if(i.type==="terminatePicker"){const y=Number(i.bulkCount)>1,S=!!i.systemRestart,w=String(i.sessionTitle||"").trim()||"this session",k=Number(i.bulkCount)||0,E=y?`What should happen to the ${k} selected sessions? Choose an action; you'll be asked to confirm.`:S?`How should "${w}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${w}"? Choose an action; you'll be asked to confirm.`,x=v=>()=>{t.pickTerminateAction(v).catch(()=>{})};return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:v=>v.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},o.createElement("p",{style:{color:"#94a3b8",margin:0}},E)),o.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.canRegenerate?o.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},title:"Archive and distill the transcript, then rebuild context fresh at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved.",onClick:x("regenerate")},"Regenerate Context"):null,o.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:x("complete")},y?`Mark ${k} Completed`:S?"Complete & Restart":"Mark Completed"),o.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:x("cancel")},y?`Cancel ${k} Sessions`:S?"Terminate & Restart":"Cancel Session"),o.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:x("delete")},y?`Hard Delete ${k} Sessions`:S?"Hard Delete & Restart":"Delete Session")),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Close"))))}if(i.type==="artifactUpload"&&r.artifactUpload)return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.artifactUpload.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{className:"ps-modal-input",value:r.artifactUpload.value,placeholder:r.artifactUpload.placeholder,onChange:y=>t.setArtifactUploadValue(y.currentTarget.value,y.currentTarget.selectionStart||y.currentTarget.value.length),autoFocus:!0}),o.createElement("div",{className:"ps-modal-details"},je(r.artifactUpload.helpLines||[]).map((y,S)=>o.createElement(We,{key:`help:${S}`,line:y,theme:n,className:"ps-modal-detail-line"}))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const b=i.type==="logFilter"?r.logFilter:i.type==="filesFilter"?r.filesFilter:i.type==="historyFormat"?r.historyFormat:null;return b?o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-wide",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},b.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((y,S)=>{const w=i.type==="filesFilter"?r.filesFilterState?.[y.id]||y.options?.[0]?.id:i.type==="historyFormat"?r.historyFormatState:r.logsFilter?.[y.id]||y.options?.[0]?.id;return o.createElement("div",{key:y.id||S,className:"ps-filter-column"},o.createElement("div",{className:"ps-filter-title"},y.label),(y.options||[]).map(k=>o.createElement("button",{key:k.id,type:"button",className:`ps-filter-option${k.id===w?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:S}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:k.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[y.id]:k.id}}),t.ensureFilesForScope(k.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[y.id]:k.id}})}},k.label)))})),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:m},"Done")))):null}function mv({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(d=>d.qualifiedName===e.distillerModel)||null,r=n?.supportedReasoningEfforts||[],i=n?.supportedContextTiers||[],a={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},l={flex:"1",padding:"4px 8px"},c=d=>t.updateConfirmExtras(d);return o.createElement(o.Fragment,null,o.createElement("label",{style:a},"Distiller model",o.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerModel||"",onChange:d=>c({distillerModel:d.currentTarget.value,distillerEffort:"",distillerContextTier:""})},o.createElement("option",{value:""},"Deployment default"),s.map(d=>o.createElement("option",{key:d.qualifiedName,value:d.qualifiedName},d.qualifiedName)))),r.length>0?o.createElement("label",{style:a},"Reasoning",o.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerEffort||"",onChange:d=>c({distillerEffort:d.currentTarget.value})},o.createElement("option",{value:""},"Model default"),r.map(d=>o.createElement("option",{key:d,value:d},d)))):null,i.length>0?o.createElement("label",{style:a},"Context",o.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerContextTier||"",onChange:d=>c({distillerContextTier:d.currentTarget.value})},o.createElement("option",{value:""},"Model default"),i.map(d=>o.createElement("option",{key:d,value:d},d==="long_context"?"long context (fits a larger transcript)":d)))):null)}function fv(t,e){o.useEffect(()=>{const s=n=>{const r=n.target,i=r instanceof HTMLElement&&(r.tagName==="TEXTAREA"||r.tagName==="INPUT"||r.tagName==="SELECT"||r.isContentEditable),a=t.getState().ui.modal,l=Mi(t),c=t.getState().ui.inspectorTab,d=t.getState().ui.focusRegion,u=!n.metaKey&&!n.ctrlKey&&!n.altKey,p=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,m=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,f=h=>{const g=wy(l,c,h);t.selectInspectorTab(g).catch(()=>{})};if(!i&&p){n.preventDefault(),t.handleCommand(M.OPEN_THEME_PICKER).catch(()=>{});return}if(!i&&m){n.preventDefault(),t.handleCommand(M.OPEN_MODEL_PICKER).catch(()=>{});return}if(a&&!i){if(n.key==="Escape"||a.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(M.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||a.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(M.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(M.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(M.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(M.MODAL_NEXT).catch(()=>{}));return}if(a&&i&&r instanceof HTMLElement&&r.dataset.modalSearch==="true"){if(n.key==="Escape"){n.preventDefault(),t.handleCommand(M.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"){n.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="ArrowUp"){n.preventDefault(),t.handleCommand(M.MODAL_PREV).catch(()=>{});return}if(n.key==="ArrowDown"){n.preventDefault(),t.handleCommand(M.MODAL_NEXT).catch(()=>{});return}return}if(!i){if(n.key==="r"&&u&&d!=="prompt"){n.preventDefault(),t.handleCommand(M.REFRESH).catch(()=>{});return}if(n.key==="n"&&u){n.preventDefault(),t.handleCommand(M.NEW_SESSION).catch(()=>{});return}if(d==="inspector"&&c==="files"&&(n.key==="u"&&u||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(M.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(M.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="x"&&u){n.preventDefault(),t.handleCommand(M.DELETE_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="o"&&u){n.preventDefault(),t.handleCommand(M.OPEN_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.OPEN_FILES_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="stats"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.TOGGLE_STATS_VIEW).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="v"&&u){n.preventDefault(),t.handleCommand(M.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(M.TOGGLE_LOG_TAIL).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.OPEN_LOG_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="r"&&u){n.preventDefault(),t.handleCommand(M.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(M.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&u){n.preventDefault(),t.handleCommand(M.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&u){n.preventDefault(),t.handleCommand(M.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&u){n.preventDefault(),t.handleCommand(M.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&u){n.preventDefault(),t.handleCommand(M.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(M.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&u&&d==="inspector"){n.preventDefault(),f(1);return}if(n.key==="["&&u){n.preventDefault(),t.handleCommand(M.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&u){n.preventDefault(),t.handleCommand(M.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&u){n.preventDefault(),t.handleCommand(M.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&u){n.preventDefault(),t.handleCommand(M.GROW_SESSION_PANE).catch(()=>{});return}if(d==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),f(-1);return}if(d==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),f(1);return}if(d==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(M.MOVE_SESSION_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(M.MOVE_SESSION_DOWN).catch(()=>{});return}if(d==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(M.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(M.PAGE_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(M.PAGE_DOWN).catch(()=>{});return}if(d==="sessions"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(M.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(M.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(M.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&u){n.preventDefault(),t.handleCommand(M.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(M.SCROLL_BOTTOM).catch(()=>{});return}if(d!=="prompt"&&n.key==="h"&&u){n.preventDefault(),t.handleCommand(M.FOCUS_LEFT).catch(()=>{});return}if(d!=="prompt"&&n.key==="l"&&u){n.preventDefault(),t.handleCommand(M.FOCUS_RIGHT).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(M.MOVE_FILE_UP).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(M.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(M.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(M.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(M.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function hv(t){if(!t)return"Unknown user";const e=String(t.displayName||"").trim(),s=String(t.email||"").trim();if(e&&s&&e.toLowerCase()!==s.toLowerCase())return`${e} <${s}>`;if(e)return e;if(s)return s;const n=String(t.provider||"").trim(),r=String(t.subject||"").trim();return[n,r].filter(Boolean).join(":")||"user"}function gv({controller:t,mobile:e=!1}){const s=ee(t,gt,Le),n=s.packages||{},r=s.section==="packages",i=s.section==="workers",[a,l]=o.useState(null),[c,d]=o.useState(!1),[u,p]=o.useState(null),[m,f]=o.useState(()=>{const N={wsWidth:440,treePct:44,navWidth:240};try{return{...N,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return N}}),h=o.useCallback(N=>{f(_=>{const D={..._,...N};D.wsWidth=Math.min(900,Math.max(300,Math.round(D.wsWidth))),D.treePct=Math.min(85,Math.max(15,D.treePct)),D.navWidth=Math.min(420,Math.max(170,Math.round(D.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(D))}catch{}return D})},[]),g=o.useCallback(N=>{N.preventDefault(),document.body.style.cursor="col-resize";const _=N.clientX,D=m.navWidth??240,L=C=>h({navWidth:D+(C.clientX-_)}),I=()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",I),document.body.style.cursor=""};window.addEventListener("pointermove",L),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",I)},[m.navWidth,h]);o.useCallback(()=>{t.closeAdminConsole()},[t]);const b=o.useCallback(()=>{l(null),d(!1),p(null),t.dismissAdminModelProviderMutationError()},[t]),y=o.useCallback(async N=>{d(!0),p(null);const _=a?.update?await t.updateAdminProviderCredential({name:N.name,credentials:N.credentials,shared:N.shared===!0}):await t.createAdminProvider(N);if(d(!1),!_?.ok){p(_?.error||`The provider key could not be ${a?.update?"updated":"created"}.`);return}b()},[b,t,a]),S=o.createElement("header",{className:"ps-admin-console__header"},o.createElement("h2",null,s.isAdmin?"Admin Console":"Settings")),w=o.createElement(xv,{controller:t,view:s,sheetOpen:!!a,onAddPersonal:()=>{t.dismissAdminModelProviderMutationError(),l({shared:!1,github:!0})},onAddShared:()=>{t.dismissAdminModelProviderMutationError(),l({shared:!0,github:!1})},onUpdatePersonal:N=>{t.dismissAdminModelProviderMutationError(),l({update:N,shared:N.class==="shared"})}}),k=o.createElement(yv,{controller:t,view:s}),E=o.createElement(bv,{controller:t,view:s}),x=r&&n.selectedName?o.createElement(vv,{controller:t,view:s,layout:m,onLayout:h}):null,v=n.addDialog?.open?o.createElement(kv,{controller:t,dialog:n.addDialog}):null,P=a?o.createElement(tv,{types:s.modelProviders?.providerTypes||[],existingNames:[...s.modelProviders?.sharedProviders||[],...s.modelProviders?.myProviders||[]].map(N=>N.name),isAdmin:s.isAdmin,initialShared:a.shared,updateProvider:a.update||null,initialType:a.github?(s.modelProviders?.providerTypes||[]).find(N=>/github/i.test(N.id))?.id||"":a.update?.typeId||"",initialName:a.update?.name||"",busy:c,error:u,onDirty:()=>p(null),onCancel:b,onConfirm:y}):null;if(e){let N;return r&&n.selectedName?N=o.createElement("div",{className:"ps-admin-mobile-stack"},o.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>t.selectAdminPackage(null)},"← All packages"),E,x):r?N=k:i?N=o.createElement("div",{className:"ps-admin-mobile-stack"},k,o.createElement(Za,{controller:t,view:s})):N=o.createElement("div",{className:"ps-admin-mobile-stack"},k,w),o.createElement("div",{className:"ps-admin-console is-mobile"},S,s.loadError?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,N,v,P)}return o.createElement("div",{className:"ps-admin-console is-workspace"},S,s.loadError?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,o.createElement("div",{className:"ps-admin-workspace",style:x?{gridTemplateColumns:`${m.navWidth}px minmax(0, 1fr) minmax(0, ${m.wsWidth}px)`}:{gridTemplateColumns:`${m.navWidth}px minmax(0, 1fr)`}},o.createElement("div",{className:"ps-admin-nav"},k,o.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:g,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),o.createElement("div",{className:"ps-admin-main"},r?E:i?o.createElement(Za,{controller:t,view:s}):w),x),v,P)}function Za({controller:t,view:e}){const s=e.workers||{},n=s.rows||[],r=s.counts||{};return o.useEffect(()=>{const i=window.setInterval(()=>{t.refreshAdminWorkers()},25e3);return()=>window.clearInterval(i)},[t]),o.createElement("div",{className:"ps-admin-detail ps-admin-workers"},o.createElement("div",{className:"ps-admin-workers__head"},o.createElement("h3",null,"Workers"),s.summaryText?o.createElement("span",{className:"ps-admin-workers__summary"},`${s.summaryText}${r.pools>1?` · ${r.pools} pools`:""}${r.draining?` · ${r.draining} draining`:""}`):null,o.createElement("button",{type:"button",className:"ps-mini-button is-icon",onClick:()=>t.refreshAdminWorkers(),disabled:!!s.loading,title:s.loading?"Refreshing…":"Refresh the worker list","aria-label":"Refresh the worker list"},o.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M16.2 8.2A6.4 6.4 0 0 0 4.6 6.4M3.8 11.8a6.4 6.4 0 0 0 11.6 1.8"}),o.createElement("path",{d:"M16.4 3.6v4.6h-4.6M3.6 16.4v-4.6h4.6"})))),s.error?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.error):null,s.empty?o.createElement("p",{className:"ps-admin-console__hint"},"No workers registered. Workers appear here on their first heartbeat and self-prune after an hour of silence."):o.createElement("div",{className:"ps-admin-workers__scroll"},o.createElement("table",{className:"ps-admin-workers__table"},o.createElement("thead",null,o.createElement("tr",null,["Worker","Pool","Phase","Heartbeat","Uptime","RSS","Sessions","Loop p99","Packages","SDK"].map(i=>o.createElement("th",{key:i},i)))),o.createElement("tbody",null,n.map(i=>o.createElement("tr",{key:i.id,className:i.live?"is-live":"is-stale"},o.createElement("td",{className:"ps-admin-workers__id",title:i.owner?`owner: ${i.owner}`:void 0},o.createElement("span",{className:`ps-worker-dot${i.live?" is-live":""}`}),i.id,i.substrate&&i.substrate!=="kubernetes"?o.createElement("span",{className:"ps-admin-workers__substrate"},i.substrate):null),o.createElement("td",null,i.pool),o.createElement("td",null,o.createElement("span",{className:`ps-worker-phase is-${i.phase}`},i.phase)),o.createElement("td",null,i.agoText),o.createElement("td",null,i.uptimeText??"—"),o.createElement("td",null,i.rssText??"—"),o.createElement("td",null,i.sessions??"—"),o.createElement("td",null,i.eventLoopText??"—"),o.createElement("td",{title:i.pkgEpoch!=null?`epoch ${i.pkgEpoch}`:void 0},i.pkgText??"—"),o.createElement("td",null,i.sdkVersion??"—")))))))}function yv({controller:t,view:e}){const s=e.packages||{};return o.createElement("nav",{className:"ps-admin-tree"},o.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(e.settingsTree||[]).map(n=>{if(n.kind==="group")return o.createElement("div",{key:n.id,className:"ps-admin-tree__group"},`${n.label}`,o.createElement("span",{className:"ps-admin-tree__count"},String(n.count??0)));const r=n.kind==="package"?()=>t.selectAdminPackage(n.name,{scope:n.scope==="shared"?"shared":"user",...n.scope!=="shared"&&n.owner?.provider&&n.owner?.subject?{owner:{provider:n.owner.provider,subject:n.owner.subject}}:{}}):()=>{n.id==="providers"||n.id==="myProviders"?(t.setAdminSection("providers"),t.setAdminModelProviderPage("mine")):n.id==="sharedProviders"?(t.setAdminSection("providers"),t.setAdminModelProviderPage("shared")):t.setAdminSection(n.id==="agents"?"packages":"workers")};return o.createElement("button",{key:n.id,type:"button",className:`ps-admin-tree__row depth-${n.depth}${n.selected?" is-selected":""}${n.kind==="package"&&!n.enabled?" is-disabled":""}`,onClick:r},n.kind==="package"?n.ownerBadge?o.createElement(Br,{badge:n.ownerBadge}):o.createElement("span",{className:"ps-scope-badge is-shared",title:"shared with the whole deployment"},"S"):null,o.createElement("span",{className:"ps-admin-tree__name"},n.label),n.kind==="package"&&n.semver?o.createElement("span",{className:"ps-admin-tree__ver"},n.semver):null)}),s.loading?o.createElement("div",{className:"ps-admin-tree__hint"},"Loading packages…"):null,s.error?o.createElement("div",{className:"ps-admin-tree__hint is-error"},s.error):null,e.section==="packages"?o.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>t.openAdminAddPackage()},"+ Add package"):null)}function bv({controller:t,view:e}){const s=e.packages||{},n=s.detail;if(!s.selectedName)return o.createElement("div",{className:"ps-admin-detail is-empty"},o.createElement("h3",null,"Agents"),o.createElement("p",{className:"ps-admin-console__hint"},s.empty?"No agent packages yet. Add one from a GitHub/ADO repo, a tarball URL, or upload a folder — or push from a terminal with `pilotswarm agents push ./my-agents`.":"Select a package from the tree to see its detail, versions, and files."));const r=()=>{window.confirm(`Delete ${n.name}? Every version and its artifacts are removed. Live sessions using its agents will fail on their next turn.`)&&t.runAdminPackageAction("delete")},i=(c,d)=>()=>t.runAdminPackageAction(c,d),a=n.actionPending,l=async()=>{try{await t.transport.saveAgentPackageDownload(n.name,n.activeSemver??null,{scope:n.scope,owner:n.owner??null})}catch(c){window.alert(`Could not download ${n.name}: ${c?.message||c}`)}};return o.createElement("div",{className:"ps-admin-detail"},n.error?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},`Package load failed: ${n.error}`):null,n.loading?o.createElement("p",{className:"ps-admin-console__hint"},"Loading package…"):null,o.createElement("div",{className:"ps-admin-detail__head"},o.createElement("h3",null,n.name),o.createElement("span",{className:`ps-scope-badge is-${n.scope}`},n.scope),n.enabled?null:o.createElement("span",{className:"ps-scope-badge is-off"},"disabled")),n.description?o.createElement("p",{className:"ps-admin-detail__desc"},n.description):null,o.createElement("dl",{className:"ps-admin-detail__meta"},o.createElement("dt",null,"Version"),o.createElement("dd",null,n.activeSemver?`${n.activeSemver} · sha ${n.activeSha12||"?"} · ${n.sizeText}`:"no active version"),n.fleet?[o.createElement("dt",{key:"fk"},"Fleet"),o.createElement("dd",{key:"fv",className:"is-ok"},n.fleet.text)]:null,o.createElement("dt",null,"Created"),o.createElement("dd",null,`${n.createdBy||"unknown"} · ${n.createdAtText}`)),n.agents.length?o.createElement("div",null,o.createElement("div",{className:"ps-admin-detail__label"},"Agents in this package"),o.createElement("div",{className:"ps-admin-detail__chips"},n.agents.map(c=>o.createElement("span",{key:c.name,className:"ps-agent-chip",title:c.description},c.name,c.toolCount?o.createElement("i",null,` · ${c.toolCount} tools`):null)))):null,n.versions.length?o.createElement("div",null,o.createElement("div",{className:"ps-admin-detail__label"},"Versions"),o.createElement("div",{className:"ps-admin-versions"},n.versions.map(c=>o.createElement("div",{key:c.semver,className:`ps-admin-version${c.active?" is-active":""}`},o.createElement("b",null,c.semver),o.createElement("span",null,c.sha12),o.createElement("span",null,c.dateText),c.active?o.createElement("span",{className:"is-ok"},"● active"):n.canEdit?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("pin",c.semver),disabled:!!a},"Pin"):null)))):null,n.scope==="shared"?o.createElement(Sv,{controller:t,detail:n,pending:a}):null,n.canEdit?o.createElement("div",{className:"ps-admin-detail__actions"},n.source&&n.canManage?o.createElement("button",{type:"button",className:"ps-primary-button",onClick:i("sync"),disabled:!!a},a==="sync"?"Syncing…":"Sync now"):null,o.createElement("button",{type:"button",className:"ps-primary-button",onClick:()=>t.openAdminUpdatePackage(n.name,n.scope),disabled:!!a,title:`Publish a new version of ${n.name} from a repo folder`},"Update"),n.scope==="user"&&n.hasSharedCounterpart?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("republish",n.activeSemver),disabled:!!a||!n.activeSemver,title:`Publish ${n.name}@${n.activeSemver??"?"} into the existing shared package`},a==="republish"?"Publishing…":`Publish ${n.activeSemver??""} to shared`):n.canManage?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.scope==="shared"?"demote":"promote"),disabled:!!a,title:n.scope==="shared"&&n.editors.length?"Demoting revokes every editor grant":void 0},n.scope==="shared"?"Demote to user":"Promote to shared"):null,n.scope==="shared"&&!n.hasOwnUserCounterpart?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("republish",n.activeSemver),disabled:!!a||!n.activeSemver,title:"Copy the active version into your user scope as a private test bench"},a==="republish"?"Copying…":"Copy to my user scope"):null,typeof t.transport.saveAgentPackageDownload=="function"?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>l(),disabled:!!a||!n.activeSemver,title:`Download ${n.name}@${n.activeSemver??"?"} as the .tgz the CLI would push`},a==="download"?"Downloading…":"Download"):null,o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.enabled?"disable":"enable"),disabled:!!a},n.enabled?"Disable":"Enable"),n.canManage?o.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:r,disabled:!!a},"Delete"):null):o.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator, a granted editor, or an admin can modify it."),n.actionError?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function Sv({controller:t,detail:e,pending:s}){const[n,r]=o.useState(""),[i,a]=o.useState([]);o.useEffect(()=>{if(!e.canManage||typeof t.transport.listKnownUsers!="function")return;let m=!1;return t.transport.listKnownUsers({limit:500}).then(f=>{m||a(Array.isArray(f)?f:[])}).catch(()=>{}),()=>{m=!0}},[t,e.canManage]);const l=new Set(e.editors.map(m=>`${m.provider}${m.subject}`)),c=n.trim().toLowerCase(),d=c?i.filter(m=>!l.has(`${m.provider}${m.subject}`)&&(m.displayName&&m.displayName.toLowerCase().includes(c)||m.email&&m.email.toLowerCase().includes(c)||m.subject&&m.subject.toLowerCase().includes(c))).slice(0,8):[],u=m=>{!m?.provider||!m?.subject||(r(""),t.runAdminPackageAction("grantEditor",{provider:m.provider,subject:m.subject}))},p=()=>{const m=n.trim();if(!m)return;const f=i.find(h=>h.displayName&&h.displayName.toLowerCase()===m.toLowerCase()||h.email&&h.email.toLowerCase()===m.toLowerCase()||h.subject&&h.subject.toLowerCase()===m.toLowerCase());if(f)return u(f);if(d.length===1)return u(d[0])};return o.createElement("div",{className:"ps-admin-editors"},o.createElement("div",{className:"ps-admin-detail__label"},"Editors"),e.editors.length?o.createElement("div",{className:"ps-admin-detail__chips"},e.editors.map(m=>o.createElement("span",{key:`${m.provider}${m.subject}`,className:"ps-agent-chip",title:`${m.provider}:${m.subject}${m.grantedByDisplay?` · granted by ${m.grantedByDisplay}`:""}`},m.label,e.canManage?o.createElement("button",{type:"button",className:"ps-chip-remove","aria-label":`Remove editor ${m.label}`,disabled:!!s,onClick:()=>t.runAdminPackageAction("revokeEditor",{provider:m.provider,subject:m.subject})},"×"):null))):o.createElement("p",{className:"ps-admin-console__hint"},e.canManage?"No editors yet. Add a person to let them publish, pin and enable this package. Grants are revoked if the package is demoted.":"Only the owner and admins can change this package."),e.canManage?o.createElement("div",{className:"ps-admin-editors__add"},o.createElement("input",{type:"text",className:"ps-input",placeholder:"Add editor by name, email, or id…",value:n,disabled:!!s,onChange:m=>r(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),p())},"aria-label":"Add editor"}),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:p,disabled:!!s||!n.trim()},"Add"),d.length?o.createElement("div",{className:"ps-admin-editors__suggestions",role:"listbox"},d.map(m=>o.createElement("button",{key:`${m.provider}${m.subject}`,type:"button",role:"option",className:"ps-admin-editors__suggestion",onClick:()=>u(m)},m.displayName||m.email||m.subject,m.email&&m.displayName?o.createElement("i",null,` ${m.email}`):null))):null):null)}function vv({controller:t,view:e,layout:s=null,onLayout:n=null}){const r=ee(t,p=>p.ui.themeId),i=ft(r),a=e.packages?.workspace,l=o.useRef(null),c=o.useCallback((p,m)=>{if(!n)return;p.preventDefault();const f=p.clientX,h=p.clientY,g={...s},b=S=>m(g,S.clientX-f,S.clientY-h),y=()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),document.body.style.cursor=""};window.addEventListener("pointermove",b),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)},[s,n]),d=o.useCallback(p=>{document.body.style.cursor="col-resize",c(p,(m,f)=>n({wsWidth:m.wsWidth-f}))},[c,n]),u=o.useCallback(p=>{document.body.style.cursor="row-resize";const m=l.current?.getBoundingClientRect().height||600;c(p,(f,h,g)=>n({treePct:f.treePct+g/m*100}))},[c,n]);return a?o.createElement("div",{className:"ps-admin-ws",ref:l,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?o.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:d}):null,o.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${a.semver?` · ${e.packages.selectedName}@${a.semver}`:""}`),o.createElement("div",{className:"ps-admin-ws__tree"},a.loading?o.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,a.error?o.createElement("div",{className:"ps-admin-tree__hint is-error"},a.error):null,a.treeRows.map(p=>o.createElement("button",{key:`${p.type}:${p.path}`,type:"button",style:{paddingLeft:`${8+(p.depth||0)*16}px`},className:`ps-admin-ws__row is-${p.type}${p.selected?" is-selected":""}`,onClick:p.type==="dir"?()=>t.toggleAdminPackageDir(p.path):()=>t.selectAdminPackageFile(p.path)},o.createElement("span",{className:"ps-admin-ws__caret"},p.type==="dir"?p.expanded?"▾":"▸":""),o.createElement("span",{className:"ps-admin-ws__name"},p.label),p.sizeText?o.createElement("span",{className:"ps-admin-ws__size"},p.sizeText):null))),o.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?u:void 0},a.selectedPath?`Preview · ${a.selectedPath}`:"Preview"),o.createElement("div",{className:"ps-admin-ws__preview"},a.fileLoading?o.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,a.fileError?o.createElement("div",{className:"ps-admin-tree__hint is-error"},a.fileError):null,a.file?a.file.isBinary?o.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${a.file.sizeText}`):o.createElement(Ev,{file:a.file,theme:i}):null)):null}function wv(t){const e=/^---\n([\s\S]*?)\n---\n?/.exec(t||"");if(!e)return{meta:null,body:t||""};const s=e[1].split(`
|
|
97
|
-
`).map(n=>/^([A-Za-z0-9_-]+):\s*(.*)$/.exec(n)).filter(Boolean).map(([,n,r])=>({key:n,value:r}));return s.length===0?{meta:null,body:t||""}:{meta:s,body:(t||"").slice(e[0].length)}}function Ev({file:t,theme:e}){const s=t.language||"text",n=t.truncated?o.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:r,body:i}=wv(t.text||"");return o.createElement("div",{className:"ps-admin-ws__doc"},r?o.createElement("div",{className:"ps-admin-ws__frontmatter"},r.map(a=>o.createElement("div",{key:a.key,className:"ps-admin-ws__fm-row"},o.createElement("span",{className:"ps-admin-ws__fm-key"},a.key),o.createElement("span",{className:"ps-admin-ws__fm-val"},a.value)))):null,o.createElement(Bi,{content:i,theme:e}),n)}if(s==="json"){let r=t.text||"";if(!t.truncated)try{r=JSON.stringify(JSON.parse(r),null,2)}catch{}return o.createElement("div",{className:"ps-admin-ws__doc"},o.createElement("pre",{className:"ps-admin-ws__code lang-json"},o.createElement("code",null,us(r,"json",e))),n)}return o.createElement("div",{className:"ps-admin-ws__doc"},o.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},o.createElement("code",null,us(t.text||"",s,e))),n)}function kv({controller:t,dialog:e}){const s=ee(t,p=>p.docs?.agentPackageGuideUrl||null),n=p=>m=>t.setAdminAddPackageField(p,m.target.value),r=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],i=e.kind==="repo"||e.kind==="github"||e.kind==="ado",a=o.useRef(null),[l,c]=o.useState(!1),d=2*1024*1024,u=p=>{if(p.preventDefault(),!(l||e.submitting)){if(e.kind==="upload"){const m=a.current;if(!m?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const f=[...m.files].map(g=>({file:g,path:g.webkitRelativePath.split("/").slice(1).join("/")||g.name})).filter(({path:g})=>g&&!g.split("/").includes("node_modules")&&!g.split("/").includes(".git")),h=f.reduce((g,{file:b})=>g+b.size,0);if(f.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(h>d){t.failAdminAddPackage(`Folder is ${(h/(1024*1024)).toFixed(1)} MB after filtering — the upload envelope is 2 MB. Use a repo/URL source or 'pilotswarm agents push' for larger packages.`);return}c(!0),Promise.all(f.map(({file:g,path:b})=>new Promise((y,S)=>{const w=new FileReader;w.onerror=()=>S(new Error(`could not read ${b}`)),w.onload=()=>y({path:b,contentBase64:String(w.result).split(",",2)[1]||""}),w.readAsDataURL(g)}))).then(g=>t.submitAdminUploadPackage(g,e.scope)).catch(g=>t.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return o.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},o.createElement("form",{className:"ps-modal ps-admin-add",onClick:p=>p.stopPropagation(),autoComplete:"off",onSubmit:u},o.createElement("div",{className:"ps-modal-header"},o.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),o.createElement("div",{className:"ps-admin-add__body"},o.createElement("div",{className:"ps-admin-add__tabs"},r.map(([p,m])=>o.createElement("button",{key:p,type:"button",className:`ps-admin-add__tab${e.kind===p?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",p)},m))),i?[o.createElement("label",{key:"u",className:"ps-admin-add__field"},"Link to plugin.json (or the folder containing it)",o.createElement("input",{value:e.repoUrl,onChange:n("repoUrl"),placeholder:"https://github.com/org/repo/blob/main/my-agents/plugin.json",autoFocus:!0,type:"url",name:"agent-package-link",autoComplete:"off",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"})),o.createElement("div",{key:"h",className:"ps-admin-add__hint"},"Paste the browser URL — branch and path are read from the link. The files are read by THIS BROWSER with your access (public GitHub needs nothing; Azure DevOps uses your signed-in account) and uploaded as a package artifact."),o.createElement("label",{key:"t",className:"ps-admin-add__field"},"PAT (only for private GitHub repos, or to override — used here, never stored)",o.createElement("input",{type:"password",value:e.authToken,onChange:n("authToken"),name:"agent-package-pat",autoComplete:"new-password","data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"}))]:o.createElement("label",{className:"ps-admin-add__field"},"Package folder with plugin.json — the manifest (≤ 2 MB; node_modules skipped)",o.createElement("input",{ref:a,type:"file",webkitdirectory:"",directory:"",multiple:!0})),o.createElement("div",{className:"ps-admin-add__scope"},o.createElement("label",null,o.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="shared",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),o.createElement("label",null,o.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="user",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","user")})," User — only you see it")),e.updateName?o.createElement("p",{className:"ps-admin-console__hint"},`Publishes a new version of ${e.updateName}. Its scope is unchanged — use Demote/Promote on the package to move it.`):null,s?o.createElement("p",{className:"ps-admin-console__hint"},"New to this? ",o.createElement("a",{href:s,target:"_blank",rel:"noreferrer noopener"},"How to build an agent package")," — a complete guide you can also hand straight to Claude or Copilot."):null,o.createElement("p",{className:"ps-admin-console__hint"},"Same thing from a terminal: pilotswarm agents push ./my-agents --shared"),e.progress&&!e.error?o.createElement("p",{className:"ps-admin-add__progress"},e.progress):null,e.error?o.createElement("pre",{className:"ps-admin-add__error",role:"alert"},e.error):null),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage(),disabled:e.submitting},"Cancel"),o.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.submitting||l},l?"Reading folder…":e.submitting?"Importing…":e.updateName?"Import & update":"Import & publish"))))}function Sr(t){return t?.configured?.model||""}function vr({label:t,hint:e,value:s,choices:n,disabled:r,emptyLabel:i,onChange:a}){return o.createElement("label",{className:"ps-admin-provider-default"},o.createElement("span",{className:"ps-admin-detail__label"},t),o.createElement("select",{className:"ps-budget-input",value:s,disabled:r,"aria-label":t,onChange:l=>a(l.target.value)},o.createElement("option",{value:""},i),s&&!n.some(l=>l.qualifiedName===s)?o.createElement("option",{value:s},`${s} (currently configured)`):null,n.map(l=>o.createElement("option",{key:l.qualifiedName,value:l.qualifiedName},`${l.provider} · ${l.model}`))),e?o.createElement("span",{className:"ps-admin-console__hint"},e):null)}function Ja({providers:t,isAdmin:e,personal:s,busy:n,onSystemUse:r,onUpdate:i,onDelete:a}){return t.length?o.createElement("div",{className:"ps-admin-provider-list"},t.map(l=>o.createElement("div",{key:l.name,className:"ps-admin-provider-row"},o.createElement("div",{className:"ps-admin-provider-row__identity"},o.createElement("strong",{title:l.name},l.name),o.createElement("span",{className:`ps-scope-badge is-${l.class==="shared"?"shared":"user"}`},l.class),l.isMyDefault?o.createElement("span",{className:"ps-scope-badge is-off"},"my default"):null,l.isClusterDefault?o.createElement("span",{className:"ps-scope-badge is-off"},"cluster default"):null,l.isSystemDefault?o.createElement("span",{className:"ps-scope-badge is-off"},"system default"):null),o.createElement("div",{className:"ps-admin-provider-row__actions"},s&&e?o.createElement("label",{className:"ps-admin-console__system-toggle"},o.createElement("input",{type:"checkbox",checked:l.systemUseEnabled,disabled:n,onChange:c=>r(l.name,c.target.checked)}),"Allow system sessions"):null,(s||e)&&!l.usesWorkloadIdentity?o.createElement("button",{type:"button",className:"ps-mini-button","aria-label":`Update key for ${l.name}`,title:`Update key for ${l.name}`,disabled:n,onClick:()=>i(l)},"Update key"):null,o.createElement(he,{icon:o.createElement(Jb),label:`Delete ${l.name}`,className:"ps-mini-button is-danger",disabled:n,onClick:()=>a(l)}))))):o.createElement("p",{className:"ps-admin-console__hint"},s?"No personal providers yet.":"No shared providers are configured.")}function xv({controller:t,view:e,onAddPersonal:s,onAddShared:n,onUpdatePersonal:r,sheetOpen:i=!1}){const a=e.modelProviders||{},l=!!a.mutation?.pending,c=Sr(a.systemSessionDefault),[d,u]=o.useState(c),[p,m]=o.useState(""),[f,h]=o.useState(null);o.useEffect(()=>{u(c)},[c]);const g=(P,N)=>P.find(_=>_.qualifiedName===N)||null,b=(P,N,_)=>{t.setAdminModelDefault(P,g(N,_))},y=P=>{window.confirm(`Delete ${P.name}? Sessions using it will wait until that provider name exists again.`)&&t.deleteAdminProvider(P.name,{shared:P.class==="shared"})},S=async()=>{h(null);const P=await t.setAdminSystemModelDefault(g(a.systemChoices||[],d),{restartDisposition:p||null});P?.ok&&h(P.result?.restart||{requested:!1})},w=(a.systemAgentRoutes||[]).filter(P=>!P.override),k=a.page==="shared"&&e.isAdmin,E=o.createElement("div",{className:"ps-admin-provider-heading"},o.createElement("h3",null,"Model Providers"),o.createElement(he,{icon:"↻",label:"Refresh model providers",className:"ps-mini-button",disabled:a.loading,onClick:()=>t.refreshAdminModelProviders()})),x=o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("div",{className:"ps-admin-provider-block__head"},o.createElement("h4",null,"My Providers"),o.createElement("button",{type:"button",className:"ps-primary-button",onClick:s,disabled:l},"Add provider")),o.createElement(Ja,{providers:a.myProviders||[],isAdmin:e.isAdmin,personal:!0,busy:l,onSystemUse:(P,N)=>t.setAdminProviderSystemUse(P,N),onUpdate:r,onDelete:y})),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement(vr,{label:"My Session Default",hint:`Effective: ${a.mySessionDefault?.effective?.model||"none"}.`,value:Sr(a.mySessionDefault),choices:a.userChoices||[],disabled:l,emptyLabel:"Use cluster default",onChange:P=>b("user",a.userChoices||[],P)}))),v=o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("div",{className:"ps-admin-provider-block__head"},o.createElement("h4",null,"Shared Providers"),o.createElement("button",{type:"button",className:"ps-primary-button",onClick:n,disabled:l},"Add provider")),o.createElement(Ja,{providers:a.sharedProviders||[],isAdmin:!0,personal:!1,busy:l,onSystemUse:()=>{},onDelete:y,onUpdate:r})),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement(vr,{label:"Cluster Session Default",hint:`Effective: ${a.clusterSessionDefault?.effective?.model||"none"}.`,value:Sr(a.clusterSessionDefault),choices:a.clusterChoices||[],disabled:l,emptyLabel:"Use first shared provider",onChange:P=>b("cluster",a.clusterChoices||[],P)})),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("h4",null,"System Session Default"),o.createElement(vr,{label:"Model",hint:"Shared and system-enabled personal providers.",value:d,choices:a.systemChoices||[],disabled:l,emptyLabel:"Use first eligible provider",onChange:u}),o.createElement("div",{className:"ps-admin-detail__label"},"Existing system sessions"),o.createElement($t,{value:p,onChange:m,label:"Existing system sessions",options:[{value:"",label:"Future only"},{value:"complete",label:"Complete & restart"},{value:"terminate",label:"Terminate & restart"},{value:"hard_delete",label:"Hard delete & restart"}]}),o.createElement("div",{className:"ps-admin-provider-apply"},o.createElement("p",{className:"ps-admin-console__hint"},`${w.length} agent${w.length===1?"":"s"} inherit this default.`),o.createElement("button",{type:"button",className:"ps-primary-button",disabled:l,onClick:S},l&&a.mutation?.pending==="systemDefault"?"Applying…":"Apply")),f?.requested?o.createElement("p",{className:"ps-admin-console__status"},`${f.restarted}/${f.affected} restarted${f.failures?.length?` · ${f.failures.length} failed`:""}.`):null),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("h4",null,"System Agent Overrides"),(a.systemAgentRoutes||[]).length===0?o.createElement("p",{className:"ps-admin-console__hint"},"No system agents."):o.createElement("div",{className:"ps-admin-override-table"},(a.systemAgentRoutes||[]).map(P=>o.createElement("div",{key:P.agentId,className:"ps-admin-override-row"},o.createElement("div",{className:"ps-admin-override-row__agent"},o.createElement("strong",null,P.title),o.createElement("span",null,P.effectiveModel||"blocked"),o.createElement("small",null,P.override?"override":"system default")),o.createElement("select",{className:"ps-budget-input",value:P.override?.model||"",disabled:l,"aria-label":`Model override for ${P.title}`,onChange:N=>{const _=g(a.systemChoices||[],N.target.value);_?t.setAdminSystemAgentModel(P.agentId,_):t.clearAdminSystemAgentModel(P.agentId)}},o.createElement("option",{value:""},"Inherit system default"),(a.systemChoices||[]).map(N=>o.createElement("option",{key:N.qualifiedName,value:N.qualifiedName},`${N.provider} · ${N.model}`))))))));return o.createElement("section",{className:"ps-admin-detail ps-admin-model-providers"},E,a.error||a.mutation?.error&&!i?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},!i&&a.mutation?.error||a.error):null,k?v:x)}function Nv({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){My(),typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;const r=Uh(Hh,Ar({mode:e,branding:s,docs:n}));return new Gg({store:r,transport:t})}function Cv({controller:t}){const e=o.useRef(null),s=o.useRef(null),n=Ia(e),r=Ia(s),i=Hy(n);o.useEffect(()=>{const R=()=>{try{const O=document.createElement("span");O.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const q=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");if(q){const fe=window.getComputedStyle(q);O.style.fontFamily=fe.fontFamily,O.style.fontSize=fe.fontSize,O.style.fontWeight=fe.fontWeight,O.style.letterSpacing=fe.letterSpacing}O.textContent="0".repeat(100),(q?.parentElement||document.body).appendChild(O);const te=O.getBoundingClientRect().width/100||8;O.remove();const se=document.documentElement.clientWidth||window.innerWidth,ue=document.documentElement.clientHeight||window.innerHeight;t.dispatch({type:"ui/viewport",width:Math.floor(se/te),height:Math.floor(ue/bt)})}catch{}};R();let F;const A=()=>{clearTimeout(F),F=setTimeout(R,150)};return window.addEventListener("resize",A),window.addEventListener("orientationchange",A),()=>{clearTimeout(F),window.removeEventListener("resize",A),window.removeEventListener("orientationchange",A)}},[t]);const[a,l]=o.useState("split"),c=ee(t,R=>({themeId:R.ui.themeId,touchScale:!!R.ui.touchScale,sessionDetailCollapsed:!!R.ui.sessionDetailCollapsed,agentPickerUsage:R.ui.agentPickerUsage,ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,manualOrder:R.sessions.manualOrder,collapsedSessionIds:R.sessions.collapsedIds,activeSessionId:R.sessions.activeSessionId||null,promptRows:qc(R),rightPaneMode:R.ui.rightPaneMode||"panes",canvasOpen:R.ui.canvasOpen===!0,diagnosticsOpen:R.ui.diagnosticsOpen===!0,canvasMaximized:R.ui.canvasMaximized===!0,canvasZen:R.ui.canvasZen===!0,canvasPrefs:R.canvas?.prefs,activeSessionIsGroup:!!(R.sessions.activeSessionId&&R.sessions.byId[R.sessions.activeSessionId]?.isGroup),paneAdjust:R.ui.layout?.paneAdjust??0,sessionPaneAdjust:R.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:R.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:R.ui.layout?.activityPaneAdjust??0,canvasPaneAdjust:R.ui.layout?.canvasPaneAdjust??0,diagnosticsPaneAdjust:R.ui.layout?.diagnosticsPaneAdjust??0,diagnosticsSplitAdjust:R.ui.layout?.diagnosticsSplitAdjust??0,focusRegion:R.ui.focusRegion,requestedFocusRegion:R.ui.requestedFocusRegion,inspectorTab:R.ui.inspectorTab,filesFullscreen:!!R.files.fullscreen,selectedArtifactId:R.files.selectedArtifactId||null,artifactPaneOpen:!!R.files.paneOpen,adminVisible:!!R.admin?.visible,budgetOpen:!!R.ui?.budgetOpen}),Le),d=o.useRef(!1),u=o.useRef(null),p=o.useRef(null),m=o.useRef(null),f=o.useRef(null),h=o.useRef(null),g=o.useRef(null),b=o.useRef(!1),y=o.useRef(!1),S=o.useRef(null),w=o.useRef(null),[k,E]=o.useState("workspace"),x=(n.width||window.innerWidth||0)<dy,P=c.activeSessionIsGroup?0:c.promptRows;fv(t,x);const N=AS(x&&k==="workspace"&&!c.adminVisible);o.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-kb-takeover",N),()=>document.body.classList.remove("ps-kb-takeover")},[N]),o.useEffect(()=>{N&&t.applyPaneVisualScrollOffset?.("chat",0,{followBottom:!0})},[N,t]);const _=ee(t,fi,Le),D=k==="canvas",L=o.useRef("workspace"),[I,C]=o.useState(!1),[U,B]=o.useState(!1);o.useEffect(()=>{E(R=>R==="canvas"?L.current||"workspace":R),C(!1),B(!1)},[_.sessionId]),o.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-canvas-lock",!!(x&&D)),()=>document.body.classList.remove("ps-canvas-lock")},[x,D]);const V=o.useCallback(()=>{k!=="canvas"&&(L.current=k),E("canvas"),C(!0),t.dispatch({type:"ui/rightPaneMode",mode:"canvas",sessionId:_.sessionId})},[t,k,_.sessionId]),ce=o.useCallback(()=>{E(L.current||"workspace"),t.dispatch({type:"ui/rightPaneMode",mode:"panes",sessionId:_.sessionId,manual:!0})},[t,_.sessionId]),X=o.useRef(_.flipSeq);o.useEffect(()=>{_.flipSeq!==X.current&&(X.current=_.flipSeq,x&&V())},[_.flipSeq,x,V]);const re=o.useCallback(()=>{if(D){ce();return}V()},[D,ce,V]);o.useEffect(()=>{let R=!0;d.current=!1,u.current=null,S.current=null,w.current=Ea(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),b.current=!1,y.current=!1;const F=t.transport;if(typeof F?.getCurrentUserProfile!="function"||typeof F?.setCurrentUserProfileSettings!="function")return d.current=!0,()=>{R=!1};const A=async()=>{if(!(!R||b.current)){b.current=!0;try{const O=await F.getCurrentUserProfile();if(!R)return;O&&typeof O.isAdmin=="boolean"&&!t.getState().admin?.profile&&t.dispatch({type:"admin/profile/loaded",profile:O});const q=Ft(O?.profileSettings);typeof q[wn()]=="boolean"&&(p.current=q[wn()]),(q.rightPaneMode==="canvas"||q.rightPaneMode==="panes")&&(m.current=q.rightPaneMode),q.desktopPanes&&(f.current=q.desktopPanes),w.current=Ea(t.getState(),p.current,m.current,f.current);const te=Ry(O?.profileSettings,w.current),se=JSON.stringify(te),ue=dr(t.getState(),p.current,m.current,f.current),fe=JSON.stringify(ue),Te=d.current&&u.current!=null&&fe!==u.current,Be=!!h.current||y.current||Te;if(!Be&&S.current!==se&&(t.dispatch({type:"profileSettings/apply",settings:te}),S.current=se),!d.current||!Be){const me=dr(t.getState(),p.current,m.current,f.current);u.current=JSON.stringify(me)}d.current=!0}catch{if(!R)return;d.current=!0}finally{b.current=!1}}};return A().catch(()=>{}),g.current=setInterval(()=>{A().catch(()=>{})},gy),()=>{R=!1,h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),b.current=!1}},[t]),o.useEffect(()=>{if(!d.current)return;const R=dr(c,p.current,m.current,f.current),F=JSON.stringify(R);u.current!==F&&(u.current=F,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,y.current=!0,$y(t,R).catch(()=>{}).finally(()=>{y.current=!1})},400))},[t,c.activeSessionId,c.activityPaneAdjust,c.agentPickerUsage,c.canvasOpen,c.canvasPaneAdjust,c.canvasPrefs,c.canvasZen,c.collapsedSessionIds,c.diagnosticsOpen,c.diagnosticsPaneAdjust,c.diagnosticsSplitAdjust,c.ownerFilter,c.paneAdjust,c.manualOrder,c.pinnedIds,c.portalSessionColumnAdjust,c.rightPaneMode,c.sessionDetailCollapsed,c.sessionPaneAdjust,c.themeId,c.touchScale]),o.useEffect(()=>{By(c.themeId),Dy(c.touchScale)},[c.themeId,c.touchScale]);const T=o.useRef(null);o.useEffect(()=>{const R=T.current;if(T.current=c.focusRegion,R===null||R===c.focusRegion)return;const F=c.requestedFocusRegion;x&&(c.focusRegion==="inspector"||c.focusRegion==="activity")&&(F==="inspector"||F==="activity")&&E(c.focusRegion)},[x,c.focusRegion,c.requestedFocusRegion]),o.useEffect(()=>{const R=Mi(t);!R.includes(c.inspectorTab)&&R.length>0&&t.selectInspectorTab(R[0]).catch(()=>{})},[t,c.inspectorTab]);const j=o.useMemo(()=>Cs(i,c.paneAdjust,P,c.sessionPaneAdjust,c.activityPaneAdjust),[i,c.activityPaneAdjust,c.paneAdjust,P,c.sessionPaneAdjust]),H=c.filesFullscreen&&c.inspectorTab==="files",W=c.inspectorTab==="files"&&!!c.selectedArtifactId&&!H,z=!x&&c.artifactPaneOpen&&!!c.selectedArtifactId&&!H,Q=!x&&c.canvasOpen&&!H;o.useEffect(()=>{Q&&B(!0)},[Q,_.sessionId]);const K=!x&&c.diagnosticsOpen&&!H&&!z&&!(c.canvasZen&&c.canvasOpen),Y=z||Q||K,Z=c.canvasMaximized&&Q,de=c.canvasZen&&Q&&!z,ve=Math.max(260,Math.min(720,Number(c.canvasPrefs?.[c.activeSessionId]?.zenRailPx)||380));o.useEffect(()=>{if(!Z&&!de)return;const R=F=>{F.key==="Escape"&&t.dispatch(Z?{type:"ui/canvasMaximized",on:!1}:{type:"ui/canvasZen",on:!1})};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[t,Z,de]);const le=Math.max(0,_i+(Number(c.canvasPaneAdjust)||0)),st=Math.max(0,Ri+(Number(c.diagnosticsPaneAdjust)||0)),ye=(Q?le:0)+(Q&&K?1:0)+(K?st:0),nt=o.useCallback(()=>{t.closeArtifactPane().catch(()=>{})},[t]),Ce=Math.max(0,(n.width||0)*.68),Oe=r.width||Ce,ut=Ly(Oe,c.portalSessionColumnAdjust),rt=de?"hidden":Oy(ut),G=rt==="hidden"?"0px":`clamp(0px, calc(${Ti*100}% + ${Number(c.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,oe=o.createElement("div",{className:`ps-workspace-grid${Y?"":" is-right-hidden"}`,style:{gridTemplateColumns:z?`minmax(0, ${j.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${j.rightWidth}fr)`:de?`${ve}px var(--ps-resizer-track, 16px) minmax(0, 1fr)`:Y?`minmax(0, 1fr) var(--ps-resizer-track, 16px) min(${ye}px, calc(100% - var(--ps-resizer-track, 16px) - ${Pi}px))`:"minmax(0, 1fr)"}},o.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${rt}`,style:{gridTemplateColumns:`${G} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},rt!=="hidden"?o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},o.createElement(Hr,{controller:t,structuredRows:!0})):null,o.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},o.createElement(OS,{controller:t,portalSessionColumnAdjust:c.portalSessionColumnAdjust})),o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},o.createElement(jr,{controller:t}))),Y?z?o.createElement(LS,{controller:t,paneAdjust:c.paneAdjust}):de?o.createElement(DS,{controller:t,sessionId:c.activeSessionId,railPx:ve}):o.createElement(BS,{controller:t,target:Q?"canvas":"diagnostics",adjust:Q?c.canvasPaneAdjust:c.diagnosticsPaneAdjust}):null,o.createElement("div",{className:`ps-workspace-column-host is-split${Z?" has-maximized":""}`},z?o.createElement("div",{className:"ps-workspace-column is-artifact"},o.createElement(wS,{controller:t,onClose:nt})):null,U?o.createElement("div",{key:`canvas:${c.activeSessionId||""}`,className:`ps-workspace-column is-artifact ps-canvas-layer${Q&&!z?"":" is-hidden"}${Z&&Q&&!z?" is-maximized":""}`,style:Q&&!z&&K&&!Z?{flex:`0 0 ${le}px`,minWidth:0}:void 0,...Q&&!z?{}:{inert:!0,"aria-hidden":"true"}},o.createElement(wd,{controller:t,visible:Q&&!z,maximized:Z})):null,Q&&K?o.createElement(FS,{controller:t,canvasPaneAdjust:c.canvasPaneAdjust,diagnosticsPaneAdjust:c.diagnosticsPaneAdjust}):null,K?o.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`minmax(0px, calc(50% + ${Math.round(Number(c.diagnosticsSplitAdjust)||0)}px)) var(--ps-resizer-track, 16px) minmax(0px, 1fr)`,...Q?{flex:"1 1 0%",minWidth:0}:null}},o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},o.createElement(xs,{controller:t,mobile:!1})),o.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},o.createElement(HS,{controller:t,splitAdjust:c.diagnosticsSplitAdjust})),o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},W?o.createElement(Rn,{controller:t,focused:!1,previewOnly:!0}):o.createElement(yr,{controller:t}))):null)),be=o.createElement("div",{className:"ps-workspace-full"},o.createElement(xs,{controller:t,mobile:!1}));let pe=null;H&&!x?pe=o.createElement("div",{className:"ps-mobile-pane-fill"},o.createElement(xs,{controller:t,mobile:!0})):k==="inspector"?pe=c.inspectorTab==="nodes"?o.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},o.createElement(xs,{controller:t,mobile:!0}),o.createElement(yr,{controller:t,panelClassName:"ps-mobile-node-detail"})):o.createElement("div",{className:"ps-mobile-pane-fill"},o.createElement(xs,{controller:t,mobile:!0})):k==="activity"?pe=o.createElement("div",{className:"ps-mobile-pane-fill"},o.createElement(yr,{controller:t})):k==="canvas"?pe=null:pe=o.createElement(NS,{controller:t,layout:a});const xe=x&&I?o.createElement(ES,{key:`canvas:${_.sessionId||""}`,controller:t,visible:D}):null;return o.createElement(Jc.Provider,{value:t},o.createElement("div",{ref:e,className:"ps-web-shell"},o.createElement($S,{controller:t,mobile:x,canvasPaneOpen:D,onToggleCanvasPane:re,mobilePane:k,mobileMainLayout:a,onSelectMobilePane:(R,F)=>{R==="workspace"&&k==="workspace"&&l(A=>A==="split"?"chat":A==="chat"?"sessions":"split"),t.closeBudget(),E(R),F&&t.setFocus(F)}}),o.createElement("div",{className:"ps-workspace"},c.adminVisible?o.createElement(gv,{controller:t,mobile:x}):c.budgetOpen?o.createElement(uv,{controller:t}):H?be:x?pe:oe,xe),x&&H?o.createElement(kS,{controller:t}):null,o.createElement(pv,{controller:t})))}export{Cv as P,o as R,Dc as _,Md as a,ft as b,Nv as c,Wr as d,Iv as e,hf as f,Nd as g,el as r,Av as s};
|
|
96
|
+
`)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Zs(r)){const i=_a(n),a=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],d=Xe(c);if(fr(d)){s+=1;break}Ps(d)?l.push(_a(c)):l.push(c?.kind==="runs"?c.runs:[{text:Xe(c),color:c?.color||null}]),s+=1}s<t.length&&Xe(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:i,bodyLines:l,borderColor:a});continue}e.push({type:"line",line:n}),s+=1}return e}function Rb({lines:t,theme:e,controller:s=null}){const n=o.useMemo(()=>pd((t||[]).filter(r=>!r?.canvasUpdate)),[t]);return o.createElement(fd,{blocks:n,theme:e,controller:s})}const ht=new Map,$b=60;function md(t,e,s){const n=`${e}/${s}`,r=ht.get(n);if(r)return ht.delete(n),ht.set(n,r),r;const i=t?.transport?.api?.downloadArtifactResponse;if(typeof i!="function")return Promise.reject(new Error("artifact download unavailable"));const a=i.call(t.transport.api,e,s).then(async l=>{if(!l?.ok)throw new Error(`download failed (${l?.status})`);const c=await l.blob(),d=Zy(s),u=d&&!$i.test(c.type)?new Blob([c],{type:d}):c;return URL.createObjectURL(u)}).catch(l=>{throw ht.get(n)===a&&ht.delete(n),l});for(ht.set(n,a);ht.size>$b;){const[l,c]=ht.entries().next().value;ht.delete(l),Promise.resolve(c).then(d=>URL.revokeObjectURL(d)).catch(()=>{})}return a}function Lb({controller:t,sessionId:e,attachments:s}){const[n,r]=o.useState({});return o.useEffect(()=>{if(!t||!e)return;let i=!1;for(const a of s){const l=a?.filename;l&&md(t,e,l).then(c=>{i||r(d=>d[l]===c?d:{...d,[l]:c})}).catch(()=>{i||r(c=>c[l]==="error"?c:{...c,[l]:"error"})})}return()=>{i=!0}},[t,e,s]),o.createElement("div",{className:"ps-chat-image-strip"},s.map((i,a)=>{const l=i?.filename||`image-${a}`,c=n[l];return c&&c!=="error"?o.createElement("img",{key:`thumb:${a}:${l}`,className:"ps-chat-image-thumb",src:c,alt:l,title:`${l} — click to view full size`,onClick:()=>{try{window.open(c,"_blank","noopener")}catch{}}}):o.createElement("div",{key:`thumb:${a}:${l}`,className:`ps-chat-image-thumb is-pending${c==="error"?" is-error":""}`,title:l},c==="error"?"⚠":"🖼")}))}function fd({blocks:t,theme:e,controller:s=null}){return o.createElement(o.Fragment,null,(t||[]).map((n,r)=>{if(n.type==="imageAttachments")return o.createElement(Lb,{key:`imageAttachments:${r}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const i=n.splashVariant?` is-splash-${n.splashVariant}`:"";return o.createElement("div",{key:`preserve:${r}`,className:`ps-chat-preserve-block${i}`},n.lines.map((a,l)=>o.createElement(We,{key:`preserve:${r}:${l}`,line:a,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const i=nd(n.language),a=o.createElement("section",{key:`code:${r}`,className:`ps-md-code-block ps-chat-code-block${i?" is-diff":""}`},o.createElement("div",{className:"ps-md-code-header"},n.language||"text"),o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,i?Di(n.content||"",e):us(n.content||"",n.language,e))));return rd(n.language)?o.createElement(id,{key:`code:${r}`,code:n.content||"",theme:e,fallback:a}):a}if(n.type==="card")return o.createElement("section",{key:`card:${r}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":Ve(e,n.borderColor)||"var(--ps-border)"}},o.createElement("header",{className:"ps-chat-card-header"},o.createElement(ze,{runs:n.headerRuns,theme:e})),o.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?o.createElement(fd,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((i,a)=>o.createElement("div",{key:`card:${r}:line:${a}`,className:"ps-chat-card-line"},o.createElement(ze,{runs:i,theme:e})))));if(n.type==="table"){const i=n.headerRows||[],a=n.bodyRows||[],l=Math.max(1,...i.map(b=>b.length),...a.map(b=>b.length)),c=l<=6,d=c?Fc([...i,...a]):null,u=!!d,p=d?d.flexIndex:-1,m=b=>b===p?"is-flex-column":null,f=od(i,l),h=`ps-chat-table${c?" is-fit-width":""}${u?" has-flex-column":""}`,g=`ps-chat-table-wrap${c?" is-fit-width":""}${u?" has-flex-column":""}`;return o.createElement("div",{key:`table:${r}`,className:g},o.createElement("table",{className:h,style:d?.minWidth?{"--ps-table-min-width":d.minWidth}:void 0},d?o.createElement("colgroup",null,d.widths.map((b,y)=>o.createElement("col",{key:`col:${y}`,className:m(y)||void 0,style:{width:b}}))):null,i.length>0?o.createElement("thead",null,i.map((b,y)=>o.createElement("tr",{key:`thead:${y}`},Array.from({length:l},(S,w)=>o.createElement("th",{key:`th:${y}:${w}`,className:m(w)||void 0},mt(b[w]||"",e,`chat-table:${r}:head:${y}:${w}`)))))):null,o.createElement("tbody",null,a.map((b,y)=>o.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(S,w)=>o.createElement("td",{key:`td:${y}:${w}`,className:m(w)||void 0,"data-label":f[w]||void 0},o.createElement("span",{className:"ps-table-cell-value"},mt(b[w]||"",e,`chat-table:${r}:${y}:${w}`)))))))))}return o.createElement(We,{key:`line:${r}`,line:n.line,theme:e})}))}function At({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:r=null,children:i,theme:a,className:l=""}){const c=Ve(a,s),d=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||r);return o.createElement("section",{className:`ps-panel${n?" is-focused":""}${d?"":" is-chromeless"}${l?` ${l}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},d?o.createElement("header",{className:"ps-panel-header"},o.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?o.createElement(ze,{runs:t,theme:a}):ka(t)),e||r?o.createElement("div",{className:"ps-panel-header-right"},e?o.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?o.createElement(ze,{runs:e,theme:a}):ka(e)):null,r?o.createElement("div",{className:"ps-panel-actions"},r):null):null):null,o.createElement("div",{className:"ps-panel-body"},i))}function Ob({lines:t,theme:e,controller:s}){return o.createElement("div",{className:"ps-nodemap"},(t||[]).map((n,r)=>{const i=Array.isArray(n?.runs)?n.runs:Array.isArray(n)?n:[n],a=i.find(d=>d?.nodeSelect)?.nodeSelect||null,l=i.some(d=>d?.nodeSelected),c=o.createElement(ze,{runs:i,theme:e});return a?o.createElement("button",{key:`line:${r}`,type:"button",className:`ps-nodemap__row${l?" is-selected":""}`,onPointerDown:d=>{d.preventDefault(),d.stopPropagation(),s.selectNodeMapNode(a)}},c):o.createElement("div",{key:`line:${r}`,className:"ps-nodemap__line"},c)}))}function Fb({lines:t,theme:e,completionByTurn:s}){const[n,r]=o.useState(()=>new Set),i=o.useCallback(u=>{r(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),m})},[]),a=u=>Number(u||0).toLocaleString("en-US"),l=u=>{const p=Number(u||0);if(!Number.isFinite(p))return"?K";const m=p/1e3,f=Math.abs(m)>=10?1:2;return`${m.toFixed(f)}K`},c=u=>{const p=Number(u||0);return Number.isFinite(p)?`${(p/1e3).toFixed(1)}s`:"?s"},d=u=>{const p=String(u||"").trim();if(!p)return"unknown";const m=p.split(":").filter(Boolean),f=m[m.length-1]||"",h=m.length>1&&yy.has(f.toLowerCase())?m.length-2:m.length-1;return m[Math.max(0,h)]||m[0]||"unknown"};return o.createElement(o.Fragment,null,t.map((u,p)=>{const m=u?.kind==="runs"&&Array.isArray(u.runs)?u.runs.find(v=>v?.completedTurn!=null)?.completedTurn:null,f=m!=null?s.get(Number(m)):null;if(!f)return o.createElement(We,{key:`line:${p}`,line:u,theme:e});const h=f.data||{},g=String(f.seq??`${h.turnIndex??m}:${f.createdAt??p}`),b=n.has(g),y=h.reasoningEffort?`${h.model||"(unknown)"}:${h.reasoningEffort}`:h.model||"(unknown)",S=d(h.model),w=h.durationMs!=null?c(h.durationMs):"duration n/a",k=h.durationMs!=null?`${a(h.durationMs)} ms`:"duration n/a",E=`${l(h.tokensInput)} / ${l(h.tokensOutput)}`,x=[["model",y],["started",h.startedAt?new Date(h.startedAt).toLocaleString():null],["ended",h.endedAt?new Date(h.endedAt).toLocaleString():null],["duration",k],["tokens",`${a(h.tokensInput)} in / ${a(h.tokensOutput)} out`],["cache",`${a(h.tokensCacheRead)} read / ${a(h.tokensCacheWrite)} write`],["tools",`${a(h.toolCalls)} calls / ${a(h.toolErrors)} errors`],["names",Array.isArray(h.toolNames)&&h.toolNames.length?h.toolNames.join(", "):null],["worker",h.workerNodeId||null],["result",h.resultType||null],["error",h.errorMessage||null]].filter(([,v])=>v!=null&&v!=="");return o.createElement(o.Fragment,{key:`seq:${p}`},o.createElement(We,{line:u,theme:e}),o.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>i(g)},o.createElement("span",{className:"ps-sequence-turn-caret"},b?"v":">"),o.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),o.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),o.createElement("span",{className:"ps-sequence-turn-model"},S),o.createElement("span",{className:"ps-sequence-turn-rule"}," ("),o.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),o.createElement("span",{className:"ps-sequence-turn-tokens"},E),o.createElement("span",{className:"ps-sequence-turn-rule"},", "),o.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),o.createElement("span",{className:"ps-sequence-turn-duration"},w),o.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),b?o.createElement("div",{className:"ps-sequence-turn-details"},x.map(([v,P])=>o.createElement("div",{key:v},o.createElement("span",{className:"ps-sequence-turn-detail-label"},`${v}: `),o.createElement("span",null,String(P))))):null)}))}const Db={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Hi(t,e=null){return e||Db[String(t||"")]||null}function _n({title:t,titleRight:e=null,color:s,focused:n,actions:r,lines:i,stickyLines:a=[],bottomStickyLines:l=[],scrollOffset:c=0,scrollMode:d="top",paneKey:u,controller:p,className:m="",panelClassName:f="",topContent:h=null,bottomContent:g=null,structuredBlocks:b=!1,stickyBottom:y=!1,renderBody:S=null,focusRegion:w=null,panelRef:k=null}){const E=ee(p,Y=>Y.ui.themeId),x=ft(E),v=o.useRef(null),P=o.useCallback(Y=>{v.current=Y,typeof k=="function"?k(Y):k&&(k.current=Y)},[k]),N=o.useRef(null),_=o.useRef(!1),{normalizedLines:D,onScroll:L,onWheel:I,onTouchStart:C,onTouchMove:U,onTouchEnd:B}=Wy(v,i,c,d,u,p,{stickyBottom:y}),V=o.useMemo(()=>je(a),[a]),ce=o.useMemo(()=>je(l),[l]),X=m.includes("is-preserve")&&f.includes("has-preserved-sticky"),re=`${u}:${t}`;o.useEffect(()=>{const Y=()=>{v.current&&(v.current.scrollLeft=0),N.current&&(N.current.scrollLeft=0)};Y();const Z=typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{Y()}):null;return()=>{Z!=null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Z)}},[re]);const T=o.useCallback(()=>{const Y=Hi(u,w);Y&&p?.setFocus&&p.setFocus(Y)},[p,u,w]),j=o.useCallback((Y,Z)=>{!Y||!Z||Math.abs((Z.scrollLeft||0)-(Y.scrollLeft||0))<=1||(_.current=!0,Z.scrollLeft=Y.scrollLeft,window.requestAnimationFrame(()=>{_.current=!1}))},[]),[H,W]=o.useState({up:!1,down:!1}),z=o.useCallback(Y=>{if(!Y)return;const Z=Y.scrollHeight-Y.scrollTop-Y.clientHeight>4,de=Y.scrollTop>4;W(ve=>ve.up===Z&&ve.down===de?ve:{up:Z,down:de})},[]),Q=o.useCallback(Y=>{L(),z(Y.currentTarget),!(!X||_.current)&&j(Y.currentTarget,N.current)},[L,X,j,z]);o.useEffect(()=>{z(v.current)});const K=o.useCallback(Y=>{!X||_.current||j(Y.currentTarget,v.current)},[X,j]);return o.createElement(At,{title:t,titleRight:e,color:s,focused:n,actions:r,theme:x,className:f},h,V.length>0?o.createElement("div",{ref:N,className:`ps-panel-sticky${X?" is-scroll-sync":""}`,onScroll:K},V.map((Y,Z)=>o.createElement(We,{key:`sticky:${Z}`,line:Y,theme:x}))):null,o.createElement("div",{ref:P,className:`ps-scroll-panel ${m}${H.down?" is-scrolled-down":""}${H.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":w==="sessions"?"1":void 0,onScroll:Q,onMouseDown:T,onTouchStart:C,onWheel:I,onTouchMove:U,onTouchEnd:B,onTouchCancel:B},typeof S=="function"?S(D,x):b?o.createElement(Rb,{lines:D,theme:x,controller:p}):D.map((Y,Z)=>o.createElement(We,{key:`line:${Z}`,line:Y,theme:x}))),ce.length>0?o.createElement("div",{className:"ps-panel-bottom-sticky"},ce.map((Y,Z)=>o.createElement(We,{key:`bottom-sticky:${Z}`,line:Y,theme:x}))):null,g)}const hr="—";function Bb(t,e){const s=typeof t?.waitReason=="string"&&t.waitReason.trim()?jb(t.waitReason):null;if(!s)return null;const n=String(e||"");return n==="waiting"||n.startsWith("waiting on")||n==="input_required"?s:null}const Hb=10,Ub=72;function jb(t,e=Hb,s=Ub){const n=String(t??"").replace(/\s+/gu," ").trim();if(!n)return"";let i=n.split(" ").slice(0,e).join(" ");if(i.length>s){const a=i.slice(0,s),l=a.lastIndexOf(" ");i=l>0?a.slice(0,l):a}return i===n?n:`${i.replace(/[.,;:—-]+$/u,"")}…`}function Gb(t){return t?.cronActive===!0?"On wake":"Waiting"}function Wb({session:t,childCount:e=0,pause:s=null,controller:n=null,collapsed:r=!1,onToggle:i=null}){const a=(S,w,k="")=>{const E=w==null||w===""?hr:String(w),x=E===hr;return o.createElement("div",{className:`ps-session-detail-field${k?` ${k}`:""}${x?" is-none":""}`,key:S},o.createElement("span",{className:"ps-session-detail-label"},S),o.createElement("span",{className:"ps-session-detail-value",title:E},E))},l=t?.contextUsage,c=l&&Number.isFinite(l.currentTokens)&&Number.isFinite(l.tokenLimit)&&l.tokenLimit>0,d=c?Math.round(l.currentTokens/l.tokenLimit*100):null,u=c?`${J(l.currentTokens)} / ${J(l.tokenLimit)} · ${d}%`:null;let p=null;t&&!t.isGroup&&(p="off",t.cronActive===!0&&(p=t.cronKind==="wall-clock"?`next ${un(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${Vt(t.cronInterval)}`:"on"));const m=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,f=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,h=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null,g=jp(t),b=Bb(t,g?.status),y=!s&&!b?null:o.createElement("div",{className:`ps-session-detail-pause${s?" is-paused":""}`},o.createElement("span",{className:"ps-session-detail-label"},s?"Paused":Gb(t)),o.createElement("span",{className:"ps-session-detail-why",...!s&&typeof t?.waitReason=="string"&&t.waitReason.trim()?{title:t.waitReason.trim()}:{}},s?s.reason:b,s&&s.clears?o.createElement("span",{className:"ps-session-detail-clears"},s.clears):null,s&&n?o.createElement("button",{type:"button",className:"ps-budget-link",title:s.provider?`Open ${s.provider} in Providers & Budgets`:"Open providers and budgets",onClick:()=>n.openBudget(s.provider?{provider:s.provider}:{}).catch(()=>{})},s.provider?`Open ${s.provider}`:"Open providers and budgets"):null));if(r){const S=[];return u&&S.push(o.createElement("span",{key:"context",className:`ps-session-detail-mark${d!=null&&d>=85?" is-hot":d!=null&&d>=70?" is-warm":""}`},d!=null?`${d}%`:u)),g&&S.push(o.createElement("span",{key:"updated",className:"ps-session-detail-mark"},`${g.relative} (${g.status})`)),(s||b)&&S.push(o.createElement("span",{key:"halt",className:`ps-session-detail-mark${s?" is-paused":""}`,title:s?s.reason:b},s?"paused":"waiting")),o.createElement("div",{className:"ps-session-detail-box is-collapsed"},o.createElement("button",{type:"button",className:"ps-session-detail-summary","aria-expanded":!1,title:"Show session details",onClick:i},o.createElement("span",{className:"ps-session-detail-twisty","aria-hidden":"true"},"▸"),o.createElement("span",{className:"ps-session-detail-summary-title"},t?.title||hr),o.createElement("span",{className:"ps-session-detail-marks"},S)),y)}return o.createElement("div",{className:"ps-session-detail-box"},o.createElement("button",{type:"button",className:"ps-session-detail-collapse","aria-expanded":!0,title:"Hide session details",onClick:i},o.createElement("span",{"aria-hidden":"true"},"▾")," Less"),a("Title",t?.title,"is-title"),a("ID",t?.sessionId,"is-id"),a("Owner",t?.owner?Sv(t.owner):null),a("Model",m),a("Context",u,d!=null&&d>=85?"is-hot":d!=null&&d>=70?"is-warm":""),a("Cron",p,t?.cronActive===!0?"is-armed":""),a("Agent",t?.agentId),a("Updated",g?`${g.relative} (${g.status})`:null),a("Children",h),a("Access",f),y)}function zb(){const t="(pointer: coarse)",e=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1,[s,n]=o.useState(e);return o.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(t),i=a=>n(a.matches);return r.addEventListener?.("change",i),()=>r.removeEventListener?.("change",i)},[]),s}const hd=13,gd=11,yd=1.5,qb=7;function Kb(t){return hd+(t-1)*gd+yd/2-qb/2}const Vb=o.memo(function({row:e,theme:s,structuredRows:n,mobile:r,onRowClick:i,setRef:a,drag:l}){const c=Math.max(0,e.depth),d=o.useMemo(()=>{if(c<1)return;const S=Array.from({length:c},(w,k)=>k);return{backgroundImage:S.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:S.map(()=>`${yd}px 100%`).join(", "),backgroundPosition:S.map(w=>`${hd+w*gd}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),u=o.useCallback(S=>a(e.sessionId,S),[a,e.sessionId]),p=o.useCallback(S=>i(S,e),[i,e]),m=e.groupId||null,f=!!(l?.dragging&&l.overGroupId&&m===l.overGroupId),h=f&&!!e.isGroup,g=!!(l?.dragging&&l.insertBeforeId===e.sessionId),b=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===e.sessionId),y=o.useCallback(S=>{if(l?.onPointerDown&&S.button===0){if(S.currentTarget?.setPointerCapture&&S.pointerId!=null)try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}l.onPointerDown(S,e)}},[l,e]);return o.createElement("button",{type:"button",ref:u,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${f?" is-drop-zone":""}${h?" is-drop-target":""}${g?" is-insert-before":""}${b?" is-insert-after":""}${e.depth>0?" is-nested":""}`,style:d,tabIndex:e.active?0:-1,"aria-selected":e.active?"true":"false","data-session-id":e.sessionId,"data-group-row":e.isGroup?"1":void 0,"data-group-id":e.isGroup?e.groupId||"":void 0,"data-drop-group":m||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:y,onClick:p,onContextMenu:S=>{S.ctrlKey&&(S.preventDefault(),i(S,e))}},o.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${Kb(c)}px`:"0px"}},o.createElement(Yb,{row:e,theme:s,structured:n,showInlineDetail:r})))});function $a(t,e){if(!Array.isArray(t))return{statusColor:null,rest:t};let s=null;const n=[];for(const r of t)if(r?.role!=="depth"&&r?.role!=="selection"){if(r?.role==="status"){s=Ve(e,r.color)||null;continue}n.push(r)}return{statusColor:s,rest:n}}function La({color:t,node:e=!1}){return o.createElement("span",{className:`ps-session-status-dot${e?" is-node":""}`,style:t?e?{borderColor:t}:{background:t}:void 0})}function Br({badge:t,size:e="sm"}){return t?o.createElement("span",{className:`ps-owner-avatar is-${e}${t.isMine?" is-mine":""}`,"data-owner-hue":String(t.hue??0),title:t.isMine?`${t.name} (you)`:t.name,"aria-label":t.name},t.initials):null}function Oa(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function Yb({row:t,theme:e,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(t.titleRuns))){if(!Array.isArray(t.runs))return t.text;const u=$a(Oa(t.runs),e);return o.createElement(o.Fragment,null,u.statusColor?o.createElement(La,{color:u.statusColor,node:t.depth>0}):null,o.createElement(Br,{badge:t.ownerBadge}),o.createElement(Wa,{mark:t.canvasMark}),o.createElement("span",{className:"ps-session-row-title__text"},o.createElement(ze,{runs:u.rest,theme:e})))}const i=$a(Oa(t.titleRuns),e),a=Array.isArray(t.ctxRuns)?t.ctxRuns:[],l=a.length>0,c=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],d=n&&t.active&&c.length>0;return o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-session-row-line"},o.createElement("div",{className:"ps-session-row-title"},i.statusColor?o.createElement(La,{color:i.statusColor,node:t.depth>0}):null,o.createElement(Br,{badge:t.ownerBadge}),o.createElement(Wa,{mark:t.canvasMark}),o.createElement("span",{className:"ps-session-row-title__text"},o.createElement(ze,{runs:i.rest,theme:e}))),l?o.createElement("div",{className:"ps-session-row-ctx"},o.createElement(ze,{runs:a,theme:e})):null),d?o.createElement("div",{className:"ps-session-row-detail"},o.createElement(ze,{runs:c,theme:e})):null)}function Xb(t){const e=o.useRef(t),s=o.useRef(null),n=o.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}const Fa=10,Qb=1.6,Da=.05,Zb=.95,Ba=4;function Jb(t,e){return Math.abs(t)<Fa&&Math.abs(e)<Fa?null:Math.abs(t)>Math.abs(e)*Qb?"x":"y"}function eS(t,e=!0){o.useEffect(()=>{const s=t.current;if(!s||!e)return;let n=0,r=0,i=0,a=0,l=0,c=0,d=null,u=null,p=!1;const m=()=>{u!==null&&(cancelAnimationFrame(u),u=null)},f=()=>typeof performance<"u"?performance.now():Date.now(),h=E=>E==="x"?s.scrollWidth>s.clientWidth+1:s.scrollHeight>s.clientHeight+1,g=E=>{if(p=u!==null,m(),E.targetTouches.length!==1){d="done";return}const x=E.targetTouches[0];n=i=x.clientX,r=a=x.clientY,l=f(),c=0,d=null},b=E=>{if(d==="done"||E.targetTouches.length!==1)return;const x=E.targetTouches[0],v=x.clientX-n,P=x.clientY-r;if(d===null){const U=h("y");if(!U&&!h("x")){d="done";return}if(U&&E.cancelable&&E.preventDefault(),d=Jb(v,P),d===null)return;if(!h(d)||!E.cancelable){d="done";return}i=x.clientX,a=x.clientY,l=f()}E.cancelable&&E.preventDefault();const N=x.clientX-i,_=x.clientY-a,D=f(),L=Math.max(1,D-l),I=d==="x"?N:_;d==="x"?s.scrollLeft-=N:s.scrollTop-=_;const C=Math.max(-Ba,Math.min(Ba,I/L));c=c*.7+C*.3,i=x.clientX,a=x.clientY,l=D},y=E=>{if(Math.abs(c)<Da)return;let x=c;const v=()=>{if(x*=Zb,Math.abs(x)<Da){u=null;return}const P=E==="x"?s.scrollLeft:s.scrollTop;if(E==="x"?s.scrollLeft-=x*16:s.scrollTop-=x*16,(E==="x"?s.scrollLeft:s.scrollTop)===P){u=null;return}u=requestAnimationFrame(v)};u=requestAnimationFrame(v)},S=E=>{if(E.targetTouches.length>0){d="done";return}const x=d;d=null,(x==="x"||x==="y")&&y(x),c=0},w=()=>{d=null,c=0,m()},k=E=>{p&&(p=!1,E.preventDefault(),E.stopPropagation())};return s.addEventListener("touchstart",g,{passive:!0}),s.addEventListener("touchmove",b,{passive:!1}),s.addEventListener("touchend",S,{passive:!0}),s.addEventListener("touchcancel",w,{passive:!0}),s.addEventListener("click",k,!0),()=>{m(),s.removeEventListener("touchstart",g),s.removeEventListener("touchmove",b),s.removeEventListener("touchend",S),s.removeEventListener("touchcancel",w),s.removeEventListener("click",k,!0)}},[t,e])}function Hr({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1,showDetailBox:r=null}){const i=String(s).includes("ps-mobile-session-pane"),a=o.useRef(null),l=zb(),c=i||l;eS(a,c);const d=ee(t,R=>R.ui.themeId),u=ft(d),p=ee(t,R=>!!R.ui.sessionDetailCollapsed),m=o.useRef(new Map),f=ee(t,R=>({branding:R.branding,activeSessionId:R.sessions.activeSessionId,sessionsById:R.sessions.byId,sessionsFlat:R.sessions.flat,filterQuery:R.sessions.filterQuery||"",ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,manualOrder:R.sessions.manualOrder,selectedIds:R.sessions.selectedIds,selectMode:R.sessions.selectMode,auth:R.auth,connectionMode:R.connection?.mode||"local",modalOpen:!!R.ui.modal,focused:R.ui.focusRegion==="sessions",listDeselected:!!R.sessions.listDeselected,canvasBySessionId:R.canvas?.bySessionId,canvasPrefs:R.canvas?.prefs,budgetPaused:R.budget?.paused}),Le),h=o.useMemo(()=>ds({sessions:{activeSessionId:f.activeSessionId,byId:f.sessionsById,flat:f.sessionsFlat,filterQuery:f.filterQuery,ownerFilter:f.ownerFilter,pinnedIds:f.pinnedIds,manualOrder:f.manualOrder,selectedIds:f.selectedIds,selectMode:f.selectMode,listDeselected:f.listDeselected},auth:f.auth,connection:{mode:f.connectionMode},branding:f.branding,canvas:{bySessionId:f.canvasBySessionId,prefs:f.canvasPrefs},budget:{paused:f.budgetPaused}}),[f.activeSessionId,f.auth,f.branding,f.budgetPaused,f.canvasBySessionId,f.canvasPrefs,f.connectionMode,f.filterQuery,f.listDeselected,f.ownerFilter,f.pinnedIds,f.manualOrder,f.selectedIds,f.selectMode,f.sessionsById,f.sessionsFlat]),g=Xb(h),b=f.activeSessionId&&f.sessionsById[f.activeSessionId]||null,y=f.activeSessionId&&g.find(R=>R.sessionId===f.activeSessionId)||null,[S,w]=o.useState(!1),[k,E]=o.useState(null),x=o.useRef(!1),v=["modelPicker","reasoningEffortPicker","contextTierPicker"],P=ee(t,R=>v.includes(R.ui.modal?.type));o.useEffect(()=>{!P&&x.current&&(x.current=!1,w(!0))},[P]);const N=()=>{x.current=!0,w(!1),t.openSwitchModelPicker(()=>{x.current=!1}).then(()=>{!v.includes(t.getState().ui.modal?.type)&&x.current&&(x.current=!1,w(!0))}).catch(R=>{x.current=!1,w(!0),t.dispatch({type:"ui/status",text:R?.message||String(R)||"Failed to switch model"})})},_=f.auth?.principal||null,D=f.auth?.authorization?.role,L=D==="admin"||D==="anonymous",I=!!(b?.owner&&_&&String(b.owner.provider)===String(_.provider)&&String(b.owner.subject)===String(_.subject)),C=!!(b&&!b.isGroup&&(b.isSystem?L:L||I)),U=Array.isArray(f.selectedIds)?f.selectedIds.length:0,B=U>1,V=!!(b?.isGroup&&!B),ce=!!(b&&!b.isSystem&&(b.isGroup||!b.parentSessionId&&!b.groupId)),X=!!(b&&Array.isArray(f.pinnedIds)&&f.pinnedIds.includes(b.sessionId)),re=!!(b?.isGroup&&Number(b.memberCount||0)===0),T=B?Array.isArray(f.selectedIds)&&f.selectedIds.some(R=>{const F=f.sessionsById[R];return F&&!F.isSystem&&!F.isGroup}):b?.isGroup?!0:!!b,j=U>0,H=!!(b&&!f.listDeselected&&!b.isSystem&&!b.isGroup&&!b.parentSessionId),W=j?f.selectedIds.filter(R=>{const F=f.sessionsById[R];return F&&!F.isSystem&&!F.isGroup&&!F.parentSessionId}):H?[b.sessionId]:[],z=`ps-session-pane${s?` ${s}`:""}`,Q=o.useRef(null);Q.current={rows:g,viewState:f,controller:t};const[K,Y]=o.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),Z=o.useRef(null),de=o.useRef(null),ve=o.useCallback(()=>{de.current!=null&&(cancelAnimationFrame(de.current),de.current=null)},[]),le=o.useCallback(()=>{let R=a.current;for(;R&&R!==document.body;){const F=window.getComputedStyle(R).overflowY;if(/(auto|scroll|overlay)/.test(F)&&R.scrollHeight-R.clientHeight>1)return R;R=R.parentElement}return null},[]),st=o.useCallback((R,F)=>{const q=le();if(!q){ve();return}const te=q.getBoundingClientRect();let se=0;if(F<te.top+48?se=-14*Math.min(1,(te.top+48-F)/48):F>te.bottom-48&&(se=14*Math.min(1,(F-(te.bottom-48))/48)),Z.current&&(Z.current.autoScrollStep=se),!Z.current){ve();return}if(de.current!=null)return;const ue=()=>{const fe=Z.current;if(!fe||!fe.autoScrollStep){ve();return}q.scrollTop+=fe.autoScrollStep,de.current=requestAnimationFrame(ue)};de.current=requestAnimationFrame(ue)},[le,ve]),ye=o.useCallback(R=>{const F=Z.current;if(Z.current=null,ve(),Y({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!R||!F?.started||F.ids.length===0)){if(F.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:F.ids[0],beforeSessionId:F.beforeSessionId});return}F.intent!=="file"&&F.intent!=="unfile"||t.moveSessionsToGroup(F.overGroupId,F.ids).catch(A=>{t.dispatch({type:"ui/status",text:`Move failed: ${A?.message||A}`})})}},[t,ve]),nt=o.useCallback((R,F)=>typeof R!="number"||typeof F!="number"?null:(document.elementFromPoint(R,F)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),Ce=o.useCallback((R,F,A,O)=>{if(typeof R!="number"||typeof F!="number"||A==null)return;const q=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(A)}"][data-orderable="1"]`));if(q.length===0)return;for(const ue of q){const fe=ue.getBoundingClientRect();if(F<fe.top+fe.height/2)return{before:ue.getAttribute("data-session-id")||null,after:null}}const se=q[q.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:se&&se!==O?se:null}},[]),Oe=o.useCallback((R,F,A)=>{const O=nt(R,F);if(A?.isGroup){const ue=A.ids.length===1?Ce(R,F,A.container,A.ids[0]):void 0;return ue===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:ue.before,after:ue.after}}const q=A?.ownGroupId||null;if(O&&O!==q)return{kind:"file",overGroupId:O,before:void 0,after:null};if(!O&&q)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const se=A?.orderable&&A.ids.length===1?Ce(R,F,A.container,A.ids[0]):void 0;return se===void 0?{kind:O?"file":"none",overGroupId:O,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:se.before,after:se.after}},[nt,Ce]);o.useEffect(()=>{if(!K.dragging)return;const R=q=>{const te=Z.current;if(!te)return;const se=Oe(q.clientX,q.clientY,te);te.intent=se.kind,te.overGroupId=se.overGroupId,te.beforeSessionId=se.before,st(q.clientX,q.clientY),document.body.classList.toggle("ps-drop-ok",se.kind==="file"),Y(ue=>({...ue,intent:se.kind,overGroupId:se.overGroupId,insertBeforeId:se.before,insertAfterId:se.after,x:q.clientX,y:q.clientY}))},F=q=>{const te=Z.current;if(te&&typeof q?.clientX=="number"){const se=Oe(q.clientX,q.clientY,te);te.intent=se.kind,te.overGroupId=se.overGroupId,te.beforeSessionId=se.before}ye(!0)},A=()=>ye(!1),O=q=>{q.key==="Escape"&&ye(!1)};return window.addEventListener("pointermove",R),window.addEventListener("pointerup",F),window.addEventListener("pointercancel",A),window.addEventListener("keydown",O),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",F),window.removeEventListener("pointercancel",A),window.removeEventListener("keydown",O),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[K.dragging,ye,Oe,st]);const ut=o.useMemo(()=>({dragging:K.dragging,overGroupId:K.overGroupId,insertBeforeId:K.insertBeforeId,insertAfterId:K.insertAfterId,onPointerDown:(R,F)=>{if(F.isSystem||!F.orderable&&!F.isGroup&&F.depth>0)return;const A=R.clientX,O=R.clientY,q={row:F,startX:A,startY:O,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!F.orderable,container:F.orderContainer??null,isGroup:!!F.isGroup,ownGroupId:F.groupId||null,intent:"none",autoScrollStep:0},te=ue=>{if(q.started||Math.hypot(ue.clientX-A,ue.clientY-O)<5)return;q.started=!0;const fe=Q.current.viewState,Te=Array.isArray(fe.selectedIds)?fe.selectedIds:[],Be=Te.includes(F.sessionId)&&Te.length>1?Te:[F.sessionId],me=fe.sessionsById||{};q.ids=Be,Z.current=q,Y({dragging:!0,ids:Be,titles:Be.map(Ke=>me[Ke]?.title||String(Ke).slice(0,8)).slice(0,3),overGroupId:null,x:ue.clientX,y:ue.clientY})},se=()=>{window.removeEventListener("pointermove",te),window.removeEventListener("pointerup",se)};window.addEventListener("pointermove",te),window.addEventListener("pointerup",se)}}),[K.dragging,K.overGroupId,K.insertBeforeId,K.insertAfterId]),rt=o.useCallback((R,F)=>{const{rows:A,viewState:O,controller:q}=Q.current;if(R.metaKey||R.ctrlKey){R.preventDefault(),O.selectMode||q.dispatch({type:"sessions/selectMode",enabled:!0}),q.dispatch({type:"sessions/selectToggle",sessionId:F.sessionId}),q.setFocus("sessions");return}if(R.shiftKey&&O.activeSessionId){R.preventDefault();const se=A.map(Te=>Te.sessionId),ue=se.indexOf(O.activeSessionId),fe=se.indexOf(F.sessionId);if(ue>=0&&fe>=0){const[Te,Be]=ue<=fe?[ue,fe]:[fe,ue],me=se.slice(Te,Be+1),Ke=Array.from(new Set([...O.selectedIds||[],...me]));q.setSessionSelection(Ke),q.setFocus("sessions");return}}if(F.hasChildren&&F.active){q.dispatch({type:F.collapsed?"sessions/expand":"sessions/collapse",sessionId:F.sessionId}),q.setFocus("sessions");return}O.selectMode&&q.dispatch({type:"sessions/selectClear"}),q.setFocus("sessions"),F.sessionId===O.activeSessionId?q.dispatch({type:"sessions/listReselect"}):F.active||q.loadSession(F.sessionId).catch(()=>{})},[]),G=o.useCallback((R,F)=>{R&&(F?m.current.set(R,F):m.current.delete(R))},[]),oe=o.useRef(null),be=`${f.activeSessionId||""}${f.focused?1:0}${f.modalOpen?1:0}`;o.useEffect(()=>{if(f.modalOpen||!f.focused||!f.activeSessionId){oe.current=null;return}const R=m.current.get(f.activeSessionId);if(!R||oe.current===be)return;oe.current=be;const F=document.activeElement,A=!!(F&&(F.tagName==="INPUT"||F.tagName==="TEXTAREA"||F.tagName==="SELECT"||F.isContentEditable));F!==R&&!A&&R.focus({preventScroll:!0}),R.scrollIntoView({block:"nearest"})},[be,f.activeSessionId,f.focused,f.modalOpen,f.sessionsFlat]);const pe=o.createElement(o.Fragment,null,B?o.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",fontSize:"12px",opacity:.85},title:"Multiple sessions selected. Move to group or cancel selected sessions; click Clear to exit."},`${U} selected`):null,B?o.createElement(he,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(M.CLEAR_SESSION_SELECTION).catch(()=>{})}):o.createElement(he,{className:"ps-mini-button ps-pin-icon",icon:o.createElement(wS),onClick:()=>t.handleCommand(M.PIN_SESSION).catch(()=>{}),disabled:!ce,active:X,label:ce?X?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),o.createElement(he,{className:"ps-mini-button",icon:W.length>1?o.createElement("span",{className:"ps-icon-badge"},o.createElement(ja),o.createElement("span",{className:"ps-icon-badge__count"},String(W.length))):o.createElement(ja),onClick:()=>t.handleCommand(M.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:W.length>1?`Move ${W.length} selected sessions to a group`:W.length===1?"Move this session to a group":"New group"}),o.createElement(he,{className:"ps-mini-button",icon:o.createElement(bd),onClick:()=>{if(b?.isGroup){t.handleCommand(M.OPEN_RENAME_SESSION).catch(()=>{});return}w(!0)},disabled:!C&&!V||B,label:B?"Disabled while multiple sessions are selected":b?.isSystem?"System sessions are managed by administrators":b?.isGroup?"Rename folder":C?"Manage session — rename, switch model, and sharing":"Only this session's owner or an admin can manage it"}),o.createElement(he,{className:"ps-mini-button",icon:o.createElement(vS),onClick:()=>{const R=b?.sessionId;if(!R)return;const F=Wc(R);F&&(Sn(F),E({url:F,warn:!1}),Py(t,R).then(A=>{E(O=>O&&O.url===F?{...O,warn:A}:O)}).catch(()=>{}))},disabled:!b||b.isGroup||B,label:"Copy link — copy a direct link to this session"}),o.createElement(he,{className:"ps-mini-button",icon:o.createElement(b?.isSystem?cS:Ur),onClick:()=>t.handleCommand(b?.isGroup?M.DELETE_SESSION:M.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!T,label:B?`Terminate ${U} selected sessions (Mark Completed, Cancel, or Delete)`:b?.isGroup?re?"Delete this empty group":"This group cannot be deleted yet":b?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),xe=K.dragging?o.createElement("div",{className:"ps-drag-ghost",style:{left:`${K.x}px`,top:`${K.y}px`}},o.createElement("div",{className:`ps-drag-ghost__stack${K.ids.length>1?" is-collection":""}`},K.ids.length>1?o.createElement("span",{className:"ps-drag-ghost__count"},String(K.ids.length)):null,o.createElement("span",{className:"ps-drag-ghost__title"},K.ids.length>1?`${K.ids.length} sessions`:K.titles[0]||"session")),o.createElement("div",{className:"ps-drag-ghost__hint"},K.intent==="file"?"Release to file here":K.intent==="unfile"?"Release to remove from folder":K.intent==="reorder"?"Release to move here":"Release to cancel")):null;return o.createElement(o.Fragment,null,xe,o.createElement(At,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:f.focused,theme:u,actions:pe,className:z},o.createElement("div",{ref:a,className:`ps-action-list ps-session-list${K.dragging?" is-dragging":""}`,onClick:R=>{R.target instanceof Element&&R.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},g.length===0?o.createElement("div",{className:"ps-empty-state"},f.filterQuery?`No sessions matched "@@${f.filterQuery}".`:"No sessions yet."):g.map(R=>o.createElement(Vb,{key:R.sessionId,row:R,theme:u,structuredRows:n,mobile:i,onRowClick:rt,setRef:G,drag:c?null:ut}))),(r===null?!i:r)?o.createElement(Wb,{session:b,childCount:y?.childCount||0,pause:y?.pause||null,controller:t,collapsed:p,onToggle:()=>t.dispatch({type:"ui/sessionDetailCollapsed",collapsed:!p})}):null),S&&b&&!b.isGroup?o.createElement(xS,{controller:t,sessionId:b.sessionId,initialTitle:b.title||"",currentModel:b.model||"",currentReasoningEffort:b.reasoningEffort||"",principal:f.auth?.principal||null,onClose:()=>w(!1),onSwitchModel:N,onChanged:()=>{}}):null,k?o.createElement(tS,{url:k.url,warn:k.warn,onCopyAgain:()=>{Sn(k.url),t.dispatch({type:"ui/status",text:Ny})},onClose:()=>E(null)}):null)}function tS({url:t,warn:e,onCopyAgain:s,onClose:n}){const[r,i]=o.useState(""),a=Ai(t,Pn).length>1,l=o.useCallback((d,u)=>{d==="session"&&!a?s?.():navigator?.clipboard?.writeText&&navigator.clipboard.writeText(u).catch(()=>{}),i(d),window.setTimeout(()=>i(""),1500)},[a,s]),c=d=>d.stopPropagation();return o.createElement("div",{className:"ps-share-overlay",onClick:n},o.createElement("div",{className:"ps-link-modal",onClick:c},o.createElement("div",{className:"ps-share-modal-head"},o.createElement("span",null,a?"Session links copied":"Link copied"),o.createElement("button",{className:"ps-modal-close",onClick:n,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-share-section-sub"},a?"All entry-point links were copied. Copy just the one your recipient's network can reach, or take both.":"Copied to your clipboard — anyone with access can open the session from this link."),o.createElement(zc,{url:t,keyPrefix:"session",copied:r,onCopy:l}),e?o.createElement("div",{className:"ps-link-warn"},Ty):null))}const Ha={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Re({children:t}){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},t)}function bd(){return o.createElement(Re,null,o.createElement("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"}))}function Ui(){return o.createElement(Re,null,o.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function sS(){return o.createElement(Re,null,o.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),o.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function nS(){return o.createElement(Re,null,o.createElement("path",{d:"M3 6h18"}),o.createElement("path",{d:"M8 6V4h8v2"}),o.createElement("path",{d:"M19 6l-1 15H6L5 6"}),o.createElement("path",{d:"M10 11v5"}),o.createElement("path",{d:"M14 11v5"}))}function rS(){return o.createElement(Re,null,o.createElement("circle",{cx:"12",cy:"12",r:"9"}),o.createElement("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor"}))}function iS(){return o.createElement(Re,null,o.createElement("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),o.createElement("path",{d:"M16 3h3a2 2 0 0 1 2 2v3"}),o.createElement("path",{d:"M21 16v3a2 2 0 0 1-2 2h-3"}),o.createElement("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}))}function oS(){return o.createElement(Re,null,o.createElement("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),o.createElement("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),o.createElement("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}),o.createElement("path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}))}function aS(){return o.createElement(Re,null,o.createElement("circle",{cx:"12",cy:"12",r:"3"}),o.createElement("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"}))}function lS(){return o.createElement(Re,null,o.createElement("circle",{cx:"12",cy:"12",r:"9"}),o.createElement("path",{d:"M14.5 9.2a2.6 2.6 0 0 0-2.5-1.6c-1.5 0-2.6.8-2.6 2s1 1.7 2.6 2 2.6.8 2.6 2-1.1 2-2.6 2a2.6 2.6 0 0 1-2.5-1.6"}),o.createElement("path",{d:"M12 6v1.6"}),o.createElement("path",{d:"M12 16.4V18"}))}function cS(){return o.createElement(Re,null,o.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),o.createElement("path",{d:"M21 3v5h-5"}))}function dS(){return o.createElement(Re,null,o.createElement("path",{d:"M12 16V4"}),o.createElement("path",{d:"M7.5 8.5L12 4l4.5 4.5"}),o.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function Sd(){return o.createElement(Re,null,o.createElement("path",{d:"M12 4v12"}),o.createElement("path",{d:"M7.5 11.5L12 16l4.5-4.5"}),o.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function uS(){return o.createElement(Re,null,o.createElement("line",{x1:"4.5",y1:"3",x2:"4.5",y2:"21"}),o.createElement("line",{x1:"19.5",y1:"3",x2:"19.5",y2:"21"}),o.createElement("path",{d:"M4.5 8.5h13"}),o.createElement("path",{d:"M15 6l2.5 2.5-2.5 2.5"}),o.createElement("path",{d:"M19.5 15.5h-13"}),o.createElement("path",{d:"M9 13l-2.5 2.5 2.5 2.5"}))}function Ua(){return o.createElement(Re,null,o.createElement("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),o.createElement("line",{x1:"9.5",y1:"4",x2:"9.5",y2:"20"}),o.createElement("line",{x1:"12.5",y1:"9",x2:"18",y2:"9"}),o.createElement("line",{x1:"12.5",y1:"13",x2:"18",y2:"13"}))}function pS(){return o.createElement(Re,null,o.createElement("path",{d:"M4 17l6-6-6-6"}),o.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function mS(){return o.createElement(Re,null,o.createElement("circle",{cx:"6",cy:"6",r:"2.6"}),o.createElement("circle",{cx:"18",cy:"6",r:"2.6"}),o.createElement("circle",{cx:"12",cy:"18",r:"2.6"}),o.createElement("line",{x1:"8.6",y1:"6",x2:"15.4",y2:"6"}),o.createElement("line",{x1:"7.4",y1:"8.3",x2:"10.6",y2:"15.7"}),o.createElement("line",{x1:"16.6",y1:"8.3",x2:"13.4",y2:"15.7"}))}const fS="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",hS="M15.2 10.1A4.2 4.2 0 0 1 15.2 11.9L14.23 11.69A3.2 3.2 0 0 1 13.8 12.73L14.64 13.26A4.2 4.2 0 0 1 13.36 14.54L12.83 13.7A3.2 3.2 0 0 1 11.79 14.13L12 15.1A4.2 4.2 0 0 1 10.2 15.1L10.41 14.13A3.2 3.2 0 0 1 9.37 13.7L8.84 14.54A4.2 4.2 0 0 1 7.56 13.26L8.4 12.73A3.2 3.2 0 0 1 7.97 11.69L7 11.9A4.2 4.2 0 0 1 7 10.1L7.97 10.31A3.2 3.2 0 0 1 8.4 9.27L7.56 8.74A4.2 4.2 0 0 1 8.84 7.46L9.37 8.3A3.2 3.2 0 0 1 10.41 7.87L10.2 6.9A4.2 4.2 0 0 1 12 6.9L11.79 7.87A3.2 3.2 0 0 1 12.83 8.3L13.36 7.46A4.2 4.2 0 0 1 14.64 8.74L13.8 9.27A3.2 3.2 0 0 1 14.23 10.31ZM12.8 11A1.7 1.7 0 0 0 9.4 11A1.7 1.7 0 0 0 12.8 11Z",gS="M7.23 15.01A5.7 5.7 0 0 1 17.76 14.55L19.11 15.04L15.1 16.57L14.71 13.44L16.06 13.93A3.9 3.9 0 0 0 8.87 14.25Z";function yS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},o.createElement("path",{d:fS,strokeWidth:"1.9",strokeLinejoin:"round"}),o.createElement("path",{d:hS,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),o.createElement("path",{d:gS,fill:"currentColor",stroke:"none"}))}function bS(){return o.createElement(Re,null,o.createElement("path",{d:"M9 2.8h4.2L17 6.6v8.6a1.8 1.8 0 0 1-1.8 1.8H15"}),o.createElement("path",{d:"M4.5 9.4a1.8 1.8 0 0 1 1.8-1.8h4.2l3.8 3.8v8a1.8 1.8 0 0 1-1.8 1.8H6.3a1.8 1.8 0 0 1-1.8-1.8z"}),o.createElement("path",{d:"M10.5 7.6v3.8h3.8"}))}function SS(){return o.createElement(Re,null,o.createElement("rect",{x:"4.2",y:"12",width:"3.6",height:"8",rx:"0.6",fill:"currentColor",stroke:"none"}),o.createElement("rect",{x:"10.2",y:"6.5",width:"3.6",height:"13.5",rx:"0.6",fill:"currentColor",stroke:"none"}),o.createElement("rect",{x:"16.2",y:"9.5",width:"3.6",height:"10.5",rx:"0.6",fill:"currentColor",stroke:"none"}),o.createElement("path",{d:"M3 21h18"}))}function vS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),o.createElement("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}))}function Ur(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M3 6h18"}),o.createElement("path",{d:"M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"}),o.createElement("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),o.createElement("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),o.createElement("line",{x1:"14",y1:"11",x2:"14",y2:"17"}))}function ja(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}))}function wS(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M9 3h6"}),o.createElement("path",{d:"M10 3v6l-3 3v2h10v-2l-3-3V3"}),o.createElement("line",{x1:"12",y1:"14",x2:"12",y2:"21"}))}function ES(){return o.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),o.createElement("path",{d:"M3 3v5h5"}),o.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),o.createElement("path",{d:"M21 21v-5h-5"}))}function kS(t,e,s){const[n,r]=o.useState({access:null,loading:!1}),i=o.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){r({access:null,loading:!1});return}let a=!1;return r(l=>({...l,loading:!0})),t.transport.getSessionAccess(e).then(l=>{a||r({access:l,loading:!1})}).catch(()=>{a||r({access:null,loading:!1})}),()=>{a=!0}},[t,e,s]);return o.useEffect(()=>{let a;const l=setTimeout(()=>{a=i()},Cy);return()=>{clearTimeout(l),typeof a=="function"&&a()}},[i]),{access:n.access,loading:n.loading,reload:i}}function xS({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:r,principal:i,onClose:a,onSwitchModel:l,onChanged:c}){const[d,u]=o.useState("general"),[p,m]=o.useState(null),[f,h]=o.useState(s||""),[g,b]=o.useState([]),[y,S]=o.useState([]),[w,k]=o.useState("private"),[E,x]=o.useState(""),[v,P]=o.useState("write"),[N,_]=o.useState([]),[D,L]=o.useState(!1),[I,C]=o.useState(null);o.useEffect(()=>{let G=!1;return t.transport.getSessionAccess(e).then(oe=>{!G&&oe&&(m(oe),k(oe.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(oe=>{G||_(Array.isArray(oe)?oe:[])}).catch(()=>{}),()=>{G=!0}},[t,e]);const U=o.useCallback(()=>{t.transport.listSessionShares(e).then(G=>{const oe=Array.isArray(G)?G:[];b(oe),S(oe)}).catch(()=>{b([]),S([])})},[t,e]);o.useEffect(()=>{U()},[U]);const B=async G=>{L(!0),C(null);try{await G(),c?.()}catch(oe){C(oe?.message||String(oe))}finally{L(!1)}},V=()=>B(async()=>{await t.transport.renameSession(e,f.trim())}),ce=G=>{const oe=G.trim().toLowerCase();if(!oe)return null;const be=N.find(pe=>pe.displayName&&pe.displayName.toLowerCase()===oe||pe.email&&pe.email.toLowerCase()===oe||pe.subject&&pe.subject.toLowerCase()===oe);return be||{provider:i?.provider||"dev",subject:G.trim(),email:null,displayName:null}},X=G=>`${G.provider}${G.subject}`,re=G=>{const oe=X(G);S(be=>[...be.filter(pe=>X(pe)!==oe),{provider:G.provider,subject:G.subject,email:G.email??null,displayName:G.displayName??null,access:v}]),x("")},T=()=>{const G=ce(E);G&&re(G)},j=G=>{const oe=X(G);S(be=>be.filter(pe=>X(pe)!==oe))},H=new Set(y.map(X)),W=p?.owner?`${p.owner.provider}${p.owner.subject}`:null,z=E.trim().toLowerCase(),Q=z?N.filter(G=>{const oe=X(G);return oe===W||H.has(oe)?!1:G.displayName&&G.displayName.toLowerCase().includes(z)||G.email&&G.email.toLowerCase().includes(z)||G.subject&&G.subject.toLowerCase().includes(z)}).slice(0,25):[],K=!!p?.canManage,Y=p?.visibility||"private",Z=new Set(y.map(G=>`${X(G)}:${G.access}`)),de=new Set(g.map(G=>`${X(G)}:${G.access}`)),ve=Z.size!==de.size||[...Z].some(G=>!de.has(G)),le=K&&(w!==Y||ve),st=()=>B(async()=>{w!==Y&&await t.transport.setSessionVisibility(e,w);const G=new Map(g.map(xe=>[X(xe),xe])),oe=new Map(y.map(xe=>[X(xe),xe]));for(const[xe,R]of oe){const F=G.get(xe);(!F||F.access!==R.access)&&await t.transport.grantSessionShare(e,{provider:R.provider,subject:R.subject,email:R.email??null,displayName:R.displayName??null},R.access)}for(const[xe,R]of G)oe.has(xe)||await t.transport.revokeSessionShare(e,{provider:R.provider,subject:R.subject});const be=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(be)&&(b(be),S(be));const pe=await t.transport.getSessionAccess(e).catch(()=>null);pe&&(m(pe),k(pe.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),ye=l||(()=>{a(),t.openSwitchModelPicker().catch(G=>{t.dispatch({type:"ui/status",text:G?.message||String(G)||"Failed to switch model"})})}),nt=n?r?`${n}:${r}`:n:"—",Ce=[{id:"general",label:"General"},...K?[{id:"access",label:"Access"}]:[]],Oe=Ce.some(G=>G.id===d)?d:"general",ut=typeof t.transport?.regenerateSession=="function",rt=G=>G.stopPropagation();return o.createElement("div",{className:"ps-share-overlay",onClick:a},o.createElement("div",{className:"ps-share-modal",onClick:rt},o.createElement("div",{className:"ps-share-modal-head"},o.createElement("span",null,"Manage session"),o.createElement("button",{className:"ps-modal-close",onClick:a,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-manage-tabs",role:"tablist"},Ce.map(G=>o.createElement("button",{key:G.id,type:"button",role:"tab","aria-selected":Oe===G.id?"true":"false",className:`ps-manage-tab${Oe===G.id?" is-active":""}`,onClick:()=>u(G.id)},G.label))),o.createElement("div",{className:"ps-share-modal-body"},Oe==="general"?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-share-section-label"},"Name"),o.createElement("div",{className:"ps-share-add-row"},o.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:f,disabled:D,onChange:G=>h(G.target.value),onKeyDown:G=>{G.key==="Enter"&&V()}}),o.createElement("button",{className:"ps-mini-button",disabled:D||!f.trim(),onClick:V},"Save")),o.createElement("div",{className:"ps-share-section-label"},"Model"),o.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),o.createElement("div",{className:"ps-share-add-row"},o.createElement("span",{className:"ps-manage-model-current"},nt),o.createElement("button",{className:"ps-mini-button",disabled:D,onClick:ye},"Switch model…")),ut?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-share-section-label"},"Context"),o.createElement("div",{className:"ps-share-section-sub"},"Rebuild this session's working context from its summary. The transcript is archived and the session keeps running — it is not a terminal action."),o.createElement("div",{className:"ps-share-add-row"},o.createElement("button",{className:"ps-mini-button ps-manage-regenerate",disabled:D,onClick:()=>{a(),t.handleCommand(M.REGENERATE_SESSION).catch(()=>{})}},o.createElement(ES),o.createElement("span",null,"Regenerate context…")))):null):null,Oe==="access"&&K?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-share-section-label"},"General access"),o.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(G=>o.createElement("label",{key:G,className:`ps-share-radio${w===G?" is-active":""}`},o.createElement("input",{type:"radio",name:"visibility",checked:w===G,disabled:D,onChange:()=>k(G)}),o.createElement("span",{className:"ps-share-radio-glyph"},Ha[G].glyph),o.createElement("span",null,Ha[G].label),o.createElement("span",{className:"ps-share-radio-hint"},G==="private"?"only you and admins":G==="shared_read"?"everyone here can view":"everyone here can view and send"))),o.createElement("div",{className:"ps-share-section-label"},"Special access"),o.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A grant can only raise someone's access above it, never lower it — to restrict everyone, lower the general level."),y.length===0?o.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(G=>o.createElement("div",{key:`${G.provider}/${G.subject}`,className:"ps-share-grant-row"},o.createElement("span",{className:"ps-share-grant-name"},G.displayName||G.subject),o.createElement("span",{className:"ps-share-grant-access"},`can ${G.access}`),o.createElement("button",{className:"ps-mini-button",disabled:D,onClick:()=>j(G)},"Remove"))),o.createElement("div",{className:"ps-share-add-wrap"},o.createElement("div",{className:"ps-share-add-row"},o.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:E,disabled:D,autoComplete:"off",onChange:G=>x(G.target.value),onKeyDown:G=>{G.key==="Enter"&&T()}}),o.createElement("select",{className:"ps-share-add-select",value:v,disabled:D,onChange:G=>P(G.target.value)},o.createElement("option",{value:"read"},"can read"),o.createElement("option",{value:"write"},"can write")),o.createElement("button",{className:"ps-mini-button",disabled:D||!E.trim(),onClick:T},"Add")),Q.length>0?o.createElement("div",{className:"ps-share-suggestions"},Q.map(G=>o.createElement("button",{key:`${G.provider}/${G.subject}`,type:"button",className:"ps-share-suggestion",disabled:D,onClick:()=>re(G)},o.createElement("span",{className:"ps-share-suggestion-name"},G.displayName||G.subject),G.email?o.createElement("span",{className:"ps-share-suggestion-email"},G.email):null))):null),o.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in.")):null),Oe==="access"&&K?o.createElement("div",{className:"ps-manage-apply-bar is-footer"},o.createElement("span",{className:"ps-share-section-sub"},le?"Unsaved access changes.":"No changes to apply."),o.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:D||!le,onClick:st},"Apply")):null,I?o.createElement("div",{className:"ps-share-error"},I):null))}function jr({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const r=ee(t,C=>C.ui.themeId),i=ft(r),a=ee(t,C=>{const U=C.sessions.activeSessionId,B=Mn(C),V=s||e?B.totalWidth:B.leftWidth,ce=Math.max(20,V-4);return{activeSessionId:U,activeHistory:U&&C.history.bySessionId.get(U)||null,activeOutbox:U&&C.outbox?.bySessionId?.[U]?C.outbox.bySessionId[U]:[],branding:C.branding,connection:C.connection,sessionsById:C.sessions.byId,sessionsFlat:C.sessions.flat,inspectorTab:C.ui.inspectorTab,activeSessionIsGroup:!!(U&&C.sessions.byId[U]?.isGroup),activeSessionStatus:U?String(C.sessions.byId[U]?.status||"").toLowerCase():"",focused:C.ui.focusRegion==="chat",scroll:C.ui.scroll.chat,authPrincipal:C.auth?.principal||null,contentWidth:ce}},Le),l=o.useMemo(()=>({branding:a.branding,connection:a.connection,auth:{principal:a.authPrincipal},sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById,flat:a.sessionsFlat},history:{bySessionId:a.activeSessionId&&a.activeHistory?new Map([[a.activeSessionId,a.activeHistory]]):new Map},outbox:{bySessionId:a.activeSessionId?{[a.activeSessionId]:a.activeOutbox}:{}},ui:{inspectorTab:a.inspectorTab}}),[a.activeHistory,a.activeSessionId,a.activeOutbox,a.authPrincipal,a.branding,a.connection,a.inspectorTab,a.sessionsById,a.sessionsFlat]),[c,d]=Kc(),u=c??a.contentWidth,p=o.useMemo(()=>mc(l,{width:u}),[l,u]),m=sl(!!p.animateTitleRight),f=o.useMemo(()=>nl(p.titleRight,p.animateTitleRight?m:""),[m,p.animateTitleRight,p.titleRight]),[h,g]=o.useState(!1),b=!!(a.activeHistory?.hasOlderEvents&&Number(a.activeHistory?.loadedEventCount||0)>=Or),y=o.useMemo(()=>mi(l,u,{tableMode:"sentinel"}),[l,u]),S=tl(a.activeSessionStatus==="running"),k=o.useMemo(()=>pi(l,{spinnerFrame:S,maxWidth:u}),[l,S,u]),E=o.useMemo(()=>gi(l,u,{tableMode:"sentinel"}),[l,u]),x=o.useMemo(()=>k.length>0?[...E,...k]:E,[E,k]),{access:v}=kS(t,a.activeSessionId,a.activeSessionIsGroup),P=ee(t,am,Le),N=n&&!a.activeSessionIsGroup,_=!!a.sessionsById?.[a.activeSessionId]?.serviceKind,D=_||!!v&&v.canWrite===!1,L=N?o.createElement("div",{className:"ps-chat-composer"},D?o.createElement("div",{className:"ps-composer-readonly"},_?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${v.owner?.displayName||v.owner?.email||"the owner"} for write access to participate.`):o.createElement(OS,{controller:t,mobile:e,active:!0})):null,I=!!(a.activeSessionId&&a.sessionsById[a.activeSessionId]);return P&&!I?o.createElement(At,{title:p.title,color:p.color,focused:a.focused,theme:i,className:"ps-chat-panel"},o.createElement("div",{className:"ps-empty-state ps-nav-error-state"},o.createElement("div",{className:"ps-nav-error-message"},P.message),P.retryable?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(P.sessionId)},"Retry"):null)):o.createElement(_n,{controller:t,title:e?xa(p.title,28):p.title,titleRight:e&&f?xa(f,18):f,actions:null,color:p.color,focused:a.focused,lines:y,bottomStickyLines:x,scrollOffset:a.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",panelRef:d,bottomContent:L,topContent:b?o.createElement("div",{className:"ps-load-older-bar"},o.createElement("button",{type:"button",className:"ps-load-older-button",disabled:h,onClick:()=>{g(!0),t.handleCommand(M.EXPAND_HISTORY).catch(()=>{}).finally(()=>g(!1))}},h?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:null})}function IS({controller:t,onClose:e}){const s=ee(t,g=>g.ui.themeId),n=ft(s),r=ee(t,g=>{const b=g.files.selectedArtifactId||"",y=b.indexOf("/");return{sessionId:y>0?b.slice(0,y):null,filename:y>0?b.slice(y+1):"",canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Le),i=ed(r.filename),a=ee(t,g=>g.files.htmlViewMode||"rendered"),l=ee(t,g=>!!g.files.htmlFitWidth),c=o.useCallback(g=>{t.dispatch({type:"files/htmlFitWidth",enabled:g})},[t]),d=o.useCallback(g=>{t.dispatch({type:"files/htmlViewMode",mode:g})},[t]),u=ee(t,g=>Number(g.files.htmlZoom)||1),p=o.useCallback(g=>{t.dispatch({type:"files/htmlZoom",zoom:g})},[t]),m=o.useCallback(g=>{t.stepArtifactPreview(g).catch(()=>{})},[t]),f=o.useCallback(g=>{if(!(g.metaKey||g.ctrlKey||g.altKey)){if(g.key==="ArrowLeft"||g.key==="["){g.preventDefault(),m(-1);return}if(g.key==="ArrowRight"||g.key==="]"){g.preventDefault(),m(1);return}g.key==="Escape"&&(g.preventDefault(),e())}},[e,m]),h=Tn(r.sessionId,r.filename);return o.createElement("section",{className:"ps-artifact-pane",onKeyDown:f,tabIndex:-1,role:"region","aria-label":`Artifact: ${r.filename||"none"}`},o.createElement("header",{className:"ps-artifact-pane-bar"},i.kind==="page"?o.createElement(cd,{mode:a,setMode:d}):null,i.kind==="page"&&a==="rendered"?o.createElement(ld,{fitWidth:l,setFitWidth:c}):null,i.kind==="page"&&a==="rendered"?o.createElement(kn,{zoom:u,setZoom:p}):null,o.createElement("span",{className:"ps-artifact-pane-heading"},o.createElement("span",{className:"ps-artifact-pane-name",title:r.filename},td(r.filename)||"Artifact"),o.createElement("span",{className:"ps-artifact-pane-type"},i.type)),o.createElement("span",{className:"ps-artifact-pane-actions"},o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canPrev,onClick:()=>m(-1),title:"Previous artifact (←)","aria-label":"Previous artifact"},"‹"),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canNext,onClick:()=>m(1),title:"Next artifact (→)","aria-label":"Next artifact"},"›"),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{h&&(Sn(h),t.dispatch({type:"ui/status",text:Gc}))},disabled:!h,title:"Copy a link that reopens this artifact","aria-label":"Copy link"},"🔗"),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.handleCommand(M.DOWNLOAD_SELECTED_FILE).catch(()=>{}),title:"Download","aria-label":"Download"},o.createElement(Sd)),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn is-close",onClick:e,title:"Close (Esc)","aria-label":"Close artifact"},"✕"))),o.createElement("div",{className:"ps-artifact-pane-body"},o.createElement(Rn,{controller:t,focused:!1,previewOnly:!0,chromeless:!0,theme:n})))}function AS({controller:t,visible:e=!0}){const[s,n]=o.useState(!1),r=o.useCallback(()=>n(i=>!i),[]);return o.useEffect(()=>{e||n(!1)},[e]),o.createElement("div",{className:`ps-mobile-canvas-layer${s?" is-maximized":""}${e?"":" is-hidden"}`,...e?{}:{inert:!0,"aria-hidden":"true"}},o.createElement(wd,{controller:t,mobile:!0,visible:e,focusOnPromote:!0,maximized:s,onToggleMaximized:r}))}function NS({controller:t}){const e=ee(t,a=>{const l=a.files.selectedArtifactId||"";return{filename:l?l.slice(l.indexOf("/")+1):"",origin:a.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Le),s=!!Oi(e.filename)||Fi(e.filename),[n,r]=o.useState(!1);o.useEffect(()=>{r(!1)},[e.filename]);const i=o.useCallback(a=>{t.stepArtifactPreview(a).catch(()=>{})},[t]);return o.createElement("div",{className:"ps-artifact-overlay"},o.createElement("header",{className:"ps-artifact-overlay-bar"},o.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",onClick:()=>t.closeArtifactPreview().catch(()=>{}),"aria-label":e.origin==="chat"?"Close, back to chat":"Close, back to artifacts"},"✕"),o.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?o.createElement("button",{type:"button",className:`ps-artifact-overlay-btn${n?" is-active":""}`,onClick:()=>r(a=>!a),"aria-label":n?"Wrap lines":"Show full lines",title:n?"Wrap to screen width":"Full line width (scroll horizontally)"},n?"⇥":"↔"):null,o.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>i(-1),"aria-label":"Previous artifact"},"‹"),o.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>i(1),"aria-label":"Next artifact"},"›")),o.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},o.createElement(Rn,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}const CS=140;function TS(t,e,s,n){let r=t;!t||Math.abs(e-t.width)>2?r={width:e,height:s}:s>t.height&&(r={width:t.width,height:s});const i=s<=r.height-CS;return{baseline:r,takeover:i&&n}}function PS(t){const[e,s]=o.useState(!1);return o.useEffect(()=>{if(!t||typeof window>"u"||!window.visualViewport){s(!1);return}const n=window.visualViewport;let r={width:n.width,height:n.height},i=0;const a=()=>{i=0;const c=!!document.activeElement?.classList?.contains("ps-prompt-input"),d=TS(r,n.width,n.height,c);r=d.baseline,s(d.takeover)},l=()=>{i||(i=requestAnimationFrame(a))};return a(),n.addEventListener("resize",l),window.addEventListener("focusin",l),window.addEventListener("focusout",l),()=>{i&&cancelAnimationFrame(i),n.removeEventListener("resize",l),window.removeEventListener("focusin",l),window.removeEventListener("focusout",l)}},[t]),t?e:!1}function MS({controller:t,layout:e="split"}){const s=o.createElement(Hr,{controller:t,panelClassName:"ps-mobile-session-pane"});return e==="chat"?o.createElement("div",{className:"ps-mobile-workspace is-chat-only"},o.createElement("div",{className:"ps-mobile-chat-pane"},o.createElement(jr,{controller:t,mobile:!0,fullWidth:!0}))):e==="sessions"?o.createElement("div",{className:"ps-mobile-workspace is-sessions-only"},o.createElement(Hr,{controller:t,panelClassName:"ps-mobile-session-pane",showDetailBox:!0})):o.createElement("div",{className:"ps-mobile-workspace"},s,o.createElement("div",{className:"ps-mobile-chat-pane"},o.createElement(jr,{controller:t,mobile:!0,fullWidth:!0})))}function vd(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:16,height:16,"aria-hidden":"true"},o.createElement("rect",{x:2.5,y:3.5,width:15,height:11,rx:1.5,...t}),o.createElement("path",{d:"M5.5 11.5l3-3.5 2.5 2.5 3.5-4",...t}),o.createElement("path",{d:"M7 17.5h6M10 14.5v3",...t}))}function Ga(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:20,height:20,"aria-hidden":"true"},o.createElement("path",{d:"M6.2 8.6a3.8 3.8 0 0 1 7.6 0v2.9a3.8 3.8 0 0 1-7.6 0z",...t}),o.createElement("path",{d:"M6.2 10.3h7.6",...t}),o.createElement("path",{d:"M7.6 6.5a2.4 2.4 0 0 1 4.8 0",...t}),o.createElement("path",{d:"M8 4.4 6.9 2.9M12 4.4l1.1-1.5",...t}),o.createElement("path",{d:"M6.3 8.6 3.8 7.4M6.2 10.6H3.6M6.3 12.6 3.8 13.9",...t}),o.createElement("path",{d:"M13.7 8.6 16.2 7.4M13.8 10.6h2.6M13.7 12.6l2.5 1.3",...t}))}function Wa({mark:t}){if(t!=="canvas"&&t!=="unseen")return null;const e=t==="unseen",s={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("span",{className:`ps-session-canvas-mark${e?" is-unseen":""}`,title:e?"Canvas updated since you last viewed it":"This session has a canvas","aria-label":e?"Canvas updated":"Has a canvas",role:"img"},o.createElement("svg",{viewBox:"0 0 16 16",width:12,height:12,"aria-hidden":"true"},o.createElement("rect",{x:1.6,y:2.6,width:12.8,height:9.2,rx:1.4,...s}),o.createElement("path",{d:"M6 14.4h4",...s}),e?o.createElement("circle",{cx:12.4,cy:4.6,r:2.4,fill:"currentColor",stroke:"none"}):null))}function za(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:14,height:14,"aria-hidden":"true"},o.createElement("path",{d:"M8.5 11.5l3-3",...t}),o.createElement("path",{d:"M7 13l-1.8 1.8a2.8 2.8 0 01-4-4l3-3a2.8 2.8 0 014 0",...t}),o.createElement("path",{d:"M13 7l1.8-1.8a2.8 2.8 0 014 4l-3 3a2.8 2.8 0 01-4 0",...t}))}const _S=[{id:"session",label:"Session access"},{id:"public",label:"Anyone with link"}];function RS({controller:t,sessionId:e,slot:s,onClose:n}){const[r,i]=o.useState(null),[a,l]=o.useState(null),[c,d]=o.useState(!1),[u,p]=o.useState(""),[m,f]=o.useState(""),[h,g]=o.useState("session"),[b,y]=o.useState(null),[S,w]=o.useState(null),k=t.transport,E=`${window.location.origin}/?session=${encodeURIComponent(e)}&view=canvas&slot=${s}&max=1`,x=(I,C)=>o.createElement(zc,{url:I,keyPrefix:C,copied:m,onCopy:_}),v=o.useCallback(()=>{k.getCanvasShareLink?.(e,s).then(I=>i(I||{exists:!1})).catch(I=>{i({exists:!1}),p(I?.message||String(I))}),typeof k.readCanvasKv=="function"&&k.readCanvasKv(e,s,{limit:1}).then(I=>{y(I?.policy||"owner"),w(I?.me||null)}).catch(()=>{y(null),w(null)})},[k,e,s]);o.useEffect(()=>{v()},[v]);const P=S?.relation==="owner"||S?.relation==="admin",N=I=>{d(!0),p(""),k.setCanvasKvAccess(e,s,I).then(()=>y(I)).catch(C=>p(C?.message||String(C))).finally(()=>d(!1))},_=(I,C)=>{navigator.clipboard?.writeText(C).then(()=>{f(I),window.setTimeout(()=>f(""),1500)}).catch(()=>p("Could not reach the clipboard — copy the link manually."))},D=I=>{d(!0),p(""),k.resetCanvasShareLink(e,s).then(({token:C})=>{l(`${window.location.origin}/?canvasShare=${encodeURIComponent(C)}`),i({exists:!0})}).catch(C=>p(C?.message||String(C))).finally(()=>d(!1))},L=()=>{d(!0),p(""),k.removeCanvasShareLink(e,s).then(()=>{l(null),i({exists:!1})}).catch(I=>p(I?.message||String(I))).finally(()=>d(!1))};return o.createElement("div",{className:"ps-canvas-share-overlay",onClick:n},o.createElement("div",{className:"ps-canvas-share-dialog",onClick:I=>I.stopPropagation(),role:"dialog","aria-label":"Share canvas"},o.createElement("div",{className:"ps-canvas-share-title"},"Share this canvas",o.createElement("button",{type:"button",className:"ps-mini-button",onClick:n,"aria-label":"Close"},"✕")),o.createElement("div",{className:"ps-manage-tabs",role:"tablist"},_S.map(I=>o.createElement("button",{key:I.id,type:"button",role:"tab","aria-selected":h===I.id?"true":"false",className:`ps-manage-tab${h===I.id?" is-active":""}`,onClick:()=>g(I.id)},I.label))),o.createElement("div",{className:"ps-canvas-share-panels"},o.createElement("div",{className:`ps-canvas-share-panel${h==="session"?" is-active":""}`,role:"tabpanel","aria-hidden":h==="session"?void 0:"true"},o.createElement("div",{className:"ps-canvas-share-sub"},"Opens the portal signed in, canvas full screen. Session visibility rules apply."),x(E,"session"),b!==null?o.createElement("div",{className:"ps-canvas-share-policy"},o.createElement("label",{className:"ps-canvas-share-sub",htmlFor:"ps-canvas-kv-policy"},"Who can edit inside this app"),o.createElement("select",{id:"ps-canvas-kv-policy",className:"ps-canvas-slot-select",value:b,disabled:c||!P,onChange:I=>N(I.target.value)},o.createElement("option",{value:"owner"},"Only people who can edit the session"),o.createElement("option",{value:"readers"},"Anyone who can open the session"),o.createElement("option",{value:"link"},"Anyone who can open the session, plus link viewers")),o.createElement("div",{className:"ps-canvas-share-sub"},b==="owner"?"You, admins, and anyone you shared the session with as “write”. People with view-only access can watch the app but not change anything in it.":b==="link"?"Your view-only people can edit inside the app. Anyone holding the share link can watch it — link holders can never edit.":"Adds your view-only people: they can edit inside the app. It does not let them message the agent."),P?null:o.createElement("div",{className:"ps-canvas-share-sub"},"Only the session owner or an admin can change this.")):null),o.createElement("div",{className:`ps-canvas-share-panel${h==="public"?" is-active":""}`,role:"tabpanel","aria-hidden":h==="public"?void 0:"true"},o.createElement("div",{className:"ps-canvas-share-sub"},"View only, live, no sign-in. One link at a time — resetting makes the previous link stop working immediately."),r===null?o.createElement("div",{className:"ps-canvas-share-sub"},"Checking…"):a?o.createElement(o.Fragment,null,x(a,"public"),o.createElement("div",{className:"ps-canvas-share-sub is-warn"},"Copy it now — the link is shown only this once.")):r.exists?o.createElement("div",{className:"ps-canvas-share-sub"},`A link exists${r.createdAt?` (created ${new Date(r.createdAt).toLocaleString()})`:""}. For safety it cannot be re-shown — Reset to get a new one.`):o.createElement("div",{className:"ps-canvas-share-sub"},"No public link yet."),o.createElement("div",{className:"ps-canvas-share-actions"},o.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:()=>D(r?.exists)},r?.exists?"Reset link":"Create link"),r?.exists?o.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:L},"Remove link"):null))),u?o.createElement("div",{className:"ps-canvas-share-error"},u):null))}function gr({controller:t,view:e,compact:s=!1}){const n=Array.isArray(e.slots)?e.slots:[];if(n.length<=1)return null;const r=n.map(c=>c.slot),i=Math.max(0,r.indexOf(e.slot)),a=c=>{const d=r[(i+c+r.length)%r.length];t.dispatch({type:"ui/canvasSlot",slot:d})},l=c=>(c.name?c.name:`canvas ${c.slot}`)+(c.unseen?" •":"");return o.createElement("span",{className:`ps-canvas-slot-controls${s?" is-compact":""}`},o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>a(-1),title:"Previous canvas","aria-label":"Previous canvas"},"‹"),o.createElement("select",{className:"ps-canvas-slot-select",value:e.slot,onChange:c=>t.dispatch({type:"ui/canvasSlot",slot:Number(c.target.value)}),"aria-label":"Choose canvas",title:"Choose canvas"},n.map(c=>o.createElement("option",{key:c.slot,value:c.slot},l(c)))),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>a(1),title:"Next canvas","aria-label":"Next canvas"},"›"))}function qa(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,"aria-hidden":"true"},o.createElement("rect",{x:2.2,y:3.4,width:3.6,height:13.2,rx:1,...t}),o.createElement("rect",{x:8.2,y:3.4,width:9.6,height:13.2,rx:1,...t}))}function Ka(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},o.createElement("path",{d:"M8 3H3v5M12 3h5v5M12 17h5v-5M8 17H3v-5",...t}))}function Va(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return o.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},o.createElement("path",{d:"M3 8h5V3M17 8h-5V3M17 12h-5v5M3 12h5v5",...t}))}function $S({controller:t,sessionId:e,slot:s=1,latestRev:n,zoom:r,visible:i=!0,focusOnPromote:a=!1,dataRev:l=0,dataPayload:c=null,dataPatch:d=null}){const[u,p]=o.useState(null),[m,f]=o.useState(null),[h,g]=o.useState(null),[b,y]=o.useState(0),S=o.useRef({live:null,staging:null}),w=o.useRef({rev:0,used:!1}),k=o.useRef(null),E=o.useRef(null),x=o.useRef(null),v=dd(k),P=o.useRef(null),N=o.useRef(r);N.current=r;const _=o.useRef(i);_.current=i,o.useEffect(()=>{if(!t||!e)return;const I=C=>{const U=E.current,B=C.data;if(!B||typeof B!="object"||!C.source)return;const V=!!(U&&C.source===U.contentWindow),ce=!!(x.current&&C.source===x.current.contentWindow);if(!(!V&&!ce)){if(B.type==="canvas-action"){if(!V)return;t.submitCanvasAction(e,B).then(X=>{X&&X.ok===!1&&typeof console<"u"&&console.warn(`canvas action rejected: ${X.reason}`)}).catch(()=>{});return}if(B.type==="canvas-kv"){const X=B.id,re=t.transport,T=C.source,j=z=>{try{T.postMessage(z,"*")}catch{}},H=(z,Q="ERROR")=>j({type:"canvas-kv-result",id:X,ok:!1,error:String(z?.message||z||"failed"),code:z?.code||Q});if(typeof re?.readCanvasKv!="function"){H("the canvas KV store is not available on this deployment","UNAVAILABLE");return}const W=String(B.op||"");if(!V&&(W==="put"||W==="delete")){H("the canvas is still loading; retry the write in a moment","NOT_READY");return}if(W==="ready"||W==="list"){re.readCanvasKv(e,s,{prefix:B.prefix??null,limit:B.limit??null,after:B.after??null}).then(z=>j({type:W==="ready"?"canvas-kv-ready":"canvas-kv-result",id:X,ok:!0,entries:z?.entries??[],nextAfter:z?.nextAfter??null,me:z?.me??null,canWrite:!!z?.me?.canWrite,policy:z?.policy??"owner"})).catch(H);return}if(W==="get"){re.readCanvasKv(e,s,{key:B.key}).then(z=>j({type:"canvas-kv-result",id:X,ok:!0,entry:z?.entries?.[0]??null})).catch(H);return}if(W==="put"||W==="delete"){const z=W==="put"?{op:"put",key:B.key,value:B.value,...B.ifMatch!=null?{ifMatch:B.ifMatch}:{}}:{op:"delete",key:B.key,...B.ifMatch!=null?{ifMatch:B.ifMatch}:{}};re.writeCanvasKv(e,s,[z]).then(Q=>{const K=Q?.results?.[0]??{ok:!1,error:"no result"};j({type:"canvas-kv-result",id:X,ok:!!K.ok,key:K.key,rev:K.rev,capped:K.capped,error:K.error,code:K.code})}).catch(H);return}H(`unknown canvas-kv op ${W}`,"INVALID_REQUEST")}}};return window.addEventListener("message",I),()=>window.removeEventListener("message",I)},[t,e,s]),o.useEffect(()=>{if(!(!t||!e||typeof t.subscribeCanvasKv!="function"))return t.subscribeCanvasKv(e,I=>{if(!I||Number(I.slot)!==Number(s))return;const C=E.current?.contentWindow;if(!C)return;const U=B=>{try{C.postMessage({type:"canvas-kv-change",key:I.key,rev:I.rev,op:I.op,...B?{v:B.v,by:B.by,at:B.at}:{}},"*")}catch{}};if(I.op==="delete"){U(null);return}if(I.value&&typeof I.value=="object"){U({v:I.value.v,by:I.value.by,at:I.value.at});return}t.transport?.readCanvasKv?.(e,s,{key:I.key}).then(B=>U(B?.entries?.[0]??null)).catch(()=>{})})},[t,e,s]),o.useEffect(()=>{if(!t||!e||!n)return;let I=!1,C=null;return ud(t,e,s<=1?"canvas.html":`canvas${s}.html`).then(U=>{if(I){URL.revokeObjectURL(U);return}S.current.staging&&S.current.staging!==S.current.live&&URL.revokeObjectURL(S.current.staging),S.current.staging=U,g(null),f({url:U,rev:n})}).catch(()=>{if(!I){if(w.current.rev!==n&&(w.current={rev:n,used:!1}),!w.current.used){w.current.used=!0,C=setTimeout(()=>{I||y(U=>U+1)},1500);return}g({rev:n})}}),()=>{I=!0,C&&clearTimeout(C)}},[t,e,s,n,b]),o.useEffect(()=>()=>{S.current.staging&&S.current.staging!==S.current.live&&URL.revokeObjectURL(S.current.staging),S.current.live&&URL.revokeObjectURL(S.current.live),S.current={live:null,staging:null},p(null),f(null),g(null)},[e]);const D=o.useCallback(I=>{if(!I||S.current.staging!==I.url)return;const C=S.current.live;S.current.live=I.url,S.current.staging=null,C&&C!==I.url&&URL.revokeObjectURL(C),p(I),f(B=>B&&B.url===I.url?null:B);const U=k.current;if(U){const B=U.getBoundingClientRect(),V=N.current||1;P.current={w:Math.round(B.width/V),h:Math.round(B.height/V)}}if(t&&e&&_.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:I.rev}),a&&_.current)try{E.current?.focus({preventScroll:!0})}catch{}},[t,e,a]);o.useEffect(()=>{if(!(!u||!l||c===null)){try{E.current?.contentWindow?.postMessage({type:"canvas-data",data:c,dataRev:l},"*"),d&&E.current?.contentWindow?.postMessage({type:"canvas-patch",patch:d,dataRev:l},"*")}catch{}t&&e&&_.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,dataRev:l})}},[u,l,c,d,t,e]),o.useEffect(()=>{if(i&&u&&t&&e&&(t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:u.rev,...l?{dataRev:l}:{}}),a))try{E.current?.focus({preventScroll:!0})}catch{}},[i,u,t,e,a,l]),o.useEffect(()=>{if(!u||!i)return;const I=r||1,C=Math.round((v.width||0)/I),U=Math.round((v.height||0)/I);if(!C||!U)return;const B=P.current;if(B){if(!(B.w<220||B.h<170))return;const X=Math.abs(B.w-C),re=Math.abs(B.h-U);if(X<=2&&re<=2||X<=2&&re/Math.max(1,B.h)<.15)return}const V=setTimeout(()=>{P.current={w:C,h:U},y(ce=>ce+1)},350);return()=>clearTimeout(V)},[v.width,v.height,r,u,i]);const L=r!==1&&v.width>0?{flex:"none",width:`${Math.max(1,Math.round(v.width/r))}px`,height:`${Math.max(1,Math.round(v.height/r))}px`,transform:`scale(${r})`,transformOrigin:"top left"}:void 0;return o.createElement("div",{ref:k,className:"ps-html-preview-host is-fitting"},[u,m].filter(Boolean).map(I=>o.createElement("iframe",{key:`canvas:${I.rev}:${I.url}`,ref:I===u?(C=>{E.current=C}):(C=>{x.current=C}),className:`ps-html-preview-frame${I===u?"":" is-staging"}`,style:L,src:I.url,title:"Session canvas",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:I===m?()=>D(I):void 0})),h?o.createElement("div",{className:"ps-canvas-load-error"},o.createElement("span",null,u?`Couldn't load rev ${h.rev} — showing rev ${u.rev}.`:`Couldn't load rev ${h.rev}.`),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{w.current={rev:0,used:!1},g(null),y(I=>I+1)}},"Retry")):null)}const LS=160;function wd({controller:t,mobile:e=!1,visible:s=!0,focusOnPromote:n=!1,maximized:r=!1,onToggleMaximized:i=null}){const a=ee(t,fi,Le),l=ee(t,b=>Number(b.files.htmlZoom)||1),c=o.useCallback(b=>{t.dispatch({type:"files/htmlZoom",zoom:b})},[t]);o.useEffect(()=>{if(!s||!a.sessionId)return;const b=setTimeout(()=>{t.ensureCanvasSnapshot(a.sessionId).catch(()=>{})},LS);return()=>clearTimeout(b)},[t,a.sessionId,s]);const d=ee(t,b=>b?.ui?.canvasZen===!0),[u,p]=o.useState(!1),[m,f]=o.useState(null);o.useEffect(()=>{if(!r){f(null);return}let b=0;const y=()=>{const S=document.getElementById("ps-toolbar-canvas-slot");S?f(S):b=requestAnimationFrame(y)};return y(),()=>cancelAnimationFrame(b)},[r]),o.useCallback(()=>{t.dispatch({type:"ui/canvasOpen",open:!1,sessionId:a.sessionId,manual:!0})},[t,a.sessionId]);const h=e&&(a.exists||r),g=e?h?o.createElement("header",{className:"ps-artifact-pane-bar is-rev-strip"},o.createElement("span",{className:"ps-artifact-pane-type",title:a.note||void 0},a.exists?`${a.name?`${a.name} · `:""}rev ${a.latestRev}`:""),o.createElement(gr,{controller:t,view:a,compact:!0}),a.exists?o.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:()=>p(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},o.createElement(za)):null,i?o.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:i,title:r?"Back to the inset canvas":"Maximize — cover the whole screen","aria-label":r?"Restore canvas":"Maximize canvas"},o.createElement(r?Va:Ka)):null):null:r?m?Wr.createPortal(o.createElement(o.Fragment,null,a.exists?o.createElement("span",{className:"ps-toolbar-canvas-rev"},`${a.name?`${a.name} · `:""}rev ${a.latestRev}`):null,o.createElement(gr,{controller:t,view:a,compact:!0}),a.exists?o.createElement(kn,{zoom:l,setZoom:c}):null,o.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>{t.dispatch({type:"ui/canvasMaximized",on:!1}),t.dispatch({type:"ui/canvasZen",on:!d})},title:d?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":d?"Leave zen mode":"Zen mode"},o.createElement(qa)),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn ps-toolbar-canvas-restore",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!1}),title:"Back to the workspace","aria-label":"Restore canvas"},o.createElement(Va))),m):null:o.createElement("header",{className:"ps-artifact-pane-bar"},o.createElement("span",{className:"ps-artifact-pane-heading"},o.createElement("span",{className:"ps-artifact-pane-name ps-canvas-pane-glyph",title:a.note||"Canvas"},o.createElement(vd)),a.exists?o.createElement("span",{className:"ps-artifact-pane-type",title:a.note||void 0},`${a.name?`${a.name} · `:""}rev ${a.latestRev}`):null,o.createElement(gr,{controller:t,view:a})),o.createElement("span",{className:"ps-artifact-pane-actions"},a.exists?o.createElement(kn,{zoom:l,setZoom:c}):null,a.exists?o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>p(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},o.createElement(za)):null,o.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>t.dispatch({type:"ui/canvasZen"}),title:d?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":d?"Leave zen mode":"Zen mode"},o.createElement(qa)),o.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!0}),title:"Full screen — hide chat and sessions","aria-label":"Full screen canvas"},o.createElement(Ka))));return o.createElement("section",{className:"ps-artifact-pane ps-canvas-pane",role:"region","aria-label":"Session canvas"},g,o.createElement("div",{className:"ps-artifact-pane-body"},a.exists?o.createElement($S,{key:`slot:${a.slot}`,controller:t,sessionId:a.sessionId,slot:a.slot,latestRev:a.latestRev,zoom:l,visible:s,focusOnPromote:n,dataRev:a.latestDataRev,dataPayload:a.dataPayload,dataPatch:a.dataPatch}):o.createElement("div",{className:"ps-canvas-blank"},o.createElement("p",{className:"ps-canvas-blank-title"},"Nothing on the canvas yet."),o.createElement("p",null,"Ask the agent to draw — a dashboard, a chart, a diagram — or it will draw when it has something worth showing."))),u&&a.exists?o.createElement(RS,{controller:t,sessionId:a.sessionId,slot:a.slot,onClose:()=>p(!1)}):null)}function Ed({activeTab:t,controller:e}){const s=o.useMemo(()=>Mi(e),[e]);return o.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>o.createElement(he,{key:n,icon:wa[n]?o.createElement(wa[n]):"•",label:vy[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Rn({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:r=!1,chromeless:i=!1}){const a=ee(t,C=>C.ui.themeId),l=ft(a),c=o.useRef(null),d=ee(t,C=>{const U=C.sessions.activeSessionId,B=Mn(C),V=s||C.files.fullscreen?C.ui.layout?.viewportWidth??120:B.rightWidth;return{activeSessionId:U,sessionsById:C.sessions.byId,sessionsFlat:C.sessions.flat,filesBySessionId:C.files.bySessionId,filesFilter:C.files.filter,selectedArtifactId:C.files.selectedArtifactId,markedIds:C.files.markedIds||[],previewOrigin:C.files.previewOrigin||null,focused:e,previewScroll:C.ui.scroll.filePreview,fullscreen:!!C.files.fullscreen,contentWidth:Math.max(20,V-4),canBrowserUpload:Ey(t),canPathUpload:ky(t),canDeleteArtifacts:Iy(t),canOpenLocally:Ay(t)}},Le),u=o.useMemo(()=>({sessions:{activeSessionId:d.activeSessionId,byId:d.sessionsById,flat:d.sessionsFlat},files:{bySessionId:d.filesBySessionId,selectedArtifactId:d.selectedArtifactId,filter:d.filesFilter,fullscreen:d.fullscreen},ui:{scroll:{filePreview:d.previewScroll}}}),[d.activeSessionId,d.filesBySessionId,d.filesFilter,d.fullscreen,d.previewScroll,d.selectedArtifactId,d.sessionsById,d.sessionsFlat]),p=o.useMemo(()=>Si(u,{listWidth:Math.max(18,d.contentWidth-4),previewWidth:Math.max(18,d.contentWidth-4),showHints:!1}),[u,d.contentWidth]),m=o.useMemo(()=>Rt(u),[u]),f=m.length>0,h=o.useCallback(C=>{const U=Array.isArray(C)?C.filter(Boolean):[];U.length!==0&&t.uploadArtifactFiles(U).catch(()=>{})},[t]),g=o.useCallback(()=>{if(d.canBrowserUpload&&c.current){c.current.click();return}d.canPathUpload&&t.handleCommand(M.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,d.canBrowserUpload,d.canPathUpload]),b=o.useMemo(()=>new Set(d.markedIds||[]),[d.markedIds]),y=o.createElement(o.Fragment,null,b.size>0?o.createElement(o.Fragment,null,o.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",opacity:.85},title:"Cmd/Ctrl-click to mark, Shift-click for a range"},`${b.size} marked`),d.canDeleteArtifacts?o.createElement(he,{icon:o.createElement(Ur),label:`Delete ${b.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,o.createElement(he,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,o.createElement("input",{ref:c,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:C=>{h(Array.from(C.currentTarget.files||[])),C.currentTarget.value=""}}),o.createElement(he,{icon:o.createElement(dS),label:"Upload",onClick:g,disabled:!d.canBrowserUpload&&!d.canPathUpload}),o.createElement(he,{icon:o.createElement(Sd),label:"Download",onClick:()=>t.handleCommand(M.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),o.createElement(he,{icon:"🔗",label:"Copy link to this artifact",onClick:()=>{const C=Tn(p.selectedSessionId,p.selectedFilename);C&&(Sn(C),t.dispatch({type:"ui/status",text:Gc}))},disabled:!f||!p.selectedFilename}),d.canDeleteArtifacts?o.createElement(he,{icon:o.createElement(Ur),label:"Delete",onClick:()=>t.handleCommand(M.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,d.canOpenLocally?o.createElement(he,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(M.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,o.createElement(he,{icon:o.createElement(Ui),label:"Filter",onClick:()=>t.handleCommand(M.OPEN_FILES_FILTER).catch(()=>{})}),o.createElement(he,{icon:o.createElement(d.fullscreen?oS:iS),label:d.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(M.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),S=o.useRef(null);o.useEffect(()=>{const C=S.current;C&&typeof C.scrollIntoView=="function"&&C.scrollIntoView({block:"nearest"})},[p.selectedIndex,d.selectedArtifactId]);const w=m.length===0?je(p.listBodyLines||[]).map((C,U)=>o.createElement(We,{key:`empty:${U}`,line:C,theme:l})):m.map((C,U)=>o.createElement("button",{key:C.id,type:"button",ref:U===p.selectedIndex?S:null,className:`ps-list-button${U===p.selectedIndex?" is-selected":""}`+(b.has(C.id)?" is-marked":""),onClick:B=>{if(t.setFocus("inspector"),B.metaKey||B.ctrlKey){t.toggleArtifactMark(C);return}if(B.shiftKey){t.markArtifactRange(C);return}t.clearArtifactMarks(),t.selectFileBrowserItem(C).then(()=>{s&&t.handleCommand(M.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},o.createElement(We,{line:je([p.listBodyLines?.[U]])[0],theme:l}))),k=!p.previewLoading&&!p.previewError,E=k&&Fi(p.selectedFilename,p.previewContentType)&&!p.previewIsBinary&&!!p.previewContent,x=k&&($i.test(String(p.previewContentType||""))||Li.test(String(p.selectedFilename||""))),v=k&&!p.previewIsBinary&&!E&&p.previewRenderMode!=="markdown"&&p.previewContent?Oi(p.selectedFilename):null,P=n?"activity":null,N=r?null:"filePreview",_=k&&!p.previewIsBinary&&Qc(p.selectedFilename,p.previewContentType)&&!!p.previewContent,L=k&&!p.previewIsBinary&&Xc(p.selectedFilename,p.previewContentType)?o.createElement(xb,{controller:t,sessionId:p.selectedSessionId,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,theme:l,color:"cyan",focused:!1,title:null,chromeless:i}):_?o.createElement(pr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:N,scrollOffset:d.previewScroll,className:"ps-csv-preview",focusRegion:P},o.createElement(rb,{content:p.previewContent,filename:p.selectedFilename})):x?o.createElement(Ma,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):v?o.createElement(pr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:N,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:P},o.createElement("pre",{className:"ps-md-code-pre"},o.createElement("code",null,us(p.previewContent,v,l)))):E?o.createElement(pr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:N,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:P},o.createElement("pre",{className:"ps-md-code-pre is-diff"},o.createElement("code",null,Di(p.previewContent,l)))):p.previewRenderMode==="markdown"&&!p.previewLoading&&!p.previewError?o.createElement(vb,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:d.previewScroll,paneKey:N,theme:l,focusRegion:P,content:eb(p.previewContent||"")}):p.previewIsBinary&&!p.previewLoading&&!p.previewError?o.createElement(Ma,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):o.createElement(_n,{controller:t,title:null,color:"cyan",focused:!1,lines:p.previewLines,scrollOffset:d.previewScroll,scrollMode:"top",paneKey:N,focusRegion:P,className:"is-preview is-wrapped"}),I=d;return n?L:o.createElement(At,{title:I.fullscreen?p.fullscreenTitle:s&&p.panelTitleMobile?p.panelTitleMobile:p.panelTitle,color:"magenta",focused:I.focused,actions:y,theme:l},o.createElement(Ed,{activeTab:"files",controller:t}),I.fullscreen?L:o.createElement("div",{className:"ps-files-grid is-list-only"},o.createElement("div",{className:"ps-action-list ps-files-list"},w)))}function xs({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const r=ee(t,b=>{const y=Mn(b),S=b.ui.inspectorTab,w=e?b.ui.layout?.viewportWidth??120:y.rightWidth;return{inspectorTab:S,statsViewMode:b.ui.statsViewMode,adminWorkers:b.admin?.workers,nodeMapSelectedNode:b.ui.nodeMapSelectedNode,activeSessionId:b.sessions.activeSessionId,sessionsById:b.sessions.byId,sessionsFlat:b.sessions.flat,historyBySessionId:b.history.bySessionId,sessionStats:b.sessionStats,fleetStats:b.fleetStats,connection:b.connection,orchestrationBySessionId:b.orchestration.bySessionId,executionHistoryBySessionId:b.executionHistory?.bySessionId||{},executionHistoryFormat:b.executionHistory?.format||"pretty",logs:b.logs,files:b.files,focused:b.ui.focusRegion==="inspector",scroll:b.ui.scroll.inspector,followBottom:b.ui.followBottom?.inspector!==!1,logsTailing:b.logs.tailing,filesFullscreen:!!b.files.fullscreen,contentWidth:Fy(w,S,e)}},Le),i=o.useMemo(()=>({sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},history:{bySessionId:r.historyBySessionId},sessionStats:r.sessionStats,fleetStats:r.fleetStats,connection:r.connection,admin:{workers:r.adminWorkers},ui:{inspectorTab:r.inspectorTab,statsViewMode:r.statsViewMode,nodeMapSelectedNode:r.nodeMapSelectedNode,scroll:{inspector:r.scroll}},logs:r.logs,files:r.files,orchestration:{bySessionId:r.orchestrationBySessionId},executionHistory:{bySessionId:r.executionHistoryBySessionId,format:r.executionHistoryFormat}}),[r.activeSessionId,r.adminWorkers,r.connection,r.executionHistoryBySessionId,r.executionHistoryFormat,r.fleetStats,r.nodeMapSelectedNode,r.files,r.historyBySessionId,r.inspectorTab,r.sessionStats,r.statsViewMode,r.logs,r.orchestrationBySessionId,r.scroll,r.sessionsById,r.sessionsFlat]),[a,l]=Kc(),c=a??r.contentWidth,d=o.useMemo(()=>It(i,{width:c}),[i,c]),u=o.useMemo(()=>{const b=r.activeSessionId&&r.historyBySessionId?.get(r.activeSessionId)||null,y=new Map;for(const S of b?.events||[]){if(S?.eventType!=="session.turn_completed")continue;const w=Number(S?.data?.turnIndex??S?.data?.iteration);Number.isFinite(w)&&y.set(w,S)}return y},[r.activeSessionId,r.historyBySessionId]),p=o.useCallback((b,y)=>o.createElement(Fb,{lines:b,theme:y,completionByTurn:u}),[u]),m=o.useCallback((b,y)=>o.createElement(Ob,{lines:b,theme:y,controller:t}),[t]);o.useEffect(()=>{if(r.inspectorTab!=="nodes")return;t.ensureInspectorData("nodes");const b=window.setInterval(()=>{t.ensureInspectorData("nodes")},1e4);return()=>window.clearInterval(b)},[t,r.inspectorTab]);const f=o.useRef(null);if(o.useEffect(()=>{if(e)return f.current=requestAnimationFrame(()=>{try{const b=document.querySelector(".ps-mobile-pane-fill .ps-inspector-pane .ps-scroll-panel"),y=b?b.querySelector(".ps-line"):null;if(!b||!y)return;const S=window.getComputedStyle(y),w=document.createElement("span");w.style.cssText="position:absolute;visibility:hidden;white-space:pre;",w.style.fontFamily=S.fontFamily,w.style.fontSize=S.fontSize,w.style.fontWeight=S.fontWeight,w.style.letterSpacing=S.letterSpacing,w.textContent="0".repeat(100),y.parentElement.appendChild(w);const k=w.getBoundingClientRect().width/100||8;w.remove();const E=window.getComputedStyle(b),x=b.clientWidth-(parseFloat(E.paddingLeft)||0)-(parseFloat(E.paddingRight)||0);if(!(x>50))return;const P=Math.floor(x/k)+6,N=t.getState().ui.layout?.viewportWidth??120;if(Math.abs(P-N)<=2)return;t.dispatch({type:"ui/viewport",width:P,height:null})}catch{}}),()=>{f.current&&cancelAnimationFrame(f.current)}},[t,e,r.inspectorTab,r.activeSessionId]),r.inspectorTab==="files"&&!d.disabled)return o.createElement(Rn,{controller:t,focused:r.focused,mobile:e});const h=[];if(r.inspectorTab==="logs")h.push(o.createElement(he,{key:"tail",icon:r.logsTailing?"■":"⇣",label:r.logsTailing?"Stop tailing":"Tail (follow)",active:r.logsTailing,onClick:()=>t.handleCommand(M.TOGGLE_LOG_TAIL).catch(()=>{})})),h.push(o.createElement(he,{key:"filter",icon:o.createElement(Ui),label:"Filter",onClick:()=>t.handleCommand(M.OPEN_LOG_FILTER).catch(()=>{})}));else if(r.inspectorTab==="history")h.push(o.createElement(he,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(M.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),h.push(o.createElement(he,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(M.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(r.inspectorTab==="stats"){const b={session:"◉",fleet:"⬢",users:"⚇"};for(const y of["session","fleet","users"])h.push(o.createElement(he,{key:`stats-view:${y}`,icon:b[y],label:`${y.replace(/^./u,S=>S.toUpperCase())} stats`,active:r.statsViewMode===y,onClick:()=>t.setStatsViewMode(y)}))}const g=n?h.concat(n):h;return o.createElement(_n,{controller:t,title:d.title,color:"magenta",focused:r.focused,actions:g,topContent:o.createElement(Ed,{activeTab:d.activeTab,controller:t}),stickyLines:d.stickyLines||[],lines:d.lines,renderBody:d.activeTab==="sequence"?p:d.activeTab==="nodes"?m:null,scrollOffset:r.scroll,scrollMode:d.activeTab==="sequence"||d.activeTab==="logs"&&r.followBottom?"bottom":"top",stickyBottom:d.activeTab==="logs",paneKey:"inspector",panelRef:l,className:d.activeTab==="history"||d.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${d.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function yr({controller:t,panelClassName:e="",extraActions:s=null}){const n=ee(t,l=>{const c=l.sessions.activeSessionId,d=Mn(l),u=Math.max(3,d.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&l.sessions.byId[c]||null,activeHistory:c&&l.history.bySessionId.get(c)||null,focused:l.ui.focusRegion==="activity",scroll:l.ui.scroll.activity,followBottom:l.ui.followBottom?.activity!==!1,maxLines:u,nodeMapSelectedNode:l.ui.nodeMapSelectedNode,adminWorkers:l.admin?.workers,branding:l.branding,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,historyBySessionId:l.history.bySessionId,inspectorTab:l.ui.inspectorTab}},Le),r=n.inspectorTab==="nodes",i=o.useMemo(()=>({branding:n.branding,admin:{workers:n.adminWorkers},ui:{nodeMapSelectedNode:n.nodeMapSelectedNode},sessions:{activeSessionId:n.activeSessionId,byId:r?n.sessionsById:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{},flat:n.sessionsFlat},history:{bySessionId:r?n.historyBySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[r,n.activeHistory,n.activeSession,n.activeSessionId,n.adminWorkers,n.branding,n.historyBySessionId,n.nodeMapSelectedNode,n.sessionsById,n.sessionsFlat]),a=o.useMemo(()=>r?fc(i):bi(i,n.maxLines),[r,i,n.maxLines]);return o.createElement(_n,{controller:t,title:a.title,color:"gray",focused:n.focused,actions:s,lines:a.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:`ps-activity-pane${e?` ${e}`:""}`})}const Ya=Object.freeze([]);function Xa(t){const e=Number(t)||0;return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function OS({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const r=ee(t,v=>{const P=v.sessions.activeSessionId,N=P&&v.sessions.byId[P]||null,_=P&&v.outbox?.bySessionId?.[P]?v.outbox.bySessionId[P]:[];return{value:v.ui.prompt,cursor:v.ui.promptCursor,focused:v.ui.focusRegion==="prompt",modalOpen:!!v.ui.modal,answerMode:!!N?.pendingQuestion?.question,canStopTurn:ac(N),hasOutbox:_.length>0,hasPendingOutbox:_.some(D=>D?.phase==="pending"),pendingCount:_.filter(D=>D?.phase==="pending").length,editingPending:v.ui.promptEdit?.sessionId===P,selectedOutboxPhase:v.ui.promptEdit?.sessionId===P&&v.ui.promptEdit?.phase||null,promptAttachments:v.ui.promptAttachments||Ya}},Le),i=o.useRef(null),a=o.useRef(null),[l,c]=o.useState(!1),d=o.useCallback(()=>{const v=i.current;v&&(v.style.height="0px",v.style.height=`${v.scrollHeight+2}px`)},[]);o.useLayoutEffect(()=>{d()},[d,r.value]),o.useEffect(()=>(window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)),[d]);const u=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",p=u?r.promptAttachments.filter(v=>v?.kind==="image"):Ya,m=o.useRef(new Map);o.useEffect(()=>{const v=m.current,P=new Set(p.map(N=>N.file));for(const[N,_]of v)P.has(N)||(URL.revokeObjectURL(_),v.delete(N));for(const N of p)if(N.file&&!v.has(N.file))try{v.set(N.file,URL.createObjectURL(N.file))}catch{}},[p]),o.useEffect(()=>()=>{for(const v of m.current.values())URL.revokeObjectURL(v);m.current.clear()},[]);const f=o.useCallback(v=>{if(!u)return 0;const P=Array.from(v||[]).filter(_=>_&&typeof _.type=="string"&&_.type.startsWith("image/"));return P.length===0?0:t.addPendingImageFiles(P)?.accepted||0},[t,u]);o.useEffect(()=>{const v=i.current;if(!(!s||r.modalOpen||!r.focused||!v)){if(document.activeElement!==v){if(e)return;try{v.focus({preventScroll:!0})}catch{v.focus()}}v.value===r.value&&v.selectionStart!==r.cursor&&v.setSelectionRange(r.cursor,r.cursor)}},[s,e,r.cursor,r.value,r.focused,r.modalOpen]);const h=o.useCallback(()=>{t.handleCommand(M.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[g,b]=o.useState(!1),y=o.useCallback(()=>{b(!0),t.handleCommand(M.STOP_TURN).catch(()=>{}).finally(()=>b(!1))},[t]),S=o.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),w=r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"⇪":r.hasOutbox?"+":"❯",k=r.selectedOutboxPhase==="queued",E=r.selectedOutboxPhase==="cancelling",x=k||E;return o.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${l?" is-drag-over":""}`,...u?{onDragOver:v=>{v.dataTransfer?.types?.includes?.("Files")&&(v.preventDefault(),c(!0))},onDragLeave:v=>{v.currentTarget.contains(v.relatedTarget)||c(!1)},onDrop:v=>{c(!1),v.dataTransfer?.files?.length&&(v.preventDefault(),f(v.dataTransfer.files))}}:{}},p.length>0?o.createElement("div",{className:"ps-prompt-attachments"},p.map((v,P)=>{const N=v.file?m.current.get(v.file):null;return o.createElement("div",{key:`attach:${P}:${v.filename}`,className:"ps-attach-chip",title:`${v.filename} · ${Xa(v.sizeBytes)}`},N?o.createElement("img",{className:"ps-attach-thumb",src:N,alt:v.filename}):o.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),o.createElement("div",{className:"ps-attach-size"},Xa(v.sizeBytes)),o.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${v.filename}`,"aria-label":`Remove attachment ${v.filename}`,onClick:()=>t.removePendingImageAttachment(P)},"✕"))})):null,(()=>{const v=r.answerMode?"answer":E?"cancelling":k?"queued":r.editingPending?"pending":"you";return o.createElement("label",{className:`ps-prompt-label${v==="you"?" is-default":""}`},v)})(),o.createElement("textarea",{ref:i,className:"ps-prompt-input",rows:1,value:r.value,readOnly:x,placeholder:r.answerMode?"Type an answer and press Enter":r.editingPending?E?"Cancellation requested":k?"Queued message selected":"Edit the pending message, then send or cancel it":r.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:e?"enter":"send",onFocus:()=>t.setFocus("prompt"),onSelect:v=>t.setPromptCursor(v.currentTarget.selectionStart||0),onChange:v=>t.setPrompt(v.currentTarget.value,v.currentTarget.selectionStart||v.currentTarget.value.length),onPaste:u?v=>{const N=Array.from(v.clipboardData?.items||[]).filter(_=>_.kind==="file"&&_.type.startsWith("image/")).map(_=>_.getAsFile()).filter(Boolean);N.length>0&&f(N)>0&&v.preventDefault()}:void 0,onKeyDown:v=>{if(v.key==="Tab"&&!v.shiftKey&&t.acceptPromptReferenceAutocomplete()){v.preventDefault();return}if(v.key==="Escape"&&r.editingPending){if(v.preventDefault(),x){t.exitPendingPromptEdit({restoreDraft:!0});return}S();return}v.key==="Enter"&&!v.shiftKey&&!v.metaKey&&!e&&(v.preventDefault(),h())}}),o.createElement("div",{className:"ps-prompt-actions"},u?o.createElement(o.Fragment,null,o.createElement("input",{ref:a,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:v=>{f(v.currentTarget.files),v.currentTarget.value=""}}),o.createElement("button",{type:"button",className:"ps-mini-button ps-attach-button",title:"Attach images (or paste / drop them into the composer)","aria-label":"Attach images",onPointerDown:v=>v.preventDefault(),onClick:()=>a.current?.click()},"📎")):null,r.editingPending&&!E?o.createElement("button",{type:"button",className:"ps-mini-button",title:k?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":k?"Delete selected queued prompt":"Cancel selected pending prompt",onPointerDown:v=>v.preventDefault(),onClick:S},k?"Delete":"Cancel"):null,r.canStopTurn||g?o.createElement("button",{type:"button",className:`ps-stop-button${g?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:g,onPointerDown:v=>v.preventDefault(),onClick:y},"■"):null,o.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"Send all queued prompts":r.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"Send queued prompts":r.hasOutbox?"Queue prompt":"Send prompt",onPointerDown:v=>v.preventDefault(),onClick:h},w)))}const FS=1e3;function he({icon:t,label:e,onClick:s,disabled:n=!1,active:r=!1,className:i="ps-toolbar-button"}){const[a,l]=o.useState(null),c=o.useRef(null),d=o.useRef(null),u=o.useRef(null),p=o.useRef(!1);o.useLayoutEffect(()=>{if(!a||!d.current||typeof window>"u")return;const v=d.current.offsetWidth/2,P=6,N=Math.max(v+P,Math.min(a.x,window.innerWidth-v-P));d.current.style.left=`${N}px`},[a]);const m=(v=!1)=>{const P=c.current;if(!P||typeof window>"u")return;const N=P.getBoundingClientRect(),_=v?N.top-44<0:N.bottom+44<window.innerHeight;l({x:N.left+N.width/2,y:_?N.bottom+6:N.top-6,placement:_?"below":"above"})},f=o.useRef(null),h=o.useRef(null),g=v=>{v.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(f.current),u.current=setTimeout(m,FS))},b=v=>{v.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(f.current),l(null))},y=v=>{v.pointerType!=="mouse"&&(p.current=!1,h.current={x:v.clientX,y:v.clientY},clearTimeout(u.current),clearTimeout(f.current),u.current=setTimeout(()=>{p.current=!0,m(!0)},450))},S=v=>{if(v.pointerType==="mouse"||!h.current)return;const P=v.clientX-h.current.x,N=v.clientY-h.current.y;P*P+N*N>100&&(h.current=null,clearTimeout(u.current),l(null))},w=v=>{v.pointerType!=="mouse"&&(h.current=null,clearTimeout(u.current),p.current?(clearTimeout(f.current),f.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{p.current=!1},250)):l(null))};o.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(f.current)},[]);const k=v=>{if(p.current){p.current=!1,v.preventDefault?.();return}n||s?.(v)},E=v=>{v.preventDefault?.()},x=a&&typeof document<"u"&&document.body?Wr.createPortal(o.createElement("span",{ref:d,className:`ps-icon-tooltip is-${a.placement}`,role:"tooltip",style:{left:`${a.x}px`,top:`${a.y}px`}},e),document.body):null;return o.createElement("button",{ref:c,type:"button",className:`${i} ps-icon-button${r?" is-active":""}`,onClick:k,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:b,onPointerDown:y,onPointerMove:S,onPointerUp:w,onPointerCancel:w,onContextMenu:E},o.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),x)}function DS({controller:t,mobile:e,canvasPaneOpen:s=!1,onToggleCanvasPane:n=null,mobilePane:r="workspace",onSelectMobilePane:i=null,mobileMainLayout:a="split"}){const[l,c]=o.useState(null);o.useEffect(()=>{typeof document>"u"||c(e?null:document.getElementById("ps-header-toolbar-slot"))},[e]);const d=ee(t,I=>!!I.admin?.visible),u=ee(t,I=>!!(I.admin?.profile?.isAdmin||I.auth?.authorization?.role==="admin")),p=u?"admin console":"settings",m=ee(t,I=>!!I.ui?.budgetOpen),f=ee(t,fi,Le),h=ee(t,I=>I?.ui?.diagnosticsOpen===!0),g=ee(t,I=>I?.ui?.canvasMaximized===!0),b=ee(t,I=>!!(I?.files?.paneOpen&&I?.files?.selectedArtifactId)),y=[{key:"new",icon:o.createElement(sS),label:"New session — choose model and agent",onClick:()=>t.handleCommand(M.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:o.createElement(Ui),label:"Filter sessions",onClick:()=>t.handleCommand(M.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:o.createElement(rS),label:"Theme",onClick:()=>t.handleCommand(M.OPEN_THEME_PICKER).catch(()=>{})},{key:"canvas",icon:o.createElement(vd),label:(e?s:f.mode==="canvas"&&!b)?"Hide the canvas":"Show canvas",onClick:()=>{if(e){n&&n();return}t.dispatch({type:"ui/canvasOpen",open:f.mode!=="canvas",sessionId:f.sessionId,manual:!0})},active:e?s:f.mode==="canvas"&&!b,badge:e?f.exists&&(f.latestRev>(f.lastViewedRev||0)||(f.latestDataRev||0)>(f.lastViewedDataRev||0))&&!s:f.unseen,loadedDot:f.exists},{key:"budget",icon:o.createElement(lS),label:m?"Close budget":"Budget — providers, limits and usage",onClick:()=>{m?t.closeBudget():t.openBudget().catch(()=>{})},active:m},...e?[]:[{key:"diagnostics",icon:o.createElement(Ga),label:h?"Hide diagnostics":"Show diagnostics (inspector and activity)",onClick:()=>t.dispatch({type:"ui/diagnosticsOpen"}),active:h}],...e?[]:[{key:"admin",icon:o.createElement(aS),label:d?`Close ${p}`:u?"Admin console":"Settings",onClick:()=>t.handleCommand(d?M.CLOSE_ADMIN_CONSOLE:M.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:d}],...e?[]:[{key:"workspace",icon:o.createElement(Ua),label:"Workspace — sessions, chat and panels",onClick:()=>t.handleCommand(M.OPEN_WORKSPACE).catch(()=>{}),active:!d&&!m}]],S=I=>{const C=o.createElement(he,{key:I.badge?void 0:I.key,icon:I.icon,label:I.label,onClick:I.onClick,disabled:!!I.disabled,active:!!I.active});return I.badge||I.loadedDot?o.createElement("span",{key:I.key,className:"ps-canvas-toggle"},C,I.loadedDot?o.createElement("span",{className:"ps-canvas-loaded-dot","aria-hidden":"true"}):null,I.badge?o.createElement("span",{className:"ps-canvas-badge","aria-hidden":"true"}):null):C};if(e){const I={split:"Main — sessions and chat (tap for chat only)",chat:"Main — chat only (tap for sessions only)",sessions:"Main — sessions only (tap for both)"},C=r==="inspector"||r==="activity",U=r==="inspector"?"activity":"inspector",B=[{id:"workspace",icon:Ua,label:I[a]||I.split,focus:"chat"},{id:U,icon:Ga,active:C,label:C?r==="inspector"?"Diagnostics — inspector (tap for activity)":"Diagnostics — activity (tap for inspector)":"Diagnostics — inspector and activity",focus:U}];return o.createElement("div",{className:"ps-toolbar is-mobile"},o.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},o.createElement("div",{className:"ps-toolbar-row-actions"},y.map(S)),o.createElement("div",{className:"ps-toolbar-row-actions is-panes"},B.map(V=>o.createElement(he,{key:V.id==="workspace"?"workspace":"diagnostics",icon:o.createElement(V.icon),label:V.label,active:V.active??r===V.id,onClick:()=>{i&&i(V.id,V.focus)}})))))}const w=d?"admin":m?"budget":"workspace",k=["new","filter"],E=["canvas","diagnostics"],x=["workspace","budget","admin"],v=I=>!g||I.key==="canvas"?I:{...I,onClick:(...C)=>(t.dispatch({type:"ui/canvasMaximized",on:!1}),I.onClick?.(...C))},P=I=>I.map(C=>y.find(U=>U.key===C)).filter(Boolean).map(v).map(S),N=I=>o.createElement("span",{key:I,className:"ps-toolbar-divider","aria-hidden":"true"}),_=w==="workspace"?[...P(k),...P(E)]:[],D=[...P(x),N("mode-divider"),...P(["theme"])],L=o.createElement("div",{className:"ps-toolbar"},o.createElement("div",{className:"ps-toolbar-side is-left"},g?_:null),o.createElement("div",{className:"ps-toolbar-actions"},g?null:_),o.createElement("div",{className:"ps-toolbar-side is-right"},o.createElement("span",{className:"ps-toolbar-meta-slot",id:"ps-toolbar-meta-slot"}),g?o.createElement("span",{className:"ps-toolbar-canvas-slot",id:"ps-toolbar-canvas-slot"}):null,g?o.createElement("span",{className:"ps-toolbar-divider","aria-hidden":"true"}):null,o.createElement("div",{className:"ps-toolbar-actions is-tools"},D),o.createElement("span",{className:"ps-toolbar-signout-slot",id:"ps-toolbar-signout-slot"})));return l?Wr.createPortal(L,l):L}function hs(t){try{t.currentTarget?.setPointerCapture?.(t.pointerId)}catch{}}function BS({controller:t,paneAdjust:e=0}){const s=o.useRef(null),[n,r]=o.useState(!1);return o.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")};let a=0,l=0;const c=()=>{a=0;const u=s.current;if(!u)return;const p=Math.round((l-u.startX)/Bc),m=p-u.appliedCells;m&&(t.adjustPaneSplit(m),u.appliedCells=p)},d=u=>{s.current&&(l=u.clientX,!a&&(a=requestAnimationFrame(c)))};return window.addEventListener("pointermove",d),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{a&&(cancelAnimationFrame(a),a=0),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),o.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown:i=>{i.button===0&&(i.preventDefault(),hs(i),s.current={startX:i.clientX,appliedCells:0},r(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:i=>{if(i.key==="ArrowLeft"){i.preventDefault(),t.handleCommand(M.GROW_RIGHT_PANE).catch(()=>{});return}i.key==="ArrowRight"&&(i.preventDefault(),t.handleCommand(M.GROW_LEFT_PANE).catch(()=>{}))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function HS({controller:t,portalSessionColumnAdjust:e=0}){const s=o.useRef(null),[n,r]=o.useState(!1);return o.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")},a=l=>{const c=s.current;if(!c)return;const d=rs(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:d})};return window.addEventListener("pointermove",a),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),o.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:i=>{if(i.button!==0)return;i.preventDefault(),hs(i);const a=i.currentTarget.closest(".ps-workspace-main-grid"),l=Dr(a?.getBoundingClientRect?.().width);s.current={startX:i.clientX,startAdjust:Number(e)||0,minAdjust:l.minAdjust,maxAdjust:l.maxAdjust},r(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:i=>{const a=i.currentTarget.closest(".ps-workspace-main-grid"),l=Dr(a?.getBoundingClientRect?.().width),c=d=>{const u=rs((Number(e)||0)+d,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};if(i.key==="ArrowLeft"){i.preventDefault(),c(-24);return}i.key==="ArrowRight"&&(i.preventDefault(),c(24))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function US({controller:t,canvasPaneAdjust:e=0,diagnosticsPaneAdjust:s=0}){const n=o.useRef(null),[r,i]=o.useState(!1),a=(c,d)=>({canvas:_i+(Number(c)||0),diag:Ri+(Number(d)||0)}),l=(c,d)=>{const u=a(c,d);if(u.canvas<Qs||u.diag<Qs){t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0}),t.dispatch(u.canvas<Qs?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:c}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:d})};return o.useEffect(()=>{if(!r)return;const c=u=>{const p=n.current;if(!p)return;const m=u.clientX-p.startX;t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:p.startCanvas+m}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:p.startDiag-m})},d=()=>{const u=n.current;if(n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),u){const p=t.getState()?.ui?.layout||{};l(p.canvasPaneAdjust??0,p.diagnosticsPaneAdjust??0)}};return window.addEventListener("pointermove",c),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d),()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d)}},[t,r]),o.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to trade width between the canvas and diagnostics. Drag one away to close it. Double-click to reset.","aria-label":"Resize canvas and diagnostics columns",onPointerDown:c=>{c.button===0&&(c.preventDefault(),hs(c),n.current={startX:c.clientX,startCanvas:Number(e)||0,startDiag:Number(s)||0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0})},onKeyDown:c=>{if(c.key!=="ArrowLeft"&&c.key!=="ArrowRight")return;c.preventDefault();const d=c.key==="ArrowRight"?24:-24;l((Number(e)||0)+d,(Number(s)||0)-d)}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function jS({controller:t,sessionId:e,railPx:s=380}){const n=o.useRef(null),[r,i]=o.useState(!1);return o.useEffect(()=>{if(!r)return;const a=c=>{const d=n.current;d&&t.dispatch({type:"canvas/zenRail",sessionId:e,px:d.start+(c.clientX-d.startX)})},l=()=>{n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};return window.addEventListener("pointermove",a),window.addEventListener("pointerup",l),window.addEventListener("pointercancel",l),()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l)}},[t,r,e]),o.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to resize chat against the canvas (remembered for this session)","aria-label":"Resize the zen chat rail",onPointerDown:a=>{a.button===0&&(a.preventDefault(),hs(a),n.current={startX:a.clientX,start:s},i(!0),document.body.classList.add("is-resizing-pane-x"))},onKeyDown:a=>{a.key!=="ArrowLeft"&&a.key!=="ArrowRight"||(a.preventDefault(),t.dispatch({type:"canvas/zenRail",sessionId:e,px:s+(a.key==="ArrowRight"?24:-24)}))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function GS({controller:t,target:e,adjust:s=0}){const n=o.useRef(null),[r,i]=o.useState(!1),a=e==="canvas"?"ui/canvasPaneAdjust":"ui/diagnosticsPaneAdjust",l=e==="canvas"?"canvasPaneAdjust":"diagnosticsPaneAdjust",c=e==="canvas"?_i:Ri,d=u=>{if(c+u<Qs){t.dispatch({type:a,[l]:0}),t.dispatch(e==="canvas"?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:a,[l]:u})};return o.useEffect(()=>{if(!r)return;const u=m=>{const f=n.current;if(!f)return;const h=f.startAdjust-(m.clientX-f.startX);t.dispatch({type:a,[l]:Math.min(h,f.maxAdjust)})},p=()=>{const m=n.current;n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),m&&d((t.getState()?.ui?.layout||{})[l]??0)};return window.addEventListener("pointermove",u),window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p)}},[t,r,a,l]),o.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to resize. Drag the column away to close it. Double-click to reset.","aria-label":"Resize the right column",onPointerDown:u=>{if(u.button!==0)return;u.preventDefault(),hs(u);const p=document.querySelector(".ps-workspace-main-grid > .ps-workspace-pane-slot:last-child"),m=p?p.getBoundingClientRect().width:Number.POSITIVE_INFINITY,f=Number(s)||0;n.current={startX:u.clientX,startAdjust:f,maxAdjust:f+Math.max(0,m-Pi)},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>t.dispatch({type:a,[l]:0}),onKeyDown:u=>{u.key!=="ArrowLeft"&&u.key!=="ArrowRight"||(u.preventDefault(),d((Number(s)||0)-(u.key==="ArrowRight"?24:-24)))}},o.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}function WS({controller:t,splitAdjust:e=0}){const s=o.useRef(null),[n,r]=o.useState(!1);return o.useEffect(()=>{if(!n)return;const i=l=>{const c=s.current;if(!c)return;const d=rs(c.start+(l.clientY-c.startY),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:d})},a=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-y")};return window.addEventListener("pointermove",i),window.addEventListener("pointerup",a),window.addEventListener("pointercancel",a),()=>{window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",a),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),o.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector and activity panes. Double-click to reset.","aria-label":"Resize the inspector and activity panes",onPointerDown:i=>{if(i.button!==0)return;i.preventDefault(),hs(i);const a=i.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,a?.getBoundingClientRect?.().height||0),c=Math.max(0,i.currentTarget.getBoundingClientRect().height||0),{minAdjust:d,maxAdjust:u}=lo(l,c);s.current={startY:i.clientY,start:rs(Number(e)||0,d,u),minAdjust:d,maxAdjust:u},r(!0),document.body.classList.add("is-resizing-pane-y")},onDoubleClick:()=>t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:0}),onKeyDown:i=>{if(i.key!=="ArrowUp"&&i.key!=="ArrowDown")return;i.preventDefault();const a=i.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,a?.getBoundingClientRect?.().height||0),c=Math.max(0,i.currentTarget.getBoundingClientRect().height||0),{minAdjust:d,maxAdjust:u}=lo(l,c);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:rs((Number(e)||0)+(i.key==="ArrowDown"?c:-c),d,u)})}},o.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"}),o.createElement("span",{className:"ps-column-resizer-dot"})))}const zS=[{value:"day",label:"Daily"},{value:"week",label:"Weekly"},{value:"month",label:"Monthly"}],Qa={day:"Daily",week:"Weekly",month:"Monthly"},qS={plain:"",amber:" warn",red:" over",idle:""};function KS(t){const e=Math.abs(Number(t)||0),[s,n]=e>=1e9?["B",1e9]:e>=1e6?["M",1e6]:e>=1e3?["K",1e3]:["",1],r=e/n,i=s===""||r>=100?0:r>=10?1:2;return a=>{const l=Number(a);return Number.isFinite(l)?l===0?"0":`${(l/n).toFixed(i)}${s}`:"—"}}function VS(t){const e=String(t??"").trim().replace(/[,_\s]/g,"").toUpperCase();if(!e)return null;const s=/^(\d+(?:\.\d+)?)([KMB])?$/.exec(e);if(!s)return null;const n=s[2]==="K"?1e3:s[2]==="M"?1e6:s[2]==="B"?1e9:1;if(!s[2]&&/\./.test(s[1]))return null;const r=Math.round(Number(s[1])*n);return Number.isSafeInteger(r)&&Number.isFinite(r)&&r>0?r:null}function Gr(t){return t?`resets ${t}`:"no reset recorded"}function YS(t,e,s){return`${t} ${t===1?e:s}`}function XS(t,e){return e?.typeId?t.filter(s=>s.providerId===e.typeId).map(s=>({qualifiedName:`${e.name}:${s.modelName}`,modelName:s.modelName})):[]}function QS(t){return(Array.isArray(t)?t:Array.isArray(t?.providers)?t.providers:Array.isArray(t?.models)?t.models:[]).flatMap(n=>Array.isArray(n?.models)?n.models.map(r=>({...r,providerId:r.providerId||n.providerId})):[n]).filter(n=>n&&(n.modelName||n.qualifiedName)).map(n=>({modelName:n.modelName||String(n.qualifiedName).split(":").pop(),providerId:n.providerId||"",providerType:n.providerType||n.providerId||""}))}function kd({title:t,subtitle:e,children:s,footNote:n,confirmLabel:r,danger:i=!1,busy:a=!1,disabled:l=!1,error:c=null,onCancel:d,onConfirm:u=null,cancelLabel:p="Cancel"}){const m=o.useRef(null);return o.useEffect(()=>{const f=m.current;if(!f)return;const h=()=>[...f.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')];f.contains(document.activeElement)||(h()[0]||f).focus();const g=b=>{if(b.key!=="Tab")return;const y=h();if(!y.length)return;const S=y[0],w=y[y.length-1];b.shiftKey&&document.activeElement===S?(b.preventDefault(),w.focus()):!b.shiftKey&&document.activeElement===w&&(b.preventDefault(),S.focus())};return f.addEventListener("keydown",g),()=>f.removeEventListener("keydown",g)},[]),o.useEffect(()=>{const f=h=>{h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),d())};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[d]),o.createElement("div",{className:"ps-budget-sheet-backdrop",onMouseDown:f=>{f.target===f.currentTarget&&(f.preventDefault(),d())}},o.createElement("div",{className:"ps-budget-sheet",role:"dialog","aria-modal":"true","aria-label":t,ref:m,tabIndex:-1},o.createElement("div",{className:"ps-budget-sheet-top"},o.createElement("div",{className:"ps-budget-sheet-title"},t),e?o.createElement("div",{className:"ps-budget-sheet-sub"},e):null),o.createElement("div",{className:"ps-budget-sheet-body"},s,c?o.createElement("div",{className:"ps-budget-sheet-error",role:"alert"},c):null),o.createElement("div",{className:"ps-budget-sheet-foot"},o.createElement("span",{className:"ps-budget-sheet-note"},n||""),o.createElement("div",{className:"ps-budget-sheet-actions"},o.createElement("button",{type:"button",className:"ps-mini-button",onClick:d,disabled:a},p),u?o.createElement("button",{type:"button",className:`ps-mini-button ${i?"is-danger":"is-primary"}`,onClick:u,disabled:a||l},a?"…":r):null))))}function Ge({label:t,hint:e,children:s}){return o.createElement("div",{className:"ps-budget-field",role:"group","aria-label":t},o.createElement("span",{className:"ps-budget-label"},t),s,e?o.createElement("span",{className:"ps-budget-field-hint"},e):null)}function $t({value:t,options:e,onChange:s,label:n=null}){return o.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":n||void 0},e.map(r=>o.createElement("button",{key:r.value,type:"button","aria-pressed":t===r.value?"true":"false",className:`ps-budget-seg-btn${t===r.value?" is-on":""}`,onClick:()=>s(r.value)},r.label)))}function ZS(t){const e=t.known?qS[t.tone]||"":" idle";return o.createElement(o.Fragment,null,o.createElement("span",{className:`ps-budget-pct${e}`},t.usedLabel),t.providerExhausted?o.createElement("span",{className:"ps-budget-blocked",title:"The provider's own limit is spent."}," ⏻"):null," ",o.createElement("span",{className:`ps-budget-q ps-budget-sub${t.uncapped?" is-inf":""}`},`/ ${t.quotaLabel}`))}function JS(t){if(!t.split)return o.createElement("span",{className:"ps-budget-split"},"—");const e="Parts of the input, not additions to it: the total is input + output.";return o.createElement("span",{className:"ps-budget-split"},o.createElement("span",null,"in ",J(t.split.input)),o.createElement("span",null,"out ",J(t.split.output)),o.createElement("span",{title:e},"cache r ",J(t.split.cacheRead)),o.createElement("span",{title:e},"w ",J(t.split.cacheWrite)))}function ev(t,e,s){const n=t.kind==="model"?`${t.providerName} · ${t.label}`:t.providerName,r=s.uncapped?"no limit for this period":`${s.usedLabel} of ${s.quotaLabel}${s.pct==null?"":` (${s.pct}%)`}`,i=s.providerExhausted?" The provider's own limit for this period is spent, so nothing runs against it whatever your share says.":"",a=s.splitText?` Made of ${s.splitText}.`:"";return`${n} · ${e.label} — ${r}. It ${Gr(s.resetsLabel)}.${i}${a}`}function tv({controller:t,view:e,defaults:s=null}){const n=o.useCallback((l,c="*")=>{t.selectBudgetProvider(l,c).catch(()=>{})},[t]),r=l=>l.kind==="model"?o.createElement("td",{className:"ps-budget-grid-name is-model"},o.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":l.selected?"true":"false",onClick:()=>n(l.providerName,l.scope)},o.createElement("span",{className:"ps-budget-grid-mname"},l.label),o.createElement("span",{className:"ps-budget-sub"}," · model"))):o.createElement("td",{className:"ps-budget-grid-name"},o.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":l.selected?"true":"false","aria-expanded":l.modelRowCount>0?l.expanded?"true":"false":void 0,onClick:()=>n(l.providerName)},o.createElement("span",{className:"ps-budget-grid-pname"},l.label),l.ownerLabel?o.createElement("span",{className:"ps-budget-grid-owner"},`(${l.ownerLabel})`):null,l.classLabel?o.createElement("span",{className:`ps-budget-chip is-${l.class}`,title:l.class==="shared"?"Shared: anyone may spend from it. An administrator manages its limits.":l.ownedByMe===!1?"A user provider belonging to another user.":"Your own provider. Only you see it or spend from it."},l.classLabel):null,s?.mine?.provider===l.providerName?o.createElement("span",{className:"ps-budget-chip"},"my default"):null,s?.cluster?.provider===l.providerName?o.createElement("span",{className:"ps-budget-chip"},"cluster default"):null,s?.system?.provider===l.providerName?o.createElement("span",{className:"ps-budget-chip"},"system default"):null,l.hold?o.createElement("span",{className:"ps-budget-chip is-hold",title:`It ${l.hold.label}.`},"on hold"):null,l.allowanceLabel?o.createElement("span",{className:"ps-budget-grid-allow"},l.allowanceLabel):null,l.expandLabel?o.createElement("span",{className:"ps-budget-grid-teaser"},l.expandLabel):null)),i=l=>o.createElement("tr",{key:l.key,className:`ps-budget-grid-row${l.kind==="model"?" is-model":""}${l.selected?" is-on":""}`,onClick:c=>{c.target?.closest?.("button")||n(l.providerName,l.kind==="model"?l.scope:"*")}},r(l),e.columns.map(c=>o.createElement("td",{key:c.id,className:"ps-budget-grid-num","data-period":c.label,title:ev(l,c,l.cells[c.id])},ZS(l.cells[c.id])))),a=l=>o.createElement("tr",{key:`${l.key}:split`,className:`ps-budget-grid-split${l.kind==="model"?" is-model":""}`,"aria-label":`What ${l.kind==="model"?l.label:l.providerName} spent, by kind of token`},o.createElement("td",{className:"ps-budget-grid-split-name"}),e.columns.map(c=>o.createElement("td",{key:c.id,className:"ps-budget-grid-num is-split","data-period":c.label},JS(l.cells[c.id]))));return o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-budget-table-head"},o.createElement("span",{className:"ps-budget-label"},`Providers${e.providerCount>0?` · ${e.providerCount}`:""}`),o.createElement("label",{className:"ps-budget-toggle"},o.createElement("input",{type:"checkbox",checked:e.overall,onChange:()=>t.setBudgetOverall()}),o.createElement("span",null,e.overallLabel))),e.empty?o.createElement("div",{className:"ps-budget-empty"},"No provider exists yet. Add one in Admin Console → Model Providers to start spending."):o.createElement("table",{className:"ps-budget-grid"},o.createElement("thead",null,o.createElement("tr",null,o.createElement("th",{className:"ps-budget-grid-h is-name",rowSpan:2,scope:"col"},"Provider"),o.createElement("th",{className:"ps-budget-grid-h is-span",colSpan:3,scope:"colgroup"},e.usageHeading)),o.createElement("tr",null,e.columns.map(l=>o.createElement("th",{key:l.id,className:"ps-budget-grid-h is-num",scope:"col"},l.label)))),o.createElement("tbody",null,e.rows.flatMap(l=>l.selected?[i(l),a(l)]:[i(l)]))))}function sv({controller:t,view:e}){const s=e.series,n=e.selected,r={className:"ps-budget-chart-pane","data-range-days":String(e.rangeDays)},[i,a]=o.useState(null),[l,c]=o.useState(0);o.useEffect(()=>{if(!i||typeof ResizeObserver>"u")return;const w=()=>{const E=Math.round(i.getBoundingClientRect().width);c(x=>Math.abs(E-x)<1?x:E)},k=new ResizeObserver(w);return k.observe(i),w(),()=>k.disconnect()},[i]);const d=s.days,u=d.length,p=o.useMemo(()=>{const E=l-(u-1)*5,x=l>0?Math.floor(E/30):7,v=Math.max(1,Math.min(7,x)),P=Math.max(1,Math.ceil(u/v)),N=new Set;for(let _=u-1;_>=0;_-=P)N.add(_);return N},[l,u]),m=o.createElement("div",{className:"ps-budget-chart-head"},o.createElement("span",{className:"ps-budget-chart-title"},o.createElement("strong",null,n.subject),o.createElement("span",{className:"ps-budget-sub"},` · ${e.usageHeading.toLowerCase()}, by day`)),o.createElement("div",{className:"ps-budget-chart-range"},o.createElement($t,{value:e.rangeDays,options:e.rangeOptions,label:"Chart range",onChange:w=>t.setBudgetRangeDays(w).catch(()=>{})}),o.createElement("span",{className:"ps-budget-sub"},s.rangeLabel)));if(s.failed)return o.createElement("div",r,m,o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,`The daily usage for ${n.subject} could not be read.`),o.createElement("div",{className:"ps-budget-sub"},s.error)));if(s.loading&&!s.loaded)return o.createElement("div",r,m,o.createElement("div",{className:"ps-budget-empty"},"Reading the daily usage…"));const f=s.scaleMax,h=[1,.75,.5,.25,0],g=KS(f),b=d.filter(w=>w.tokens>0).length,y=s.quotaPct==null?null:Math.max(0,Math.min(96,100-s.quotaPct)),S=o.createElement("div",{className:"ps-budget-xaxis"},o.createElement("div",{className:"ps-budget-xaxis-spacer"}),o.createElement("div",{className:"ps-budget-tl-x",ref:a},d.map((w,k)=>o.createElement("span",{key:w.dayUtc,className:p.has(k)?"is-tick":void 0},p.has(k)?w.label:""))));return o.createElement("div",r,m,s.mixedScope?o.createElement("div",{className:"ps-budget-note is-warn"},"The bars are what the whole fleet spent on this provider each day. The dashed line is YOUR share of the daily limit, not the limit itself. Tick “Show overall usage” to read both as the provider's."):null,s.stale?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"These figures are from an earlier read. The most recent read failed."),o.createElement("div",{className:"ps-budget-sub"},s.error)):null,o.createElement("div",{className:"ps-budget-chart"},o.createElement("div",{className:"ps-budget-yaxis-title"},"tokens"),o.createElement("div",{className:"ps-budget-plotwrap"},o.createElement("div",{className:"ps-budget-yaxis"},f>0?h.map(w=>o.createElement("div",{key:`t${w}`,className:"ps-budget-ytick",style:{top:`${(1-w)*100}%`}},g(f*w))):null),o.createElement("div",{className:"ps-budget-plot"},f>0?h.map(w=>o.createElement("div",{key:`g${w}`,className:"ps-budget-gridline",style:{top:`${(1-w)*100}%`}})):null,y==null?null:o.createElement("div",{className:"ps-budget-tl-median",style:{top:`${y}%`}},o.createElement("span",null,`the Day limit · ${s.quotaLabel} a day`)),o.createElement("div",{className:"ps-budget-bars"},d.map(w=>o.createElement("div",{key:w.dayUtc,className:`ps-budget-tl-col${w.tokens===0?" is-idle":""}${s.quotaTokens!=null&&w.tokens>s.quotaTokens?" is-over":""}`,title:`${w.label} · ${w.tokens?`${w.tokens.toLocaleString("en-US")} tokens · ${YS(w.turns,"turn","turns")}`:"no usage"}`},o.createElement("div",{className:"ps-budget-tl-bar",style:{height:w.tokens===0?"2px":`${Math.max(1,w.pct)}%`}})))),s.empty?o.createElement("div",{className:"ps-budget-noaxis"},`No token usage on ${n.subject} in this range.`):null)),S,o.createElement("div",{className:"ps-budget-xaxis-title"},`Daily totals · UTC · ${s.rangeLabel.toLowerCase()}`),o.createElement("div",{className:"ps-budget-legend"},o.createElement("span",null,`Peak ${s.peakLabel} tokens/day`),o.createElement("span",null,`${b} of ${u} days used`),s.quotaTokens!=null?o.createElement("span",null,`Dashed line: ${s.quotaLabel} a day`):o.createElement("span",null,"No daily limit, so no line"))))}function nv({view:t}){const e=t.systemSpend;if(!e)return null;const s=n=>String(n||"").startsWith(`${t.selectedProvider}:`)?String(n).slice(t.selectedProvider.length+1):String(n||"Unknown model");return o.createElement("section",{className:"ps-budget-system-spend","aria-label":"System spend"},o.createElement("div",{className:"ps-budget-chart-head"},o.createElement("span",{className:"ps-budget-chart-title"},o.createElement("strong",null,"System spend")),o.createElement("span",{className:"ps-budget-sub"},e.rangeLabel)),e.loading&&!e.loaded?o.createElement("div",{className:"ps-budget-empty"},"Reading system spend…"):null,e.error?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},e.error):null,e.loaded?o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-budget-system-stats"},o.createElement("div",{className:"ps-budget-system-stat"},o.createElement("strong",null,e.tokensLabel),o.createElement("span",null,"tokens")),o.createElement("div",{className:"ps-budget-system-stat"},o.createElement("strong",null,J(e.turns)),o.createElement("span",null,e.turns===1?"turn":"turns")),e.turns>0?o.createElement("div",{className:"ps-budget-system-stat"},o.createElement("strong",null,J(Math.round(e.tokens/e.turns))),o.createElement("span",null,"tokens / turn")):null),e.models.length?o.createElement("table",{className:"ps-budget-system-models"},o.createElement("thead",null,o.createElement("tr",null,o.createElement("th",{scope:"col"},"Model"),o.createElement("th",{scope:"col",className:"is-num"},"Tokens"),o.createElement("th",{scope:"col",className:"is-share"},"Share"),o.createElement("th",{scope:"col",className:"is-num"},"Turns"))),o.createElement("tbody",null,e.models.map(n=>{const r=e.tokens>0?n.tokens/e.tokens:0,i=Math.round(r*100);return o.createElement("tr",{key:n.key},o.createElement("td",{className:"ps-budget-system-model-name"},s(n.label)),o.createElement("td",{className:"is-num"},n.tokensLabel),o.createElement("td",{className:"is-share"},o.createElement("span",{className:"ps-budget-system-bar",role:"img","aria-label":`${i}% of system spend`},o.createElement("span",{className:"ps-budget-system-bar-fill",style:{width:`${Math.max(r>0?1:0,r*100)}%`}})),o.createElement("span",{className:"ps-budget-system-pct"},`${i}%`)),o.createElement("td",{className:"is-num"},J(n.turns)))}))):o.createElement("div",{className:"ps-budget-sub"},"No system spend in this range.")):null)}function rv({row:t,rawRows:e,models:s,isAdmin:n,busy:r,error:i,onCancel:a,onRun:l,initialPeriod:c="day",initialScope:d="*"}){const u=t.class==="shared",p=t.manageable===!0,m=[...p?[{value:"limit",label:"Limits"}]:[],...p&&n&&u?[{value:"allowance",label:"Allowance"}]:[],...p&&n?[{value:"hold",label:"Hold"}]:[]],[f,h]=o.useState("limit"),[g,b]=o.useState(c),[y,S]=o.useState(d==="*"?"all":"model"),[w,k]=o.useState(d==="*"?"":d),[E,x]=o.useState("");o.useEffect(()=>{!w&&s[0]&&k(s[0].qualifiedName)},[s,w]);const v=e.find(O=>O.providerName===t.providerName&&O.rowKind!=="model")||null,P=y==="model"?w||s[0]?.qualifiedName||"":null,N=y==="model"?e.find(O=>O.providerName===t.providerName&&O.rowKind==="model"&&O.scope===P)||null:v,_=N?.periods?.[g]||null,D=_?.quotaTokens??null,L=N?Number(_?.usedTokens)||0:null,I=L!=null,C=t.cells[g]?.resetsLabel||null,U=Qa[g]||g,B=P||"all models";o.useEffect(()=>{x(D==null?"":Number(D).toLocaleString("en-US"))},[D,g,P]);const V=VS(E),ce=!!V&&(y!=="model"||!!P),X=D!=null,re=Number.isFinite(t.allowancePct)?t.allowancePct:100,T=V==null||re>=100?V:Math.max(1,Math.floor(V*re/100)),j=Number(_?.yourUsedTokens),H=I&&V!==null&&L>=V,W=!H&&V!==null&&T!==V&&Number.isFinite(j)&&j>=T,z=Number.isFinite(t.allowancePct)?t.allowancePct:100,[Q,K]=o.useState(String(z)),Y=Number(String(Q).trim()),Z=Number.isFinite(Y)&&Y>=1&&Y<=100&&Math.floor(Y)===Y,de=["day","week","month"].map(O=>({id:O,label:Qa[O],tokens:v?.periods?.[O]?.quotaTokens??null})).filter(O=>O.tokens!=null),ve=!!t.hold,[le,st]=o.useState(ve?"release":"forever"),[ye,nt]=o.useState(""),Ce=(()=>{if(le!=="until"||!ye)return null;const O=new Date(ye);return Number.isNaN(O.getTime())?null:O.toISOString()})(),Oe=!!Ce&&Date.parse(Ce)<=Date.now(),ut=le!=="until"||!!Ce&&!Oe,rt=le!=="until"?null:Oe?"That time has already passed. A hold has to end in the future.":ye&&!Ce?"That is not a time this can read.":null,G={limit:"Limits",allowance:"Allowance",hold:"Hold"},oe={limit:X?"Replace limit":"Save limit",allowance:"Save allowance",hold:le==="release"?"Release hold":"Place hold"},be={limit:"Limits are enforced.",allowance:"Applies to everyone.",hold:"Stops new turns."},pe=f==="limit"?ce:f==="allowance"?Z:f==="hold"?ut:!0,xe=()=>{f==="limit"?ce&&l("limit",{period:g,model:P,tokens:V}):f==="allowance"?Z&&l("allowance",{pct:Y}):f==="hold"&&l("hold",le==="release"?{release:!0,untilUtc:null}:{release:!1,untilUtc:Ce})},R=o.createElement(o.Fragment,null,o.createElement(Ge,{label:"Time period",hint:"One limit per period and scope."},o.createElement($t,{value:g,onChange:b,options:zS,label:"Time period"})),o.createElement(Ge,{label:"Applies to"},o.createElement($t,{value:y,onChange:S,label:"Applies to",options:[{value:"all",label:"all models"},{value:"model",label:"one model"}]}),y==="model"?o.createElement("select",{className:"ps-budget-input","aria-label":"Model this limit applies to",value:w,onChange:O=>k(O.target.value)},s.length===0?o.createElement("option",{value:""},"No models are listed for this provider's type"):s.map(O=>o.createElement("option",{key:O.qualifiedName,value:O.qualifiedName},O.qualifiedName))):null),o.createElement(Ge,{label:"Tokens",hint:V?`= ${V.toLocaleString("en-US")} tokens.`:E.trim()?"A whole number of tokens: 20,000,000 or 20M.":"Remove the limit to uncap."},o.createElement("input",{className:`ps-budget-input${E&&!V?" is-invalid":""}`,value:E,"aria-label":"Tokens",placeholder:"20,000,000 or 20M",onChange:O=>x(O.target.value),onKeyDown:O=>{O.key==="Enter"&&xe()}})),o.createElement("div",{className:"ps-budget-consequences"},o.createElement("div",null,`${U} · ${B} — `,I?o.createElement(o.Fragment,null,o.createElement("strong",null,`${L.toLocaleString("en-US")} tokens`),u?" spent by users this period.":" spent this period."):o.createElement(o.Fragment,null,o.createElement("strong",null,"not measured yet"),". Current spend will count.")),C?o.createElement("div",{className:"ps-budget-sub"},`Resets ${C}.`):null),X?o.createElement("div",{className:"ps-budget-note is-warn"},`Replaces the existing ${J(D)} token limit.`):null,o.createElement("div",{className:`ps-budget-note${H||W?" is-warn":""}`},"Current spend counts. Saving does not reset usage.",H?` ${L.toLocaleString("en-US")} already meets ${V.toLocaleString("en-US")}, so sessions on ${t.providerName} pause on their next turn${C?` — until this period ${Gr(C)}`:""}.`:W?` At ${re}% each that is ${T.toLocaleString("en-US")} per person, which you have already spent — so sessions pause on their next turn${C?` — until this period ${Gr(C)}`:""}.`:""),X?o.createElement("div",null,o.createElement("button",{type:"button",className:"ps-mini-button is-danger",disabled:r,onClick:()=>l("removeLimit",{period:g,model:P})},`Remove the ${U} · ${B} limit`),o.createElement("div",{className:"ps-budget-note"},"Usage history is kept.")):null),F=o.createElement(o.Fragment,null,o.createElement(Ge,{label:"Share per person",hint:Z?Y>=100?"100% removes the per-person ceiling.":`Each person may use up to ${Y}% of each limit, per period.`:"A whole number from 1 to 100."},o.createElement("input",{className:`ps-budget-input${Q&&!Z?" is-invalid":""}`,value:Q,"aria-label":"Share per person, as a percentage",inputMode:"numeric",placeholder:"20",onChange:O=>K(O.target.value),onKeyDown:O=>{O.key==="Enter"&&Z&&xe()}})),o.createElement("div",{className:"ps-budget-consequences"},de.length===0?o.createElement("div",{className:"ps-budget-note is-warn"},"No limits yet. The allowance applies when one is added."):o.createElement(o.Fragment,null,de.map(O=>o.createElement("div",{key:O.id},`${O.label} · ${J(O.tokens)} → `,o.createElement("strong",null,Z?`${J(Math.floor(O.tokens*Y/100))} per person`:"—"))),o.createElement("div",{className:"ps-budget-note"},"The provider limit still caps total spend.")),Z&&Y<z?o.createElement("div",{className:"ps-budget-note is-warn"},"Users already past the new ceiling pause on their next turn."):null)),A=o.createElement(o.Fragment,null,o.createElement(Ge,{label:"What to do"},o.createElement($t,{value:le,onChange:st,label:"What to do",options:[...ve?[{value:"release",label:"release it"}]:[],{value:"forever",label:"hold until released"},{value:"until",label:"hold until a time"}]})),le==="until"?o.createElement(Ge,{label:"Ends at",hint:rt||"Sessions resume at this time."},o.createElement("input",{className:`ps-budget-input${ye&&!ut?" is-invalid":""}`,"aria-label":"The hold ends at",type:"datetime-local",value:ye,onChange:O=>nt(O.target.value)})):null,ve?o.createElement("div",{className:"ps-budget-consequences"},o.createElement("div",null,`This provider is on hold: it ${t.hold.label}.`)):null,o.createElement("div",{className:`ps-budget-note${le==="release"?"":" is-warn"}`},le==="release"?`Releasing wakes every session waiting on ${t.providerName}. A session still over a limit stays paused for that reason instead.`:`Every session on ${t.providerName} pauses on its next turn. Messages sent to them are kept and answered when the hold lifts.`));return o.createElement(kd,{title:G[f],subtitle:`${t.providerName}${u?" · shared":""}`,confirmLabel:oe[f]||"",danger:f==="hold"&&le==="release",busy:r,disabled:!pe,error:i,onCancel:a,onConfirm:oe[f]?xe:null,cancelLabel:oe[f]?"Cancel":"Done",footNote:be[f]},m.length>1?o.createElement(Ge,{label:"What to change"},o.createElement($t,{value:f,onChange:h,options:m,label:"What to change"})):null,f==="limit"?R:null,f==="allowance"?F:null,f==="hold"?A:null)}function iv({types:t,existingNames:e,isAdmin:s,busy:n,error:r,onDirty:i,onCancel:a,onConfirm:l,initialName:c="",initialShared:d=!1,initialType:u="",updateProvider:p=null}){const m=!!p,[f,h]=o.useState(c),[g,b]=o.useState(u||t[0]?.id||""),[y,S]=o.useState(""),[w,k]=o.useState(""),[E,x]=o.useState(s&&d),v=o.useRef(null);o.useEffect(()=>{v.current?.focus()},[]),o.useEffect(()=>{!g&&t[0]&&b(t[0].id)},[t,g]);const P=f.trim(),N=!m&&e.some(X=>X.toLowerCase()===P.toLowerCase()),_=P!==""&&!/^[A-Za-z0-9._-]+$/.test(P),D=P.length>64,L=t.find(X=>X.id===g)?.usesWorkloadIdentity===!0,I=L,C=I?!0:E,U=!!P&&!N&&!_&&!D&&!!g&&(L||!!y.trim())&&(!I||s),B=/github/i.test(g),V=()=>{if(!U)return;const X={name:P,type:g,shared:C,credentials:L?{kind:"workloadIdentity"}:B?{githubToken:y.trim()}:{apiKey:y.trim()},baseUrl:w.trim()||null};S(""),l(X)},ce=()=>{S(""),a()};return o.createElement(kd,{title:m?`Update key for ${P}`:B?"Add GitHub Copilot provider":"Add model provider",subtitle:C?"Shared":"Personal",confirmLabel:m?"Update key":"Add provider",busy:n,disabled:!U,error:r,onCancel:ce,onConfirm:V,footNote:m?"Only the key changes. The name, type, base URL, defaults, system-session routing and usage history all stay as they are.":""},o.createElement(Ge,{label:"Name",hint:N?"A provider with that name already exists, and names are unique across the cluster.":D?`Too long: ${P.length} characters, and a name may be at most 64.`:_?'Letters, numbers, dot, dash and underscore only — no colon, no spaces, no accents: a session refers to it as "<provider>:<model>".':m?"Not changing. Sessions keep referring to it as provider:model.":"Permanent. Used in provider:model."},o.createElement("input",{ref:v,className:`ps-budget-input${m?" is-static":""}${(N||_||D)&&P?" is-invalid":""}`,"aria-label":"Provider name",value:f,placeholder:"azure-prod",disabled:m,onChange:X=>{i?.(),h(X.target.value)},onKeyDown:X=>{X.key==="Enter"&&U&&V()}})),o.createElement(Ge,{label:"Type",hint:m?"Not changing.":"Backend and model catalog."},o.createElement("select",{className:`ps-budget-input${m?" is-static":""}`,"aria-label":"Provider type",value:g,disabled:m,onChange:X=>{i?.(),b(X.target.value)}},t.length===0?o.createElement("option",{value:""},"No provider types are listed on this deployment"):t.map(X=>o.createElement("option",{key:X.id,value:X.id},X.id)))),L?o.createElement(Ge,{label:"Authentication",hint:"Nothing is stored. The worker mints a short-lived token for each request."},o.createElement("div",{className:"ps-budget-input is-static",role:"note"},"Use the Workload Identity configured in the worker")):o.createElement(Ge,{label:m?B?"New GitHub Copilot token":"New API key":B?"GitHub Copilot token":"API key",hint:m?"Replaces the current one. The existing key is never shown.":"Paste the token value."},o.createElement("input",{className:"ps-budget-input",type:"password",autoComplete:"off","aria-label":m?B?"New GitHub Copilot token":"New API key":B?"GitHub Copilot token":"API key",value:y,placeholder:"Paste token",onChange:X=>{i?.(),S(X.target.value)},onKeyDown:X=>{X.key==="Enter"&&U&&V()}})),m?null:o.createElement(Ge,{label:"Base URL",hint:"Optional."},o.createElement("input",{className:"ps-budget-input",value:w,placeholder:"https://…","aria-label":"Base URL",onChange:X=>k(X.target.value)})),I&&!m?o.createElement(Ge,{label:"Access",hint:"It runs on the worker's own identity, which belongs to the organization, so it cannot be personal."},o.createElement("div",{className:"ps-budget-input is-static",role:"note"},"Shared")):s&&!m?o.createElement(Ge,{label:"Access"},o.createElement($t,{value:E?"shared":"mine",onChange:X=>x(X==="shared"),label:"Access",options:[{value:"shared",label:"Shared"},{value:"mine",label:"Only me"}]})):null)}function ov(t){const e=t.budget||{};return[!!t.ui?.budgetOpen,e.loading,e.refreshing,e.loaded,e.error,e.grid,e.paused,e.overall,e.selectedProvider,e.selectedScope,e.missingProvider,e.series,e.tab,e.summary,t.auth?.authorization?.role,t.admin?.profile]}const av=[14,30,90],lv=[{id:"all",label:"All providers"},{id:"shared",label:"Shared providers"},{id:"users",label:"User providers"}];function cv(t){if(t.preset==="all")return"All providers";if(t.preset==="shared")return"Shared providers";if(t.preset==="users")return"User providers";const e=t.selectedProviders.length;return e===0?"No providers":e===1?t.selectedProviders[0]:`${e} providers`}function dv({view:t,onChange:e}){const[s,n]=o.useState(!1),r=o.useRef(null);o.useEffect(()=>{if(!s)return;const d=p=>{r.current&&!r.current.contains(p.target)&&n(!1)},u=p=>{p.key==="Escape"&&n(!1)};return document.addEventListener("pointerdown",d),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",d),document.removeEventListener("keydown",u)}},[s]);const i=d=>d==="all"?[]:t.providers.filter(u=>d==="shared"?u.class==="shared":u.class!=="shared").map(u=>u.name),a=new Set(t.preset==="all"?t.providers.map(d=>d.name):t.preset==="custom"?t.selectedProviders:i(t.preset)),l=d=>{e({preset:d,providers:i(d)}),n(!1)},c=d=>{const u=new Set(a);u.has(d)?u.delete(d):u.add(d),e({preset:"custom",providers:Array.from(u)})};return o.createElement("div",{className:"ps-summary-picker",ref:r},o.createElement("button",{type:"button",className:`ps-mini-button ps-summary-picker__button${s?" is-open":""}`,"aria-haspopup":"listbox","aria-expanded":s,"aria-label":"Providers filter",onClick:()=>n(d=>!d)},cv(t)," ",o.createElement("span",{"aria-hidden":"true"},"▾")),s?o.createElement("div",{className:"ps-summary-picker__menu",role:"listbox","aria-label":"Providers"},lv.map(d=>o.createElement("button",{key:d.id,type:"button",role:"option","aria-selected":t.preset===d.id,className:`ps-summary-picker__preset${t.preset===d.id?" is-on":""}`,onClick:()=>l(d.id)},d.label)),o.createElement("div",{className:"ps-summary-picker__rule","aria-hidden":"true"}),o.createElement("button",{type:"button",className:"ps-summary-picker__preset is-clear",onClick:()=>e({preset:"custom",providers:[]})},"Clear all"),t.providers.length===0?o.createElement("div",{className:"ps-summary-picker__empty"},"No providers to choose from."):t.providers.map(d=>o.createElement("label",{key:d.name,className:"ps-summary-picker__row"},o.createElement("input",{type:"checkbox",checked:a.has(d.name),onChange:()=>c(d.name),"aria-label":`Include ${d.name}`}),o.createElement("span",{className:"ps-summary-picker__name"},d.name),o.createElement("span",{className:`ps-scope-badge is-${d.class}`},d.class==="shared"?"shared":"user")))):null)}function _e(t){return J(Number(t)||0)}function xd(t){const e=t.map(i=>i.total),s=Math.max(0,...e),n=e.filter(i=>i>0).sort((i,a)=>i-a),r=n.length?n[Math.floor(n.length/2)]:0;return r>0&&s>r*10}function uv({series:t}){const a=t.map(S=>S.total),l=Math.max(0,...a),c=xd(t),d=S=>c?Math.log10(1+S):S,u=d(l)||1,p=160,m=S=>p-d(S)/u*p,f=Math.max(1,t.length),h=662/f,g=Math.max(3,h*.66),b=c?[0,...Array.from({length:Math.floor(Math.log10(Math.max(10,l)))},(S,w)=>Math.pow(10,w+1))].filter(S=>S<=l||S===0).map(S=>({f:d(S)/u,label:_e(S)})):[0,.25,.5,.75,1].map(S=>({f:S,label:_e(S*l)})),y=f>40?10:f>20?5:1;return o.createElement("svg",{className:"ps-summary-chart",viewBox:"0 0 720 190",role:"img","aria-label":`Tokens per day, ${t.length} days${c?", log scale":""}`},b.map(S=>o.createElement("g",{key:S.label+S.f},o.createElement("line",{x1:58,x2:720,y1:8+p-S.f*p,y2:8+p-S.f*p,className:"ps-summary-chart__grid"}),o.createElement("text",{x:52,y:8+p-S.f*p+3,className:"ps-summary-chart__tick",textAnchor:"end"},S.label))),t.map((S,w)=>{const k=58+w*h+(h-g)/2,E=Math.min(S.input,S.cacheRead),x=Math.min(S.input-E,S.cacheWrite),v=S.input-E-x,P=v+E,N=S.input,_=N+S.output,D=8+p,L=8+m(v),I=8+m(P),C=8+m(N),U=8+m(_),B=`${S.day}: ${_e(S.total)} tokens · in ${_e(S.input)} (cache r ${_e(S.cacheRead)} · w ${_e(S.cacheWrite)}) · out ${_e(S.output)} · ${S.turns} turns`;return o.createElement("g",{key:S.day,className:"ps-summary-chart__bar"},o.createElement("title",null,B),o.createElement("rect",{x:k,y:L,width:g,height:Math.max(0,D-L),className:"is-in"}),o.createElement("rect",{x:k,y:I,width:g,height:Math.max(0,L-I),className:"is-cache"}),o.createElement("rect",{x:k,y:C,width:g,height:Math.max(0,I-C),className:"is-cache-w"}),o.createElement("rect",{x:k,y:U,width:g,height:Math.max(0,C-U),className:"is-out"}),w%y===0||w===f-1?o.createElement("text",{x:k+g/2,y:184,className:"ps-summary-chart__day",textAnchor:"middle"},S.day.slice(5)):null)}))}function pv({values:t}){const e=Math.max(0,...t);return o.createElement("span",{className:"ps-summary-spark","aria-hidden":"true",style:{gridAutoColumns:t.length>30?"2px":"4px"}},t.map((s,n)=>o.createElement("i",{key:n,style:{height:`${e>0?Math.max(s>0?8:0,s/e*100):0}%`}})))}function br({label:t,w:e}){return o.createElement("div",{className:"ps-summary-kpi"},o.createElement("div",{className:"ps-summary-kpi__label"},t),o.createElement("div",{className:"ps-summary-kpi__value"},_e(e.total)),o.createElement("div",{className:"ps-summary-kpi__split",title:"Total is input + output. Cache read and write are parts of the input, not additions to it."},o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-in"}),"in ",_e(e.input)),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-cache"}),"cache r ",_e(e.cacheRead)),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-cache-w"}),"w ",_e(e.cacheWrite)),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-out"}),"out ",_e(e.output)),o.createElement("span",null,`· ${e.turns} turns`)))}function mv(t){const e=t.budget?.summary||{};return[e.loading,e.error,e.fetchedAt,e.days,e.preset,(e.providers||[]).join(","),(t.budget?.grid||[]).length]}function fv({controller:t}){const e=ee(t,mv,Le),s=o.useMemo(()=>mf(t.getState()),[t,e]);o.useEffect(()=>{!s.loaded&&!s.loading&&!s.error&&t.loadUsageSummary().catch(()=>{})},[t]);const n=l=>t.setUsageSummaryFilter({days:l}).catch(()=>{}),r=({preset:l,providers:c})=>t.setUsageSummaryFilter({preset:l,providers:c}).catch(()=>{}),i=s.classes.filter(l=>l.total>0),a=`last ${s.days} days`;return o.createElement("div",{className:`ps-summary${s.loading?" is-loading":""}`},o.createElement("div",{className:"ps-summary__filters"},o.createElement(dv,{view:s,onChange:r}),o.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":"Window"},av.map(l=>o.createElement("button",{key:l,type:"button",className:`ps-budget-seg__button${s.days===l?" is-on":""}`,"aria-pressed":s.days===l,"aria-label":`Last ${l} days`,onClick:()=>n(l)},`${l}d`))),o.createElement("span",{className:"ps-summary__scope"},s.scope==="cluster"?"Whole cluster, system sessions included":"Your own turns")),s.error?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"The summary could not be read. "),o.createElement("div",{className:"ps-budget-sub"},s.error)):null,o.createElement("div",{className:"ps-summary__kpis"},o.createElement(br,{label:"Today (UTC)",w:s.windows.day}),o.createElement(br,{label:"Last 7 days",w:s.windows.week}),o.createElement(br,{label:"Last 30 days",w:s.windows.month})),o.createElement("div",{className:"ps-summary__card"},o.createElement("div",{className:"ps-summary__card-head"},o.createElement("b",null,"Tokens per day"),o.createElement("span",{className:"ps-summary__legend"},o.createElement("span",{title:"Prompt tokens that were neither served from nor written to the cache"},o.createElement("i",{className:"ps-summary-dot is-in"}),"input"),o.createElement("span",{title:"The part of the input served from the cache"},o.createElement("i",{className:"ps-summary-dot is-cache"}),"cache read"),o.createElement("span",{title:"The part of the input written to the cache"},o.createElement("i",{className:"ps-summary-dot is-cache-w"}),"cache write"),o.createElement("span",null,o.createElement("i",{className:"ps-summary-dot is-out"}),"output")),o.createElement("span",{className:"ps-summary__muted"},`${a} · ${_e(s.windowTotal)} tokens`),xd(s.series)?o.createElement("span",{className:"ps-summary__tag",title:"One day is more than ten times the median, so the axis is log10 — otherwise every other day is a hairline."},"log scale"):null),s.windowTotal>0||s.loaded?o.createElement(uv,{series:s.series}):null,i.length>1?o.createElement("div",{className:"ps-summary__muted"},"By charge: ",i.map((l,c)=>`${c?" · ":""}${l.chargeClass} ${_e(l.total)}`).join("")):null),o.createElement("div",{className:"ps-summary__card"},o.createElement("div",{className:"ps-summary__card-head"},o.createElement("b",null,"By model"),o.createElement("span",{className:"ps-summary__muted"},`${a} · across providers, efforts and context tiers`)),s.models.length===0?o.createElement("div",{className:"ps-budget-empty"},s.loaded?"No token usage in this window.":s.loading?"Reading…":""):o.createElement("div",{className:"ps-summary__table-wrap"},o.createElement("table",{className:"ps-summary__table"},o.createElement("thead",null,o.createElement("tr",null,[["Model"],["Turns"],["Providers","Distinct provider names in the ledger for this window — including providers since deleted"],["Input","Prompt tokens, including what was served from and written to the cache"],["Output"],["Cache read","The part of Input served from the cache"],["Cache write","The part of Input written to the cache"],["Total","Input + Output"],["Share"],["Trend"]].map(([l,c])=>o.createElement("th",{key:l,title:c},l)))),o.createElement("tbody",null,s.models.map(l=>o.createElement("tr",{key:l.model},o.createElement("td",{className:"is-model"},l.model),o.createElement("td",null,l.turns),o.createElement("td",null,l.providers),o.createElement("td",null,_e(l.input)),o.createElement("td",null,_e(l.output)),o.createElement("td",null,_e(l.cacheRead)),o.createElement("td",null,_e(l.cacheWrite)),o.createElement("td",{className:"is-total"},_e(l.total)),o.createElement("td",{className:"is-share"},o.createElement("i",{className:"ps-summary-share",style:{width:`${Math.max(1,Math.round(l.share*100))}px`}}),`${(l.share*100).toFixed(l.share<.1?1:0)}%`),o.createElement("td",null,o.createElement(pv,{values:l.sparkline})))))))))}function hv({controller:t}){const e=ee(t,ov,Le),s=o.useMemo(()=>ff(t.getState()),[t,e]),n=o.useMemo(()=>t.getState().budget?.grid||[],[t,e]),[r,i]=o.useState([]),[a,l]=o.useState(new Map),[c,d]=o.useState(null),u=o.useCallback(()=>{typeof t.transport.getDefaults=="function"&&Promise.resolve(t.transport.getDefaults()).then(L=>d(L||null)).catch(()=>{})},[t]);o.useEffect(()=>{let L=!0;return typeof t.transport.listModels=="function"&&Promise.resolve(t.transport.listModels()).then(I=>{L&&i(QS(I))}).catch(()=>{}),typeof t.transport.listProviders=="function"&&Promise.resolve(t.transport.listProviders()).then(I=>{if(!L)return;const C=new Map;for(const U of I?.providers||[])C.set(U.name,U.typeId||"");l(C)}).catch(()=>{}),u(),()=>{L=!1}},[t,u]),o.useEffect(()=>{const L=t.getState().budget||{};!L.loaded&&!L.loading&&!L.error&&t.loadProviderTable().catch(()=>{})},[t]),o.useEffect(()=>{const L=setInterval(()=>{t.refreshProviderTable().catch(()=>{})},6e4);return()=>clearInterval(L)},[t]),o.useEffect(()=>{const L=I=>{if(I.key!=="Escape")return;const C=I.target,U=C&&C.tagName;U==="SELECT"||U==="INPUT"||U==="TEXTAREA"||t.getState().ui.modal||document.querySelector(".ps-budget-sheet")||(I.preventDefault(),I.stopPropagation(),t.closeBudget())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[t]);const[p,m]=o.useState(null),[f,h]=o.useState(!1),[g,b]=o.useState(null),y=o.useRef(null),S=L=>{y.current=typeof document<"u"?document.activeElement:null,b(null),h(!1),m(L)},w=o.useCallback(()=>{m(null),b(null),h(!1);const L=y.current;y.current=null,L&&typeof L.focus=="function"&&document.contains(L)&&L.focus()},[]),k=async(L,{keepOpen:I=!1,onDone:C=null}={})=>{h(!0),b(null);const U=await L();if(h(!1),!U||U.ok!==!0){b(U?.error||"The change was refused.");return}I||w(),C&&C(U.result||null)},E=L=>t.dispatch({type:"ui/status",text:L}),x=s.selected,v=s.selectedProviderRow,P=x?XS(r,{name:x.providerName,typeId:a.get(x.providerName)||""}):[];let N=null;p?.kind==="edit"&&v&&(N=o.createElement(rv,{row:v,rawRows:n,models:P,isAdmin:s.isAdmin,initialPeriod:p.period||"day",initialScope:p.scope||"*",busy:f,error:g,onCancel:w,onRun:(L,I)=>{const C=x.providerName;if(L==="limit")return k(()=>t.setProviderLimit({provider:C,...I}),{onDone:U=>{const B=Number(U?.seededTokens)||0;E(B>0?`Limit saved. This period had already spent ${J(B)} tokens, and they count against it.`:"Limit saved. This period has spent nothing against it yet.")}});if(L==="removeLimit")return k(()=>t.removeProviderLimit({provider:C,...I}),{onDone:()=>E(`That period no longer caps ${C}.`)});if(L==="allowance")return k(()=>t.setProviderAllowance({provider:C,pct:I.pct}),{onDone:()=>E(I.pct>=100?`Everyone shares the whole of ${C} again.`:`Each person may now use up to ${I.pct}% of each of ${C}'s limits.`)});if(L==="hold")return k(()=>t.setProviderHold({provider:C,...I}),{onDone:()=>{if(I.release){E(`The hold on ${C} is released. Sessions waiting on it wake up.`);return}const U=(t.getState().budget?.grid||[]).find(V=>V.providerName===C&&V.rowKind!=="model"),B=U?.holdIndefinite===!0||(U?.holdUntilUtc?Date.parse(U.holdUntilUtc)>Date.now():!1);E(B?`${C} is on hold. No new turn runs against it until it is released.`:`${C} is NOT on hold: the time given has already passed.`)}})}}));const _=o.createElement("div",{className:"ps-budget-head"},o.createElement("div",{className:"ps-budget-headline"},o.createElement("span",{className:"ps-budget-coin","aria-hidden":"true"},"◎"),o.createElement("h2",{className:"ps-budget-h"},"Providers & Budgets"),o.createElement("span",{className:"ps-budget-sub"},"Usage and limits")),o.createElement("div",{className:"ps-budget-head-actions"},o.createElement(he,{icon:"↻",label:"Refresh providers and budgets",className:"ps-mini-button",disabled:s.loading||s.refreshing,onClick:()=>t.refreshProviderTable().catch(()=>{})})));let D;return s.failed?D=o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"Providers and budgets could not be read. ",o.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>t.loadProviderTable().catch(()=>{})},"Try again")),o.createElement("div",{className:"ps-budget-sub"},s.error)):s.loading&&!s.loaded?D=o.createElement("div",{className:"ps-budget-empty"},"Reading providers and budgets…"):D=o.createElement(o.Fragment,null,s.stale?o.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},o.createElement("div",null,"These figures are from an earlier read. The most recent read failed."),o.createElement("div",{className:"ps-budget-sub"},s.error)):null,s.paused.count>0?o.createElement("div",{className:`ps-budget-waiting${s.paused.stale?" is-stale":""}`,role:"status"},s.paused.sentence," ",s.paused.provider?o.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>{s.selectedProvider!==s.paused.provider&&t.selectBudgetProvider(s.paused.provider).catch(()=>{})}},`Open ${s.paused.provider}`):null,s.paused.stale?o.createElement("span",{className:"ps-budget-sub"}," This line is from an earlier read — the last one failed."):null):null,s.paused.count===0&&s.paused.error?o.createElement("div",{className:"ps-budget-waiting is-stale",role:"status"},"The list of waiting sessions could not be read. The figures below were read successfully."):null,s.missing?o.createElement("div",{className:"ps-budget-waiting is-missing",role:"status"},s.missing.sentence," ",o.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>{t.closeBudget(),t.openAdminConsole()}},"Open Model Providers")):null,o.createElement("div",{className:`ps-budget-body${s.refreshing?" is-refreshing":""}`},o.createElement(tv,{controller:t,view:s,defaults:c}),o.createElement("div",{className:"ps-budget-actions"},o.createElement(he,{icon:o.createElement(bd),label:"Edit usage policy",className:"ps-mini-button",disabled:!v||!v.manageable,onClick:()=>S({kind:"edit",scope:x?.kind==="model"?x.scope:"*"})}),o.createElement("span",{className:"ps-budget-sub"},x?x.providerName:"No provider selected")),o.createElement("div",{className:"ps-budget-foot ps-budget-sub"},"Manage providers and defaults in Admin Console."),x?o.createElement(sv,{controller:t,view:s}):null,x?o.createElement(nv,{view:s}):null)),o.createElement("div",{className:"ps-budget-surface"},_,o.createElement("div",{className:"ps-budget-tabs",role:"tablist"},[["providers","Providers"],["summary","Cluster summary"]].map(([L,I])=>o.createElement("button",{key:L,type:"button",role:"tab","aria-selected":(t.getState().budget?.tab||"providers")===L,className:`ps-budget-tab${(t.getState().budget?.tab||"providers")===L?" is-on":""}`,onClick:()=>t.setBudgetTab(L)},I))),(t.getState().budget?.tab||"providers")==="summary"?o.createElement("div",{className:"ps-budget"},o.createElement(fv,{controller:t})):o.createElement("div",{className:"ps-budget"},D),N)}function gv({controller:t}){const e=ee(t,y=>y.ui.themeId),s=ee(t,y=>!!y.ui.touchScale),n=ft(e),r=ee(t,y=>({rawModal:y.ui.modal,themePicker:Sh(y),modelPicker:zf(y),reasoningEffortPicker:Kf(y),contextTierPicker:Vf(y),sessionAgentPicker:qf(y),sessionGroupPicker:Yf(y),sessionGroupName:Qf(y),artifactPicker:sh(y),logFilter:eh(y),filesFilter:th(y),historyFormat:bh(y),renameSession:Xf(y),sessionOwnerFilter:Jf(y),artifactUpload:Zf(y),confirm:vh(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),Le),i=r.rawModal,a=o.useRef(null),l=o.useRef(null),c=o.useRef(null),[d,u]=o.useState(""),p=i?.type==="sessionOwnerFilter";if(o.useEffect(()=>{p||u("")},[p]),o.useEffect(()=>{if(i?.type!=="renameSession"||!r.renameSession)return;const y=a.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(r.renameSession.cursorIndex,r.renameSession.cursorIndex)}},[i?.type,r.renameSession?.cursorIndex,r.renameSession?.value]),o.useEffect(()=>{if(i?.type!=="sessionGroupName"||!r.sessionGroupName)return;const y=l.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(r.sessionGroupName.cursorIndex,r.sessionGroupName.cursorIndex)}},[i?.type,r.sessionGroupName?.cursorIndex,r.sessionGroupName?.value]),o.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const y=c.current;if(!y)return;const S=y.querySelector(".ps-list-button.is-selected");S&&typeof S.scrollIntoView=="function"&&S.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,r.themePicker?.selectedRowIndex,r.modelPicker?.selectedRowIndex,r.reasoningEffortPicker?.selectedRowIndex,r.contextTierPicker?.selectedRowIndex,r.sessionAgentPicker?.selectedRowIndex,r.sessionGroupPicker?.selectedRowIndex,r.artifactPicker?.selectedRowIndex,r.sessionOwnerFilter?.selectedRowIndex,r.logFilter?.selectedRowIndex,r.filesFilter?.selectedRowIndex,r.historyFormat?.selectedRowIndex]),!i)return null;const m=()=>t.handleCommand(M.CLOSE_MODAL).catch(()=>{}),f=()=>o.createElement("label",{className:"ps-modal-toggle",title:"Larger type and bigger hit targets, for phones and touch screens."},o.createElement("input",{type:"checkbox",checked:s,onChange:y=>t.dispatch({type:"ui/touchScale",enabled:y.target.checked})}),o.createElement("span",null,"Mobile")),h=(y,S="Apply",w=null,k=null)=>{const E=Array.isArray(y.rows)?y.rows:[],x=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,v=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",P=x&&x.length===E.length?E.map((N,_)=>{const D=x[_],L=Array.isArray(N)?N:je([N])[0]?.runs||[{text:N?.text||"",color:N?.color}];if(D==null||D<0)return o.createElement("div",{key:`row:${_}`,className:"ps-line ps-modal-list-heading-line"},o.createElement(ze,{runs:L,theme:n}));const I=i.items?.[D];return o.createElement("button",{key:I?.id||`row:${_}`,type:"button",className:`ps-list-button ps-modal-list-button${D===i.selectedIndex?" is-selected":""}${v?" is-hanging":""}${I?.disabled?" is-disabled":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:D})}},o.createElement("div",{className:"ps-line ps-modal-list-line"},o.createElement(ze,{runs:L,theme:n})))}):(i.items||[]).flatMap((N,_,D)=>{const L=o.createElement("button",{key:N.id||_,type:"button",className:`ps-list-button ps-modal-list-button${_===i.selectedIndex?" is-selected":""}${v?" is-hanging":""}${N?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:_})},o.createElement("div",{className:"ps-line ps-modal-list-line"},o.createElement(ze,{runs:Array.isArray(E?.[_])?E[_]:je([E?.[_]])[0]?.runs||[{text:E?.[_]?.text||"",color:E?.[_]?.color}],theme:n})));return N?.group&&N.group!==D[_-1]?.group?[o.createElement("div",{key:`group:${N.group}`,className:"ps-modal-list-group","aria-hidden":"true"},N.group),L]:[L]});return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:`ps-modal is-list${i.type==="themePicker"?" is-theme-picker":""}`,onClick:N=>N.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},y.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),k,o.createElement("div",{className:"ps-modal-grid"},o.createElement("div",{ref:c,className:"ps-modal-list"},P),o.createElement("div",{className:"ps-modal-details"},o.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),je(y.detailsLines||[]).map((N,_)=>o.createElement(We,{key:`detail:${_}`,line:N,theme:n,className:"ps-modal-detail-line"})))),o.createElement("div",{className:"ps-modal-footer"},w,o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},S))))};if(i.type==="confirm"&&r.confirm){const y=!!i.alert,S=!y&&i.action==="deleteSession",w=i.action==="regenerateSession",k=i.extras||{};return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:E=>E.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.confirm.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},o.createElement("p",{style:{color:"#94a3b8",margin:0}},r.confirm.message)),w?o.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},o.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",o.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:k.distillMode||"llm",onChange:E=>t.updateConfirmExtras({distillMode:E.currentTarget.value})},o.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),o.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(k.distillMode||"llm")==="llm"?o.createElement(yv,{controller:t,extras:k}):null,(k.distillMode||"llm")==="llm"?o.createElement("textarea",{className:"ps-modal-input",style:{width:"100%",minHeight:"64px",resize:"vertical",fontFamily:"inherit",fontSize:"13px"},placeholder:'Distilling instructions (optional) — e.g. "preserve every SQL snippet verbatim"',value:k.instructions||"",maxLength:4e3,onChange:E=>t.updateConfirmExtras({instructions:E.currentTarget.value})}):null):null,o.createElement("div",{className:"ps-modal-footer"},y?null:o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:`ps-modal-button ${S?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},r.confirm.confirmLabel))))}if(i.type==="themePicker"&&r.themePicker)return h(r.themePicker,"Apply Theme",f());const g=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&r.modelPicker)return h(r.modelPicker,g);if(i.type==="reasoningEffortPicker"&&r.reasoningEffortPicker)return h(r.reasoningEffortPicker,g);if(i.type==="contextTierPicker"&&r.contextTierPicker)return h(r.contextTierPicker,g);if(i.type==="sessionAgentPicker"&&r.sessionAgentPicker){const y=[["used","Most used","Ordered by how often YOU have started each agent"],["name","Name","Alphabetical by agent name"],["package","Package","Grouped by package name, then agent name"]],S=o.createElement("div",{className:"ps-agent-picker-toolbar"},o.createElement("input",{type:"search",className:"ps-agent-picker-search","data-modal-search":"true",placeholder:"Search agents, packages, tools…",value:i.query||"",autoFocus:!0,"aria-label":"Search agents",onChange:w=>t.setAgentPickerQuery(w.target.value),onKeyDown:w=>{["ArrowUp","ArrowDown","Enter","Escape","Tab"].includes(w.key)||w.stopPropagation()}}),o.createElement("div",{className:"ps-agent-picker-sorts",role:"group","aria-label":"Sort agents"},y.map(([w,k,E])=>o.createElement("button",{key:w,type:"button",className:`ps-agent-picker-sort${(i.sort||"used")===w?" is-on":""}`,title:E,"aria-pressed":(i.sort||"used")===w?"true":"false",onClick:()=>t.setAgentPickerSort(w)},k))));return h(r.sessionAgentPicker,"Create Session",null,S)}if(i.type==="sessionGroupPicker"&&r.sessionGroupPicker)return h(r.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&r.artifactPicker)return h(r.artifactPicker,r.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&r.sessionOwnerFilter){const y=r.sessionOwnerFilter,S=Array.isArray(y.rows)?y.rows:[],w=d.trim().toLowerCase(),k=x=>{const v=S?.[x];return(Array.isArray(v)?v:je([v])[0]?.runs||[]).map(N=>N?.text||"").join("")||String(v?.text||"")},E=(i.items||[]).map((x,v)=>v).filter(x=>{if(!w)return!0;const v=(i.items||[])[x]||{};return`${k(x)} ${v.label||""} ${v.description||""}`.toLowerCase().includes(w)});return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-list",onClick:x=>x.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},y.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{className:"ps-modal-input ps-modal-search","data-modal-search":"true",value:d,placeholder:"Search people…",autoFocus:!0,onChange:x=>u(x.currentTarget.value),onKeyDown:x=>{x.key==="Escape"&&d&&(x.stopPropagation(),u(""))}}),o.createElement("div",{className:"ps-modal-grid"},o.createElement("div",{ref:c,className:"ps-modal-list"},E.length===0?o.createElement("div",{className:"ps-empty-state"},`No one matches "${d}".`):null,E.map(x=>(v=>o.createElement("button",{key:v.id||x,type:"button",className:`ps-list-button ps-modal-list-button${x===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(x)},o.createElement("div",{className:"ps-line ps-modal-list-line"},o.createElement(ze,{runs:Array.isArray(S?.[x])?S[x]:je([S?.[x]])[0]?.runs||[{text:S?.[x]?.text||"",color:S?.[x]?.color}],theme:n}))))((i.items||[])[x]||{}))),o.createElement("div",{className:"ps-modal-details"},o.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),je(y.detailsLines||[]).map((x,v)=>o.createElement(We,{key:`detail:${v}`,line:x,theme:n,className:"ps-modal-detail-line"})))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:m},"Done"))))}if(i.type==="renameSession"&&r.renameSession)return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.renameSession.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{ref:a,className:"ps-modal-input",value:r.renameSession.value,placeholder:r.renameSession.placeholder,onChange:y=>t.setRenameSessionValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),o.createElement("div",{className:"ps-modal-details"},je(r.renameSession.helpLines||[]).map((y,S)=>o.createElement(We,{key:`help:${S}`,line:y,theme:n,className:"ps-modal-detail-line"}))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&r.sessionGroupName)return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.sessionGroupName.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{ref:l,className:"ps-modal-input",value:r.sessionGroupName.value,placeholder:r.sessionGroupName.placeholder,onChange:y=>t.setSessionGroupNameValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),o.createElement("div",{className:"ps-modal-details"},je(r.sessionGroupName.helpLines||[]).map((y,S)=>o.createElement(We,{key:`help:${S}`,line:y,theme:n,className:"ps-modal-detail-line"}))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},r.sessionGroupName.mode==="rename"?"Rename":"Create and Move"))));if(i.type==="terminatePicker"){const y=Number(i.bulkCount)>1,S=!!i.systemRestart,w=String(i.sessionTitle||"").trim()||"this session",k=Number(i.bulkCount)||0,E=y?`What should happen to the ${k} selected sessions? Choose an action; you'll be asked to confirm.`:S?`How should "${w}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${w}"? Choose an action; you'll be asked to confirm.`,x=v=>()=>{t.pickTerminateAction(v).catch(()=>{})};return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:v=>v.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},o.createElement("p",{style:{color:"#94a3b8",margin:0}},E)),o.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.canRegenerate?o.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},title:"Archive and distill the transcript, then rebuild context fresh at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved.",onClick:x("regenerate")},"Regenerate Context"):null,o.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:x("complete")},y?`Mark ${k} Completed`:S?"Complete & Restart":"Mark Completed"),o.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:x("cancel")},y?`Cancel ${k} Sessions`:S?"Terminate & Restart":"Cancel Session"),o.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:x("delete")},y?`Hard Delete ${k} Sessions`:S?"Hard Delete & Restart":"Delete Session")),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Close"))))}if(i.type==="artifactUpload"&&r.artifactUpload)return o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},r.artifactUpload.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("input",{className:"ps-modal-input",value:r.artifactUpload.value,placeholder:r.artifactUpload.placeholder,onChange:y=>t.setArtifactUploadValue(y.currentTarget.value,y.currentTarget.selectionStart||y.currentTarget.value.length),autoFocus:!0}),o.createElement("div",{className:"ps-modal-details"},je(r.artifactUpload.helpLines||[]).map((y,S)=>o.createElement(We,{key:`help:${S}`,line:y,theme:n,className:"ps-modal-detail-line"}))),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(M.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const b=i.type==="logFilter"?r.logFilter:i.type==="filesFilter"?r.filesFilter:i.type==="historyFormat"?r.historyFormat:null;return b?o.createElement("div",{className:"ps-modal-backdrop",onClick:m},o.createElement("div",{className:"ps-modal is-wide",onClick:y=>y.stopPropagation()},o.createElement("div",{className:"ps-modal-header"},o.createElement("div",{className:"ps-modal-title"},b.title),o.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),o.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((y,S)=>{const w=i.type==="filesFilter"?r.filesFilterState?.[y.id]||y.options?.[0]?.id:i.type==="historyFormat"?r.historyFormatState:r.logsFilter?.[y.id]||y.options?.[0]?.id;return o.createElement("div",{key:y.id||S,className:"ps-filter-column"},o.createElement("div",{className:"ps-filter-title"},y.label),(y.options||[]).map(k=>o.createElement("button",{key:k.id,type:"button",className:`ps-filter-option${k.id===w?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:S}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:k.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[y.id]:k.id}}),t.ensureFilesForScope(k.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[y.id]:k.id}})}},k.label)))})),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:m},"Done")))):null}function yv({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(d=>d.qualifiedName===e.distillerModel)||null,r=n?.supportedReasoningEfforts||[],i=n?.supportedContextTiers||[],a={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},l={flex:"1",padding:"4px 8px"},c=d=>t.updateConfirmExtras(d);return o.createElement(o.Fragment,null,o.createElement("label",{style:a},"Distiller model",o.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerModel||"",onChange:d=>c({distillerModel:d.currentTarget.value,distillerEffort:"",distillerContextTier:""})},o.createElement("option",{value:""},"Deployment default"),s.map(d=>o.createElement("option",{key:d.qualifiedName,value:d.qualifiedName},d.qualifiedName)))),r.length>0?o.createElement("label",{style:a},"Reasoning",o.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerEffort||"",onChange:d=>c({distillerEffort:d.currentTarget.value})},o.createElement("option",{value:""},"Model default"),r.map(d=>o.createElement("option",{key:d,value:d},d)))):null,i.length>0?o.createElement("label",{style:a},"Context",o.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerContextTier||"",onChange:d=>c({distillerContextTier:d.currentTarget.value})},o.createElement("option",{value:""},"Model default"),i.map(d=>o.createElement("option",{key:d,value:d},d==="long_context"?"long context (fits a larger transcript)":d)))):null)}function bv(t,e){o.useEffect(()=>{const s=n=>{const r=n.target,i=r instanceof HTMLElement&&(r.tagName==="TEXTAREA"||r.tagName==="INPUT"||r.tagName==="SELECT"||r.isContentEditable),a=t.getState().ui.modal,l=Mi(t),c=t.getState().ui.inspectorTab,d=t.getState().ui.focusRegion,u=!n.metaKey&&!n.ctrlKey&&!n.altKey,p=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,m=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,f=h=>{const g=wy(l,c,h);t.selectInspectorTab(g).catch(()=>{})};if(!i&&p){n.preventDefault(),t.handleCommand(M.OPEN_THEME_PICKER).catch(()=>{});return}if(!i&&m){n.preventDefault(),t.handleCommand(M.OPEN_MODEL_PICKER).catch(()=>{});return}if(a&&!i){if(n.key==="Escape"||a.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(M.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||a.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(M.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(M.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(M.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(M.MODAL_NEXT).catch(()=>{}));return}if(a&&i&&r instanceof HTMLElement&&r.dataset.modalSearch==="true"){if(n.key==="Escape"){n.preventDefault(),t.handleCommand(M.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"){n.preventDefault(),t.handleCommand(M.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="ArrowUp"){n.preventDefault(),t.handleCommand(M.MODAL_PREV).catch(()=>{});return}if(n.key==="ArrowDown"){n.preventDefault(),t.handleCommand(M.MODAL_NEXT).catch(()=>{});return}return}if(!i){if(n.key==="r"&&u&&d!=="prompt"){n.preventDefault(),t.handleCommand(M.REFRESH).catch(()=>{});return}if(n.key==="n"&&u){n.preventDefault(),t.handleCommand(M.NEW_SESSION).catch(()=>{});return}if(d==="inspector"&&c==="files"&&(n.key==="u"&&u||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(M.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(M.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="x"&&u){n.preventDefault(),t.handleCommand(M.DELETE_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="o"&&u){n.preventDefault(),t.handleCommand(M.OPEN_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.OPEN_FILES_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="stats"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.TOGGLE_STATS_VIEW).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="v"&&u){n.preventDefault(),t.handleCommand(M.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(M.TOGGLE_LOG_TAIL).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.OPEN_LOG_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(M.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="r"&&u){n.preventDefault(),t.handleCommand(M.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(M.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&u){n.preventDefault(),t.handleCommand(M.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&u){n.preventDefault(),t.handleCommand(M.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&u){n.preventDefault(),t.handleCommand(M.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&u){n.preventDefault(),t.handleCommand(M.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(M.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&u&&d==="inspector"){n.preventDefault(),f(1);return}if(n.key==="["&&u){n.preventDefault(),t.handleCommand(M.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&u){n.preventDefault(),t.handleCommand(M.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&u){n.preventDefault(),t.handleCommand(M.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&u){n.preventDefault(),t.handleCommand(M.GROW_SESSION_PANE).catch(()=>{});return}if(d==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),f(-1);return}if(d==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),f(1);return}if(d==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(M.MOVE_SESSION_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(M.MOVE_SESSION_DOWN).catch(()=>{});return}if(d==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(M.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(M.PAGE_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(M.PAGE_DOWN).catch(()=>{});return}if(d==="sessions"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(M.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(M.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(M.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&u){n.preventDefault(),t.handleCommand(M.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(M.SCROLL_BOTTOM).catch(()=>{});return}if(d!=="prompt"&&n.key==="h"&&u){n.preventDefault(),t.handleCommand(M.FOCUS_LEFT).catch(()=>{});return}if(d!=="prompt"&&n.key==="l"&&u){n.preventDefault(),t.handleCommand(M.FOCUS_RIGHT).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(M.MOVE_FILE_UP).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(M.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(M.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(M.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(M.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Sv(t){if(!t)return"Unknown user";const e=String(t.displayName||"").trim(),s=String(t.email||"").trim();if(e&&s&&e.toLowerCase()!==s.toLowerCase())return`${e} <${s}>`;if(e)return e;if(s)return s;const n=String(t.provider||"").trim(),r=String(t.subject||"").trim();return[n,r].filter(Boolean).join(":")||"user"}function vv({controller:t,mobile:e=!1}){const s=ee(t,gt,Le),n=s.packages||{},r=s.section==="packages",i=s.section==="workers",[a,l]=o.useState(null),[c,d]=o.useState(!1),[u,p]=o.useState(null),[m,f]=o.useState(()=>{const N={wsWidth:440,treePct:44,navWidth:240};try{return{...N,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return N}}),h=o.useCallback(N=>{f(_=>{const D={..._,...N};D.wsWidth=Math.min(900,Math.max(300,Math.round(D.wsWidth))),D.treePct=Math.min(85,Math.max(15,D.treePct)),D.navWidth=Math.min(420,Math.max(170,Math.round(D.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(D))}catch{}return D})},[]),g=o.useCallback(N=>{N.preventDefault(),document.body.style.cursor="col-resize";const _=N.clientX,D=m.navWidth??240,L=C=>h({navWidth:D+(C.clientX-_)}),I=()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",I),document.body.style.cursor=""};window.addEventListener("pointermove",L),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",I)},[m.navWidth,h]);o.useCallback(()=>{t.closeAdminConsole()},[t]);const b=o.useCallback(()=>{l(null),d(!1),p(null),t.dismissAdminModelProviderMutationError()},[t]),y=o.useCallback(async N=>{d(!0),p(null);const _=a?.update?await t.updateAdminProviderCredential({name:N.name,credentials:N.credentials,shared:N.shared===!0}):await t.createAdminProvider(N);if(d(!1),!_?.ok){p(_?.error||`The provider key could not be ${a?.update?"updated":"created"}.`);return}b()},[b,t,a]),S=o.createElement("header",{className:"ps-admin-console__header"},o.createElement("h2",null,s.isAdmin?"Admin Console":"Settings")),w=o.createElement(Cv,{controller:t,view:s,sheetOpen:!!a,onAddPersonal:()=>{t.dismissAdminModelProviderMutationError(),l({shared:!1,github:!0})},onAddShared:()=>{t.dismissAdminModelProviderMutationError(),l({shared:!0,github:!1})},onUpdatePersonal:N=>{t.dismissAdminModelProviderMutationError(),l({update:N,shared:N.class==="shared"})}}),k=o.createElement(wv,{controller:t,view:s}),E=o.createElement(Ev,{controller:t,view:s}),x=r&&n.selectedName?o.createElement(xv,{controller:t,view:s,layout:m,onLayout:h}):null,v=n.addDialog?.open?o.createElement(Nv,{controller:t,dialog:n.addDialog}):null,P=a?o.createElement(iv,{types:s.modelProviders?.providerTypes||[],existingNames:[...s.modelProviders?.sharedProviders||[],...s.modelProviders?.myProviders||[]].map(N=>N.name),isAdmin:s.isAdmin,initialShared:a.shared,updateProvider:a.update||null,initialType:a.github?(s.modelProviders?.providerTypes||[]).find(N=>/github/i.test(N.id))?.id||"":a.update?.typeId||"",initialName:a.update?.name||"",busy:c,error:u,onDirty:()=>p(null),onCancel:b,onConfirm:y}):null;if(e){let N;return r&&n.selectedName?N=o.createElement("div",{className:"ps-admin-mobile-stack"},o.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>t.selectAdminPackage(null)},"← All packages"),E,x):r?N=k:i?N=o.createElement("div",{className:"ps-admin-mobile-stack"},k,o.createElement(Za,{controller:t,view:s})):N=o.createElement("div",{className:"ps-admin-mobile-stack"},k,w),o.createElement("div",{className:"ps-admin-console is-mobile"},S,s.loadError?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,N,v,P)}return o.createElement("div",{className:"ps-admin-console is-workspace"},S,s.loadError?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,o.createElement("div",{className:"ps-admin-workspace",style:x?{gridTemplateColumns:`${m.navWidth}px minmax(0, 1fr) minmax(0, ${m.wsWidth}px)`}:{gridTemplateColumns:`${m.navWidth}px minmax(0, 1fr)`}},o.createElement("div",{className:"ps-admin-nav"},k,o.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:g,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),o.createElement("div",{className:"ps-admin-main"},r?E:i?o.createElement(Za,{controller:t,view:s}):w),x),v,P)}function Za({controller:t,view:e}){const s=e.workers||{},n=s.rows||[],r=s.counts||{};return o.useEffect(()=>{const i=window.setInterval(()=>{t.refreshAdminWorkers()},25e3);return()=>window.clearInterval(i)},[t]),o.createElement("div",{className:"ps-admin-detail ps-admin-workers"},o.createElement("div",{className:"ps-admin-workers__head"},o.createElement("h3",null,"Workers"),s.summaryText?o.createElement("span",{className:"ps-admin-workers__summary"},`${s.summaryText}${r.pools>1?` · ${r.pools} pools`:""}${r.draining?` · ${r.draining} draining`:""}`):null,o.createElement("button",{type:"button",className:"ps-mini-button is-icon",onClick:()=>t.refreshAdminWorkers(),disabled:!!s.loading,title:s.loading?"Refreshing…":"Refresh the worker list","aria-label":"Refresh the worker list"},o.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},o.createElement("path",{d:"M16.2 8.2A6.4 6.4 0 0 0 4.6 6.4M3.8 11.8a6.4 6.4 0 0 0 11.6 1.8"}),o.createElement("path",{d:"M16.4 3.6v4.6h-4.6M3.6 16.4v-4.6h4.6"})))),s.error?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.error):null,s.empty?o.createElement("p",{className:"ps-admin-console__hint"},"No workers registered. Workers appear here on their first heartbeat and self-prune after an hour of silence."):o.createElement("div",{className:"ps-admin-workers__scroll"},o.createElement("table",{className:"ps-admin-workers__table"},o.createElement("thead",null,o.createElement("tr",null,["Worker","Pool","Phase","Heartbeat","Uptime","RSS","Sessions","Loop p99","Packages","SDK"].map(i=>o.createElement("th",{key:i},i)))),o.createElement("tbody",null,n.map(i=>o.createElement("tr",{key:i.id,className:i.live?"is-live":"is-stale"},o.createElement("td",{className:"ps-admin-workers__id",title:i.owner?`owner: ${i.owner}`:void 0},o.createElement("span",{className:`ps-worker-dot${i.live?" is-live":""}`}),i.id,i.substrate&&i.substrate!=="kubernetes"?o.createElement("span",{className:"ps-admin-workers__substrate"},i.substrate):null),o.createElement("td",null,i.pool),o.createElement("td",null,o.createElement("span",{className:`ps-worker-phase is-${i.phase}`},i.phase)),o.createElement("td",null,i.agoText),o.createElement("td",null,i.uptimeText??"—"),o.createElement("td",null,i.rssText??"—"),o.createElement("td",null,i.sessions??"—"),o.createElement("td",null,i.eventLoopText??"—"),o.createElement("td",{title:i.pkgEpoch!=null?`epoch ${i.pkgEpoch}`:void 0},i.pkgText??"—"),o.createElement("td",null,i.sdkVersion??"—")))))))}function wv({controller:t,view:e}){const s=e.packages||{};return o.createElement("nav",{className:"ps-admin-tree"},o.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(e.settingsTree||[]).map(n=>{if(n.kind==="group")return o.createElement("div",{key:n.id,className:"ps-admin-tree__group"},`${n.label}`,o.createElement("span",{className:"ps-admin-tree__count"},String(n.count??0)));const r=n.kind==="package"?()=>t.selectAdminPackage(n.name,{scope:n.scope==="shared"?"shared":"user",...n.scope!=="shared"&&n.owner?.provider&&n.owner?.subject?{owner:{provider:n.owner.provider,subject:n.owner.subject}}:{}}):()=>{n.id==="providers"||n.id==="myProviders"?(t.setAdminSection("providers"),t.setAdminModelProviderPage("mine")):n.id==="sharedProviders"?(t.setAdminSection("providers"),t.setAdminModelProviderPage("shared")):t.setAdminSection(n.id==="agents"?"packages":"workers")};return o.createElement("button",{key:n.id,type:"button",className:`ps-admin-tree__row depth-${n.depth}${n.selected?" is-selected":""}${n.kind==="package"&&!n.enabled?" is-disabled":""}`,onClick:r},n.kind==="package"?n.ownerBadge?o.createElement(Br,{badge:n.ownerBadge}):o.createElement("span",{className:"ps-scope-badge is-shared",title:"shared with the whole deployment"},"S"):null,o.createElement("span",{className:"ps-admin-tree__name"},n.label),n.kind==="package"&&n.semver?o.createElement("span",{className:"ps-admin-tree__ver"},n.semver):null)}),s.loading?o.createElement("div",{className:"ps-admin-tree__hint"},"Loading packages…"):null,s.error?o.createElement("div",{className:"ps-admin-tree__hint is-error"},s.error):null,e.section==="packages"?o.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>t.openAdminAddPackage()},"+ Add package"):null)}function Ev({controller:t,view:e}){const s=e.packages||{},n=s.detail;if(!s.selectedName)return o.createElement("div",{className:"ps-admin-detail is-empty"},o.createElement("h3",null,"Agents"),o.createElement("p",{className:"ps-admin-console__hint"},s.empty?"No agent packages yet. Add one from a GitHub/ADO repo, a tarball URL, or upload a folder — or push from a terminal with `pilotswarm agents push ./my-agents`.":"Select a package from the tree to see its detail, versions, and files."));const r=()=>{window.confirm(`Delete ${n.name}? Every version and its artifacts are removed. Live sessions using its agents will fail on their next turn.`)&&t.runAdminPackageAction("delete")},i=(c,d)=>()=>t.runAdminPackageAction(c,d),a=n.actionPending,l=async()=>{try{await t.transport.saveAgentPackageDownload(n.name,n.activeSemver??null,{scope:n.scope,owner:n.owner??null})}catch(c){window.alert(`Could not download ${n.name}: ${c?.message||c}`)}};return o.createElement("div",{className:"ps-admin-detail"},n.error?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},`Package load failed: ${n.error}`):null,n.loading?o.createElement("p",{className:"ps-admin-console__hint"},"Loading package…"):null,o.createElement("div",{className:"ps-admin-detail__head"},o.createElement("h3",null,n.name),o.createElement("span",{className:`ps-scope-badge is-${n.scope}`},n.scope),n.enabled?null:o.createElement("span",{className:"ps-scope-badge is-off"},"disabled")),n.description?o.createElement("p",{className:"ps-admin-detail__desc"},n.description):null,o.createElement("dl",{className:"ps-admin-detail__meta"},o.createElement("dt",null,"Version"),o.createElement("dd",null,n.activeSemver?`${n.activeSemver} · sha ${n.activeSha12||"?"} · ${n.sizeText}`:"no active version"),n.fleet?[o.createElement("dt",{key:"fk"},"Fleet"),o.createElement("dd",{key:"fv",className:"is-ok"},n.fleet.text)]:null,o.createElement("dt",null,"Created"),o.createElement("dd",null,`${n.createdBy||"unknown"} · ${n.createdAtText}`)),n.agents.length?o.createElement("div",null,o.createElement("div",{className:"ps-admin-detail__label"},"Agents in this package"),o.createElement("div",{className:"ps-admin-detail__chips"},n.agents.map(c=>o.createElement("span",{key:c.name,className:"ps-agent-chip",title:c.description},c.name,c.toolCount?o.createElement("i",null,` · ${c.toolCount} tools`):null)))):null,n.versions.length?o.createElement("div",null,o.createElement("div",{className:"ps-admin-detail__label"},"Versions"),o.createElement("div",{className:"ps-admin-versions"},n.versions.map(c=>o.createElement("div",{key:c.semver,className:`ps-admin-version${c.active?" is-active":""}`},o.createElement("b",null,c.semver),o.createElement("span",null,c.sha12),o.createElement("span",null,c.dateText),c.active?o.createElement("span",{className:"is-ok"},"● active"):n.canEdit?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("pin",c.semver),disabled:!!a},"Pin"):null)))):null,n.scope==="shared"?o.createElement(kv,{controller:t,detail:n,pending:a}):null,n.canEdit?o.createElement("div",{className:"ps-admin-detail__actions"},n.source&&n.canManage?o.createElement("button",{type:"button",className:"ps-primary-button",onClick:i("sync"),disabled:!!a},a==="sync"?"Syncing…":"Sync now"):null,o.createElement("button",{type:"button",className:"ps-primary-button",onClick:()=>t.openAdminUpdatePackage(n.name,n.scope),disabled:!!a,title:`Publish a new version of ${n.name} from a repo folder`},"Update"),n.scope==="user"&&n.hasSharedCounterpart?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("republish",n.activeSemver),disabled:!!a||!n.activeSemver,title:`Publish ${n.name}@${n.activeSemver??"?"} into the existing shared package`},a==="republish"?"Publishing…":`Publish ${n.activeSemver??""} to shared`):n.canManage?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.scope==="shared"?"demote":"promote"),disabled:!!a,title:n.scope==="shared"&&n.editors.length?"Demoting revokes every editor grant":void 0},n.scope==="shared"?"Demote to user":"Promote to shared"):null,n.scope==="shared"&&!n.hasOwnUserCounterpart?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("republish",n.activeSemver),disabled:!!a||!n.activeSemver,title:"Copy the active version into your user scope as a private test bench"},a==="republish"?"Copying…":"Copy to my user scope"):null,typeof t.transport.saveAgentPackageDownload=="function"?o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>l(),disabled:!!a||!n.activeSemver,title:`Download ${n.name}@${n.activeSemver??"?"} as the .tgz the CLI would push`},a==="download"?"Downloading…":"Download"):null,o.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.enabled?"disable":"enable"),disabled:!!a},n.enabled?"Disable":"Enable"),n.canManage?o.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:r,disabled:!!a},"Delete"):null):o.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator, a granted editor, or an admin can modify it."),n.actionError?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function kv({controller:t,detail:e,pending:s}){const[n,r]=o.useState(""),[i,a]=o.useState([]);o.useEffect(()=>{if(!e.canManage||typeof t.transport.listKnownUsers!="function")return;let m=!1;return t.transport.listKnownUsers({limit:500}).then(f=>{m||a(Array.isArray(f)?f:[])}).catch(()=>{}),()=>{m=!0}},[t,e.canManage]);const l=new Set(e.editors.map(m=>`${m.provider}${m.subject}`)),c=n.trim().toLowerCase(),d=c?i.filter(m=>!l.has(`${m.provider}${m.subject}`)&&(m.displayName&&m.displayName.toLowerCase().includes(c)||m.email&&m.email.toLowerCase().includes(c)||m.subject&&m.subject.toLowerCase().includes(c))).slice(0,8):[],u=m=>{!m?.provider||!m?.subject||(r(""),t.runAdminPackageAction("grantEditor",{provider:m.provider,subject:m.subject}))},p=()=>{const m=n.trim();if(!m)return;const f=i.find(h=>h.displayName&&h.displayName.toLowerCase()===m.toLowerCase()||h.email&&h.email.toLowerCase()===m.toLowerCase()||h.subject&&h.subject.toLowerCase()===m.toLowerCase());if(f)return u(f);if(d.length===1)return u(d[0])};return o.createElement("div",{className:"ps-admin-editors"},o.createElement("div",{className:"ps-admin-detail__label"},"Editors"),e.editors.length?o.createElement("div",{className:"ps-admin-detail__chips"},e.editors.map(m=>o.createElement("span",{key:`${m.provider}${m.subject}`,className:"ps-agent-chip",title:`${m.provider}:${m.subject}${m.grantedByDisplay?` · granted by ${m.grantedByDisplay}`:""}`},m.label,e.canManage?o.createElement("button",{type:"button",className:"ps-chip-remove","aria-label":`Remove editor ${m.label}`,disabled:!!s,onClick:()=>t.runAdminPackageAction("revokeEditor",{provider:m.provider,subject:m.subject})},"×"):null))):o.createElement("p",{className:"ps-admin-console__hint"},e.canManage?"No editors yet. Add a person to let them publish, pin and enable this package. Grants are revoked if the package is demoted.":"Only the owner and admins can change this package."),e.canManage?o.createElement("div",{className:"ps-admin-editors__add"},o.createElement("input",{type:"text",className:"ps-input",placeholder:"Add editor by name, email, or id…",value:n,disabled:!!s,onChange:m=>r(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),p())},"aria-label":"Add editor"}),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:p,disabled:!!s||!n.trim()},"Add"),d.length?o.createElement("div",{className:"ps-admin-editors__suggestions",role:"listbox"},d.map(m=>o.createElement("button",{key:`${m.provider}${m.subject}`,type:"button",role:"option",className:"ps-admin-editors__suggestion",onClick:()=>u(m)},m.displayName||m.email||m.subject,m.email&&m.displayName?o.createElement("i",null,` ${m.email}`):null))):null):null)}function xv({controller:t,view:e,layout:s=null,onLayout:n=null}){const r=ee(t,p=>p.ui.themeId),i=ft(r),a=e.packages?.workspace,l=o.useRef(null),c=o.useCallback((p,m)=>{if(!n)return;p.preventDefault();const f=p.clientX,h=p.clientY,g={...s},b=S=>m(g,S.clientX-f,S.clientY-h),y=()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),document.body.style.cursor=""};window.addEventListener("pointermove",b),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)},[s,n]),d=o.useCallback(p=>{document.body.style.cursor="col-resize",c(p,(m,f)=>n({wsWidth:m.wsWidth-f}))},[c,n]),u=o.useCallback(p=>{document.body.style.cursor="row-resize";const m=l.current?.getBoundingClientRect().height||600;c(p,(f,h,g)=>n({treePct:f.treePct+g/m*100}))},[c,n]);return a?o.createElement("div",{className:"ps-admin-ws",ref:l,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?o.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:d}):null,o.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${a.semver?` · ${e.packages.selectedName}@${a.semver}`:""}`),o.createElement("div",{className:"ps-admin-ws__tree"},a.loading?o.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,a.error?o.createElement("div",{className:"ps-admin-tree__hint is-error"},a.error):null,a.treeRows.map(p=>o.createElement("button",{key:`${p.type}:${p.path}`,type:"button",style:{paddingLeft:`${8+(p.depth||0)*16}px`},className:`ps-admin-ws__row is-${p.type}${p.selected?" is-selected":""}`,onClick:p.type==="dir"?()=>t.toggleAdminPackageDir(p.path):()=>t.selectAdminPackageFile(p.path)},o.createElement("span",{className:"ps-admin-ws__caret"},p.type==="dir"?p.expanded?"▾":"▸":""),o.createElement("span",{className:"ps-admin-ws__name"},p.label),p.sizeText?o.createElement("span",{className:"ps-admin-ws__size"},p.sizeText):null))),o.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?u:void 0},a.selectedPath?`Preview · ${a.selectedPath}`:"Preview"),o.createElement("div",{className:"ps-admin-ws__preview"},a.fileLoading?o.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,a.fileError?o.createElement("div",{className:"ps-admin-tree__hint is-error"},a.fileError):null,a.file?a.file.isBinary?o.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${a.file.sizeText}`):o.createElement(Av,{file:a.file,theme:i}):null)):null}function Iv(t){const e=/^---\n([\s\S]*?)\n---\n?/.exec(t||"");if(!e)return{meta:null,body:t||""};const s=e[1].split(`
|
|
97
|
+
`).map(n=>/^([A-Za-z0-9_-]+):\s*(.*)$/.exec(n)).filter(Boolean).map(([,n,r])=>({key:n,value:r}));return s.length===0?{meta:null,body:t||""}:{meta:s,body:(t||"").slice(e[0].length)}}function Av({file:t,theme:e}){const s=t.language||"text",n=t.truncated?o.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:r,body:i}=Iv(t.text||"");return o.createElement("div",{className:"ps-admin-ws__doc"},r?o.createElement("div",{className:"ps-admin-ws__frontmatter"},r.map(a=>o.createElement("div",{key:a.key,className:"ps-admin-ws__fm-row"},o.createElement("span",{className:"ps-admin-ws__fm-key"},a.key),o.createElement("span",{className:"ps-admin-ws__fm-val"},a.value)))):null,o.createElement(Bi,{content:i,theme:e}),n)}if(s==="json"){let r=t.text||"";if(!t.truncated)try{r=JSON.stringify(JSON.parse(r),null,2)}catch{}return o.createElement("div",{className:"ps-admin-ws__doc"},o.createElement("pre",{className:"ps-admin-ws__code lang-json"},o.createElement("code",null,us(r,"json",e))),n)}return o.createElement("div",{className:"ps-admin-ws__doc"},o.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},o.createElement("code",null,us(t.text||"",s,e))),n)}function Nv({controller:t,dialog:e}){const s=ee(t,p=>p.docs?.agentPackageGuideUrl||null),n=p=>m=>t.setAdminAddPackageField(p,m.target.value),r=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],i=e.kind==="repo"||e.kind==="github"||e.kind==="ado",a=o.useRef(null),[l,c]=o.useState(!1),d=2*1024*1024,u=p=>{if(p.preventDefault(),!(l||e.submitting)){if(e.kind==="upload"){const m=a.current;if(!m?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const f=[...m.files].map(g=>({file:g,path:g.webkitRelativePath.split("/").slice(1).join("/")||g.name})).filter(({path:g})=>g&&!g.split("/").includes("node_modules")&&!g.split("/").includes(".git")),h=f.reduce((g,{file:b})=>g+b.size,0);if(f.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(h>d){t.failAdminAddPackage(`Folder is ${(h/(1024*1024)).toFixed(1)} MB after filtering — the upload envelope is 2 MB. Use a repo/URL source or 'pilotswarm agents push' for larger packages.`);return}c(!0),Promise.all(f.map(({file:g,path:b})=>new Promise((y,S)=>{const w=new FileReader;w.onerror=()=>S(new Error(`could not read ${b}`)),w.onload=()=>y({path:b,contentBase64:String(w.result).split(",",2)[1]||""}),w.readAsDataURL(g)}))).then(g=>t.submitAdminUploadPackage(g,e.scope)).catch(g=>t.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return o.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},o.createElement("form",{className:"ps-modal ps-admin-add",onClick:p=>p.stopPropagation(),autoComplete:"off",onSubmit:u},o.createElement("div",{className:"ps-modal-header"},o.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),o.createElement("div",{className:"ps-admin-add__body"},o.createElement("div",{className:"ps-admin-add__tabs"},r.map(([p,m])=>o.createElement("button",{key:p,type:"button",className:`ps-admin-add__tab${e.kind===p?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",p)},m))),i?[o.createElement("label",{key:"u",className:"ps-admin-add__field"},"Link to plugin.json (or the folder containing it)",o.createElement("input",{value:e.repoUrl,onChange:n("repoUrl"),placeholder:"https://github.com/org/repo/blob/main/my-agents/plugin.json",autoFocus:!0,type:"url",name:"agent-package-link",autoComplete:"off",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"})),o.createElement("div",{key:"h",className:"ps-admin-add__hint"},"Paste the browser URL — branch and path are read from the link. The files are read by THIS BROWSER with your access (public GitHub needs nothing; Azure DevOps uses your signed-in account) and uploaded as a package artifact."),o.createElement("label",{key:"t",className:"ps-admin-add__field"},"PAT (only for private GitHub repos, or to override — used here, never stored)",o.createElement("input",{type:"password",value:e.authToken,onChange:n("authToken"),name:"agent-package-pat",autoComplete:"new-password","data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"}))]:o.createElement("label",{className:"ps-admin-add__field"},"Package folder with plugin.json — the manifest (≤ 2 MB; node_modules skipped)",o.createElement("input",{ref:a,type:"file",webkitdirectory:"",directory:"",multiple:!0})),o.createElement("div",{className:"ps-admin-add__scope"},o.createElement("label",null,o.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="shared",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),o.createElement("label",null,o.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="user",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","user")})," User — only you see it")),e.updateName?o.createElement("p",{className:"ps-admin-console__hint"},`Publishes a new version of ${e.updateName}. Its scope is unchanged — use Demote/Promote on the package to move it.`):null,s?o.createElement("p",{className:"ps-admin-console__hint"},"New to this? ",o.createElement("a",{href:s,target:"_blank",rel:"noreferrer noopener"},"How to build an agent package")," — a complete guide you can also hand straight to Claude or Copilot."):null,o.createElement("p",{className:"ps-admin-console__hint"},"Same thing from a terminal: pilotswarm agents push ./my-agents --shared"),e.progress&&!e.error?o.createElement("p",{className:"ps-admin-add__progress"},e.progress):null,e.error?o.createElement("pre",{className:"ps-admin-add__error",role:"alert"},e.error):null),o.createElement("div",{className:"ps-modal-footer"},o.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage(),disabled:e.submitting},"Cancel"),o.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.submitting||l},l?"Reading folder…":e.submitting?"Importing…":e.updateName?"Import & update":"Import & publish"))))}function Sr(t){return t?.configured?.model||""}function vr({label:t,hint:e,value:s,choices:n,disabled:r,emptyLabel:i,onChange:a}){return o.createElement("label",{className:"ps-admin-provider-default"},o.createElement("span",{className:"ps-admin-detail__label"},t),o.createElement("select",{className:"ps-budget-input",value:s,disabled:r,"aria-label":t,onChange:l=>a(l.target.value)},o.createElement("option",{value:""},i),s&&!n.some(l=>l.qualifiedName===s)?o.createElement("option",{value:s},`${s} (currently configured)`):null,n.map(l=>o.createElement("option",{key:l.qualifiedName,value:l.qualifiedName},`${l.provider} · ${l.model}`))),e?o.createElement("span",{className:"ps-admin-console__hint"},e):null)}function Ja({providers:t,isAdmin:e,personal:s,busy:n,onSystemUse:r,onUpdate:i,onDelete:a}){return t.length?o.createElement("div",{className:"ps-admin-provider-list"},t.map(l=>o.createElement("div",{key:l.name,className:"ps-admin-provider-row"},o.createElement("div",{className:"ps-admin-provider-row__identity"},o.createElement("strong",{title:l.name},l.name),o.createElement("span",{className:`ps-scope-badge is-${l.class==="shared"?"shared":"user"}`},l.class),l.isMyDefault?o.createElement("span",{className:"ps-scope-badge is-off"},"my default"):null,l.isClusterDefault?o.createElement("span",{className:"ps-scope-badge is-off"},"cluster default"):null,l.isSystemDefault?o.createElement("span",{className:"ps-scope-badge is-off"},"system default"):null),o.createElement("div",{className:"ps-admin-provider-row__actions"},s&&e?o.createElement("label",{className:"ps-admin-console__system-toggle"},o.createElement("input",{type:"checkbox",checked:l.systemUseEnabled,disabled:n,onChange:c=>r(l.name,c.target.checked)}),"Allow system sessions"):null,(s||e)&&!l.usesWorkloadIdentity?o.createElement("button",{type:"button",className:"ps-mini-button","aria-label":`Update key for ${l.name}`,title:`Update key for ${l.name}`,disabled:n,onClick:()=>i(l)},"Update key"):null,o.createElement(he,{icon:o.createElement(nS),label:`Delete ${l.name}`,className:"ps-mini-button is-danger",disabled:n,onClick:()=>a(l)}))))):o.createElement("p",{className:"ps-admin-console__hint"},s?"No personal providers yet.":"No shared providers are configured.")}function Cv({controller:t,view:e,onAddPersonal:s,onAddShared:n,onUpdatePersonal:r,sheetOpen:i=!1}){const a=e.modelProviders||{},l=!!a.mutation?.pending,c=Sr(a.systemSessionDefault),[d,u]=o.useState(c),[p,m]=o.useState(""),[f,h]=o.useState(null);o.useEffect(()=>{u(c)},[c]);const g=(P,N)=>P.find(_=>_.qualifiedName===N)||null,b=(P,N,_)=>{t.setAdminModelDefault(P,g(N,_))},y=P=>{window.confirm(`Delete ${P.name}? Sessions using it will wait until that provider name exists again.`)&&t.deleteAdminProvider(P.name,{shared:P.class==="shared"})},S=async()=>{h(null);const P=await t.setAdminSystemModelDefault(g(a.systemChoices||[],d),{restartDisposition:p||null});P?.ok&&h(P.result?.restart||{requested:!1})},w=(a.systemAgentRoutes||[]).filter(P=>!P.override),k=a.page==="shared"&&e.isAdmin,E=o.createElement("div",{className:"ps-admin-provider-heading"},o.createElement("h3",null,"Model Providers"),o.createElement(he,{icon:"↻",label:"Refresh model providers",className:"ps-mini-button",disabled:a.loading,onClick:()=>t.refreshAdminModelProviders()})),x=o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("div",{className:"ps-admin-provider-block__head"},o.createElement("h4",null,"My Providers"),o.createElement("button",{type:"button",className:"ps-primary-button",onClick:s,disabled:l},"Add provider")),o.createElement(Ja,{providers:a.myProviders||[],isAdmin:e.isAdmin,personal:!0,busy:l,onSystemUse:(P,N)=>t.setAdminProviderSystemUse(P,N),onUpdate:r,onDelete:y})),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement(vr,{label:"My Session Default",hint:`Effective: ${a.mySessionDefault?.effective?.model||"none"}.`,value:Sr(a.mySessionDefault),choices:a.userChoices||[],disabled:l,emptyLabel:"Use cluster default",onChange:P=>b("user",a.userChoices||[],P)}))),v=o.createElement(o.Fragment,null,o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("div",{className:"ps-admin-provider-block__head"},o.createElement("h4",null,"Shared Providers"),o.createElement("button",{type:"button",className:"ps-primary-button",onClick:n,disabled:l},"Add provider")),o.createElement(Ja,{providers:a.sharedProviders||[],isAdmin:!0,personal:!1,busy:l,onSystemUse:()=>{},onDelete:y,onUpdate:r})),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement(vr,{label:"Cluster Session Default",hint:`Effective: ${a.clusterSessionDefault?.effective?.model||"none"}.`,value:Sr(a.clusterSessionDefault),choices:a.clusterChoices||[],disabled:l,emptyLabel:"Use first shared provider",onChange:P=>b("cluster",a.clusterChoices||[],P)})),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("h4",null,"System Session Default"),o.createElement(vr,{label:"Model",hint:"Shared and system-enabled personal providers.",value:d,choices:a.systemChoices||[],disabled:l,emptyLabel:"Use first eligible provider",onChange:u}),o.createElement("div",{className:"ps-admin-detail__label"},"Existing system sessions"),o.createElement($t,{value:p,onChange:m,label:"Existing system sessions",options:[{value:"",label:"Future only"},{value:"complete",label:"Complete & restart"},{value:"terminate",label:"Terminate & restart"},{value:"hard_delete",label:"Hard delete & restart"}]}),o.createElement("div",{className:"ps-admin-provider-apply"},o.createElement("p",{className:"ps-admin-console__hint"},`${w.length} agent${w.length===1?"":"s"} inherit this default.`),o.createElement("button",{type:"button",className:"ps-primary-button",disabled:l,onClick:S},l&&a.mutation?.pending==="systemDefault"?"Applying…":"Apply")),f?.requested?o.createElement("p",{className:"ps-admin-console__status"},`${f.restarted}/${f.affected} restarted${f.failures?.length?` · ${f.failures.length} failed`:""}.`):null),o.createElement("div",{className:"ps-admin-provider-block"},o.createElement("h4",null,"System Agent Overrides"),(a.systemAgentRoutes||[]).length===0?o.createElement("p",{className:"ps-admin-console__hint"},"No system agents."):o.createElement("div",{className:"ps-admin-override-table"},(a.systemAgentRoutes||[]).map(P=>o.createElement("div",{key:P.agentId,className:"ps-admin-override-row"},o.createElement("div",{className:"ps-admin-override-row__agent"},o.createElement("strong",null,P.title),o.createElement("span",null,P.effectiveModel||"blocked"),o.createElement("small",null,P.override?"override":"system default")),o.createElement("select",{className:"ps-budget-input",value:P.override?.model||"",disabled:l,"aria-label":`Model override for ${P.title}`,onChange:N=>{const _=g(a.systemChoices||[],N.target.value);_?t.setAdminSystemAgentModel(P.agentId,_):t.clearAdminSystemAgentModel(P.agentId)}},o.createElement("option",{value:""},"Inherit system default"),(a.systemChoices||[]).map(N=>o.createElement("option",{key:N.qualifiedName,value:N.qualifiedName},`${N.provider} · ${N.model}`))))))));return o.createElement("section",{className:"ps-admin-detail ps-admin-model-providers"},E,a.error||a.mutation?.error&&!i?o.createElement("div",{className:"ps-admin-console__error",role:"alert"},!i&&a.mutation?.error||a.error):null,k?v:x)}function Mv({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){My(),typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;const r=Uh(Hh,Ar({mode:e,branding:s,docs:n}));return new Gg({store:r,transport:t})}function _v({controller:t}){const e=o.useRef(null),s=o.useRef(null),n=Ia(e),r=Ia(s),i=Hy(n);o.useEffect(()=>{const R=()=>{try{const O=document.createElement("span");O.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const q=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");if(q){const fe=window.getComputedStyle(q);O.style.fontFamily=fe.fontFamily,O.style.fontSize=fe.fontSize,O.style.fontWeight=fe.fontWeight,O.style.letterSpacing=fe.letterSpacing}O.textContent="0".repeat(100),(q?.parentElement||document.body).appendChild(O);const te=O.getBoundingClientRect().width/100||8;O.remove();const se=document.documentElement.clientWidth||window.innerWidth,ue=document.documentElement.clientHeight||window.innerHeight;t.dispatch({type:"ui/viewport",width:Math.floor(se/te),height:Math.floor(ue/bt)})}catch{}};R();let F;const A=()=>{clearTimeout(F),F=setTimeout(R,150)};return window.addEventListener("resize",A),window.addEventListener("orientationchange",A),()=>{clearTimeout(F),window.removeEventListener("resize",A),window.removeEventListener("orientationchange",A)}},[t]);const[a,l]=o.useState("split"),c=ee(t,R=>({themeId:R.ui.themeId,touchScale:!!R.ui.touchScale,sessionDetailCollapsed:!!R.ui.sessionDetailCollapsed,agentPickerUsage:R.ui.agentPickerUsage,ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,manualOrder:R.sessions.manualOrder,collapsedSessionIds:R.sessions.collapsedIds,activeSessionId:R.sessions.activeSessionId||null,promptRows:qc(R),rightPaneMode:R.ui.rightPaneMode||"panes",canvasOpen:R.ui.canvasOpen===!0,diagnosticsOpen:R.ui.diagnosticsOpen===!0,canvasMaximized:R.ui.canvasMaximized===!0,canvasZen:R.ui.canvasZen===!0,canvasPrefs:R.canvas?.prefs,activeSessionIsGroup:!!(R.sessions.activeSessionId&&R.sessions.byId[R.sessions.activeSessionId]?.isGroup),paneAdjust:R.ui.layout?.paneAdjust??0,sessionPaneAdjust:R.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:R.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:R.ui.layout?.activityPaneAdjust??0,canvasPaneAdjust:R.ui.layout?.canvasPaneAdjust??0,diagnosticsPaneAdjust:R.ui.layout?.diagnosticsPaneAdjust??0,diagnosticsSplitAdjust:R.ui.layout?.diagnosticsSplitAdjust??0,focusRegion:R.ui.focusRegion,requestedFocusRegion:R.ui.requestedFocusRegion,inspectorTab:R.ui.inspectorTab,filesFullscreen:!!R.files.fullscreen,selectedArtifactId:R.files.selectedArtifactId||null,artifactPaneOpen:!!R.files.paneOpen,adminVisible:!!R.admin?.visible,budgetOpen:!!R.ui?.budgetOpen}),Le),d=o.useRef(!1),u=o.useRef(null),p=o.useRef(null),m=o.useRef(null),f=o.useRef(null),h=o.useRef(null),g=o.useRef(null),b=o.useRef(!1),y=o.useRef(!1),S=o.useRef(null),w=o.useRef(null),[k,E]=o.useState("workspace"),x=(n.width||window.innerWidth||0)<dy,P=c.activeSessionIsGroup?0:c.promptRows;bv(t,x);const N=PS(x&&k==="workspace"&&!c.adminVisible);o.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-kb-takeover",N),()=>document.body.classList.remove("ps-kb-takeover")},[N]),o.useEffect(()=>{N&&t.applyPaneVisualScrollOffset?.("chat",0,{followBottom:!0})},[N,t]);const _=ee(t,fi,Le),D=k==="canvas",L=o.useRef("workspace"),[I,C]=o.useState(!1),[U,B]=o.useState(!1);o.useEffect(()=>{E(R=>R==="canvas"?L.current||"workspace":R),C(!1),B(!1)},[_.sessionId]),o.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-canvas-lock",!!(x&&D)),()=>document.body.classList.remove("ps-canvas-lock")},[x,D]);const V=o.useCallback(()=>{k!=="canvas"&&(L.current=k),E("canvas"),C(!0),t.dispatch({type:"ui/rightPaneMode",mode:"canvas",sessionId:_.sessionId})},[t,k,_.sessionId]),ce=o.useCallback(()=>{E(L.current||"workspace"),t.dispatch({type:"ui/rightPaneMode",mode:"panes",sessionId:_.sessionId,manual:!0})},[t,_.sessionId]),X=o.useRef(_.flipSeq);o.useEffect(()=>{_.flipSeq!==X.current&&(X.current=_.flipSeq,x&&V())},[_.flipSeq,x,V]);const re=o.useCallback(()=>{if(D){ce();return}V()},[D,ce,V]);o.useEffect(()=>{let R=!0;d.current=!1,u.current=null,S.current=null,w.current=Ea(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),b.current=!1,y.current=!1;const F=t.transport;if(typeof F?.getCurrentUserProfile!="function"||typeof F?.setCurrentUserProfileSettings!="function")return d.current=!0,()=>{R=!1};const A=async()=>{if(!(!R||b.current)){b.current=!0;try{const O=await F.getCurrentUserProfile();if(!R)return;O&&typeof O.isAdmin=="boolean"&&!t.getState().admin?.profile&&t.dispatch({type:"admin/profile/loaded",profile:O});const q=Ft(O?.profileSettings);typeof q[wn()]=="boolean"&&(p.current=q[wn()]),(q.rightPaneMode==="canvas"||q.rightPaneMode==="panes")&&(m.current=q.rightPaneMode),q.desktopPanes&&(f.current=q.desktopPanes),w.current=Ea(t.getState(),p.current,m.current,f.current);const te=Ry(O?.profileSettings,w.current),se=JSON.stringify(te),ue=dr(t.getState(),p.current,m.current,f.current),fe=JSON.stringify(ue),Te=d.current&&u.current!=null&&fe!==u.current,Be=!!h.current||y.current||Te;if(!Be&&S.current!==se&&(t.dispatch({type:"profileSettings/apply",settings:te}),S.current=se),!d.current||!Be){const me=dr(t.getState(),p.current,m.current,f.current);u.current=JSON.stringify(me)}d.current=!0}catch{if(!R)return;d.current=!0}finally{b.current=!1}}};return A().catch(()=>{}),g.current=setInterval(()=>{A().catch(()=>{})},gy),()=>{R=!1,h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),b.current=!1}},[t]),o.useEffect(()=>{if(!d.current)return;const R=dr(c,p.current,m.current,f.current),F=JSON.stringify(R);u.current!==F&&(u.current=F,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,y.current=!0,$y(t,R).catch(()=>{}).finally(()=>{y.current=!1})},400))},[t,c.activeSessionId,c.activityPaneAdjust,c.agentPickerUsage,c.canvasOpen,c.canvasPaneAdjust,c.canvasPrefs,c.canvasZen,c.collapsedSessionIds,c.diagnosticsOpen,c.diagnosticsPaneAdjust,c.diagnosticsSplitAdjust,c.ownerFilter,c.paneAdjust,c.manualOrder,c.pinnedIds,c.portalSessionColumnAdjust,c.rightPaneMode,c.sessionDetailCollapsed,c.sessionPaneAdjust,c.themeId,c.touchScale]),o.useEffect(()=>{By(c.themeId),Dy(c.touchScale)},[c.themeId,c.touchScale]);const T=o.useRef(null);o.useEffect(()=>{const R=T.current;if(T.current=c.focusRegion,R===null||R===c.focusRegion)return;const F=c.requestedFocusRegion;x&&(c.focusRegion==="inspector"||c.focusRegion==="activity")&&(F==="inspector"||F==="activity")&&E(c.focusRegion)},[x,c.focusRegion,c.requestedFocusRegion]),o.useEffect(()=>{const R=Mi(t);!R.includes(c.inspectorTab)&&R.length>0&&t.selectInspectorTab(R[0]).catch(()=>{})},[t,c.inspectorTab]);const j=o.useMemo(()=>Cs(i,c.paneAdjust,P,c.sessionPaneAdjust,c.activityPaneAdjust),[i,c.activityPaneAdjust,c.paneAdjust,P,c.sessionPaneAdjust]),H=c.filesFullscreen&&c.inspectorTab==="files",W=c.inspectorTab==="files"&&!!c.selectedArtifactId&&!H,z=!x&&c.artifactPaneOpen&&!!c.selectedArtifactId&&!H,Q=!x&&c.canvasOpen&&!H;o.useEffect(()=>{Q&&B(!0)},[Q,_.sessionId]);const K=!x&&c.diagnosticsOpen&&!H&&!z&&!(c.canvasZen&&c.canvasOpen),Y=z||Q||K,Z=c.canvasMaximized&&Q,de=c.canvasZen&&Q&&!z,ve=Math.max(260,Math.min(720,Number(c.canvasPrefs?.[c.activeSessionId]?.zenRailPx)||380));o.useEffect(()=>{if(!Z&&!de)return;const R=F=>{F.key==="Escape"&&t.dispatch(Z?{type:"ui/canvasMaximized",on:!1}:{type:"ui/canvasZen",on:!1})};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[t,Z,de]);const le=Math.max(0,_i+(Number(c.canvasPaneAdjust)||0)),st=Math.max(0,Ri+(Number(c.diagnosticsPaneAdjust)||0)),ye=(Q?le:0)+(Q&&K?1:0)+(K?st:0),nt=o.useCallback(()=>{t.closeArtifactPane().catch(()=>{})},[t]),Ce=Math.max(0,(n.width||0)*.68),Oe=r.width||Ce,ut=Ly(Oe,c.portalSessionColumnAdjust),rt=de?"hidden":Oy(ut),G=rt==="hidden"?"0px":`clamp(0px, calc(${Ti*100}% + ${Number(c.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,oe=o.createElement("div",{className:`ps-workspace-grid${Y?"":" is-right-hidden"}`,style:{gridTemplateColumns:z?`minmax(0, ${j.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${j.rightWidth}fr)`:de?`${ve}px var(--ps-resizer-track, 16px) minmax(0, 1fr)`:Y?`minmax(0, 1fr) var(--ps-resizer-track, 16px) min(${ye}px, calc(100% - var(--ps-resizer-track, 16px) - ${Pi}px))`:"minmax(0, 1fr)"}},o.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${rt}`,style:{gridTemplateColumns:`${G} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},rt!=="hidden"?o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},o.createElement(Hr,{controller:t,structuredRows:!0})):null,o.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},o.createElement(HS,{controller:t,portalSessionColumnAdjust:c.portalSessionColumnAdjust})),o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},o.createElement(jr,{controller:t}))),Y?z?o.createElement(BS,{controller:t,paneAdjust:c.paneAdjust}):de?o.createElement(jS,{controller:t,sessionId:c.activeSessionId,railPx:ve}):o.createElement(GS,{controller:t,target:Q?"canvas":"diagnostics",adjust:Q?c.canvasPaneAdjust:c.diagnosticsPaneAdjust}):null,o.createElement("div",{className:`ps-workspace-column-host is-split${Z?" has-maximized":""}`},z?o.createElement("div",{className:"ps-workspace-column is-artifact"},o.createElement(IS,{controller:t,onClose:nt})):null,U?o.createElement("div",{key:`canvas:${c.activeSessionId||""}`,className:`ps-workspace-column is-artifact ps-canvas-layer${Q&&!z?"":" is-hidden"}${Z&&Q&&!z?" is-maximized":""}`,style:Q&&!z&&K&&!Z?{flex:`0 0 ${le}px`,minWidth:0}:void 0,...Q&&!z?{}:{inert:!0,"aria-hidden":"true"}},o.createElement(wd,{controller:t,visible:Q&&!z,maximized:Z})):null,Q&&K?o.createElement(US,{controller:t,canvasPaneAdjust:c.canvasPaneAdjust,diagnosticsPaneAdjust:c.diagnosticsPaneAdjust}):null,K?o.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`minmax(0px, calc(50% + ${Math.round(Number(c.diagnosticsSplitAdjust)||0)}px)) var(--ps-resizer-track, 16px) minmax(0px, 1fr)`,...Q?{flex:"1 1 0%",minWidth:0}:null}},o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},o.createElement(xs,{controller:t,mobile:!1})),o.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},o.createElement(WS,{controller:t,splitAdjust:c.diagnosticsSplitAdjust})),o.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},W?o.createElement(Rn,{controller:t,focused:!1,previewOnly:!0}):o.createElement(yr,{controller:t}))):null)),be=o.createElement("div",{className:"ps-workspace-full"},o.createElement(xs,{controller:t,mobile:!1}));let pe=null;H&&!x?pe=o.createElement("div",{className:"ps-mobile-pane-fill"},o.createElement(xs,{controller:t,mobile:!0})):k==="inspector"?pe=c.inspectorTab==="nodes"?o.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},o.createElement(xs,{controller:t,mobile:!0}),o.createElement(yr,{controller:t,panelClassName:"ps-mobile-node-detail"})):o.createElement("div",{className:"ps-mobile-pane-fill"},o.createElement(xs,{controller:t,mobile:!0})):k==="activity"?pe=o.createElement("div",{className:"ps-mobile-pane-fill"},o.createElement(yr,{controller:t})):k==="canvas"?pe=null:pe=o.createElement(MS,{controller:t,layout:a});const xe=x&&I?o.createElement(AS,{key:`canvas:${_.sessionId||""}`,controller:t,visible:D}):null;return o.createElement(Jc.Provider,{value:t},o.createElement("div",{ref:e,className:"ps-web-shell"},o.createElement(DS,{controller:t,mobile:x,canvasPaneOpen:D,onToggleCanvasPane:re,mobilePane:k,mobileMainLayout:a,onSelectMobilePane:(R,F)=>{R==="workspace"&&k==="workspace"&&l(A=>A==="split"?"chat":A==="chat"?"sessions":"split"),t.closeBudget(),E(R),F&&t.setFocus(F)}}),o.createElement("div",{className:"ps-workspace"},c.adminVisible?o.createElement(vv,{controller:t,mobile:x}):c.budgetOpen?o.createElement(hv,{controller:t}):H?be:x?pe:oe,xe),x&&H?o.createElement(NS,{controller:t}):null,o.createElement(gv,{controller:t})))}export{_v as P,o as R,Dc as _,Md as a,ft as b,Mv as c,Wr as d,Tv as e,hf as f,Nd as g,el as r,Pv as s};
|