@pricening/pi-web 0.12.7 → 0.12.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +7 -7
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/_not-found.html +1 -1
  15. package/.next/server/app/_not-found.rsc +2 -2
  16. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  17. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  19. package/.next/server/app/api/app-update/route.js +1 -1
  20. package/.next/server/app/index.html +1 -1
  21. package/.next/server/app/index.rsc +4 -4
  22. package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
  23. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  24. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  25. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  26. package/.next/server/app/login.html +1 -1
  27. package/.next/server/app/login.rsc +2 -2
  28. package/.next/server/app/login.segments/_full.segment.rsc +2 -2
  29. package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
  30. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +2 -2
  31. package/.next/server/app/page.js +2 -2
  32. package/.next/server/app/page_client-reference-manifest.js +1 -1
  33. package/.next/server/app-paths-manifest.json +7 -7
  34. package/.next/server/middleware-build-manifest.js +1 -1
  35. package/.next/server/pages/404.html +1 -1
  36. package/.next/server/pages/500.html +1 -1
  37. package/.next/server/server-reference-manifest.json +1 -1
  38. package/.next/static/chunks/app/{layout-dc92f566bde9cb90.js → layout-e57590007e053c2d.js} +1 -1
  39. package/.next/static/chunks/app/{page-51236672fe44826e.js → page-b49cc985ba75254a.js} +2 -2
  40. package/.next/trace +84 -84
  41. package/.next/trace-build +1 -1
  42. package/package.json +1 -1
  43. /package/.next/static/{2-ek4D4YYy-9IwxOBOJWo → bsB2D6Fb85gG5WmwkxvEo}/_buildManifest.js +0 -0
  44. /package/.next/static/{2-ek4D4YYy-9IwxOBOJWo → bsB2D6Fb85gG5WmwkxvEo}/_ssgManifest.js +0 -0
@@ -1,5 +1,5 @@
1
1
  (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>u,kU:()=>l,sn:()=>c,xG:()=>h});let r="configured",i=["configured","none","read-only","default","full"],s=[],l=["read","grep","find","ls"],o=["read","bash","edit","write"],a=["bash","read","edit","write","grep","find","ls"],d=new Set([...a,"powershell"]);function c(e){return"string"==typeof e&&i.includes(e)}function u(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>d.has(e)).sort().join(",");return t===[...l].sort().join(",")?"read-only":t===[...o].sort().join(",")?"default":t===[...a].sort().join(",")?"full":"default"}function h(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...l]:"full"===e?[...a]:[...o]}},42927:(e,t,n)=>{Promise.resolve().then(n.bind(n,65918)),Promise.resolve().then(n.bind(n,21278))},65918:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>bU});var r=n(95155),i=n(12115),s=n(73321);let l=null;function o(e,t){let n=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,s=r.id,l=null;for(;;){if(n.has(s)){l=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(r.relation?.kind!=="subagent"){l=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,l)}return n}(e),r=new Map;for(let t of e)t.relation?.kind!=="subagent"&&r.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let t of e){if(t.relation?.kind!=="subagent")continue;let e=n.get(t.id),i=e?r.get(e):void 0;i&&(i.subagents.push(t),t.modified>i.latestModified&&(i.latestModified=t.modified))}return[...r.values()].sort((e,n)=>{var r;return r=!!t?.has(e.root.id),(!!t?.has(n.root.id)===r?0:r?-1:1)||n.latestModified.localeCompare(e.latestModified)})}function a(e,t){return e.filter(e=>t.has(e.id)).length}function d(e){return`?session=${encodeURIComponent(e)}`}let c="pi-web:last-open-by-workspace";function u(){try{return window.localStorage}catch{return null}}function p(e){let t=e.getItem(c);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function h(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u();if(t)try{let n=p(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(c):t.setItem(c,JSON.stringify(n))}catch{}}function f(e){return e.projectKey??e.projectRoot??e.cwd}function m(e,t,n){let r=new Map;for(let t of e){let e=t.projectRoot??t.cwd;if(!e)continue;let i=f(t);if(n?.has(i))continue;let s=r.get(i);(!s||t.modified>s.modified)&&r.set(i,{root:e,modified:t.modified})}return[...r.entries()].sort((e,n)=>{var r;return r=!!t?.has(e[0]),(!!t?.has(n[0])===r?0:r?-1:1)||n[1].modified.localeCompare(e[1].modified)}).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let g=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,x=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function v(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function b(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function y(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let w=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function j(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?w.test(t)||[...t].length>80?void 0:t:null}let k=new TextEncoder;function S(e){return k.encode(JSON.stringify(e)).length+1}function C(e){let t=1;for(let n of e)t+=S(n);return t}function N(e,t){return e<=1e3&&t<=262144}function $(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=S(r);n+e>262144||(t.push(r),n+=e)}return t}function E(e,t){return k.encode(JSON.stringify(e)).length+k.encode(JSON.stringify(t)).length+2}function I(e,t){return e<=1e3&&t<=262144}function M(){return{version:1,revision:0,sessions:{},projects:{}}}function T(e,t,n){let r=x(e,t)?e[t]:void 0;return void 0===n.pinnedAt&&void 0===n.archivedAt?!!r&&(delete e[t],!0):(r?.pinnedAt!==n.pinnedAt||r?.archivedAt!==n.archivedAt)&&(e[t]=n,!0)}function R(e,t){var n;return n=e.projectOrder??[],!(n.length===t.length&&n.every((e,n)=>e===t[n]))&&(0===t.length?delete e.projectOrder:e.projectOrder=t,!0)}function A(e,t){let n=new Set(e),r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}function L(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:500,n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}let z={desktop:{"pinned-header":28,session:28,"pinned-more":26,group:28,"group-more":26,"group-empty":28,spacer:8,"footer-open":28,"footer-archived":28,"archive-group":28},mobile:{"pinned-header":44,session:44,"pinned-more":36,group:44,"group-more":36,"group-empty":44,spacer:8,"footer-open":44,"footer-archived":44,"archive-group":44}},P="pinned";function W(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function O(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function F(e,t){return e===t?0:e>t?-1:1}function D(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function B(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function H(e,t,n){let r=O(W(t,e.root.id)?.archivedAt);if(null===r||B(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function _(e,t,n){return null!==O(W(t,e.root.id)?.pinnedAt)&&!H(e,t,n)}function U(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e.charAt(0);let n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return t.slice(n+1)}function q(e,t){if(Object.hasOwn(t,e.key)){let n=t[e.key];if("boolean"==typeof n)return n}return e.current||e.pinned}function K(e,t){var n;return{running:B(e,t.runningIds),awaiting:!!t.awaitingIds&&B(e,t.awaitingIds),unread:B(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function V(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&B(s,t.awaitingIds)?r++:B(s,t.runningIds)&&n++,B(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function Z(e){return f(e.root)}function J(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=Z(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,l=r.get(i);if(l)return l;let o=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,a=null!==t&&t.key===i,d=n.get(i)??(a?t.root:void 0)??o?.root??i,c=((s=e.projectNames)&&x(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??U(d),customName:c,pinned:void 0!==o,current:a};return r.set(i,u),u}}}function Y(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:K(e,r)}}function G(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=K(e,r);return i.running||i.unread||i.selected}),s=t+n,l=0,o=e.filter((e,n)=>n<t||!!i[n]||n<s&&(l++,!0)),a=Math.max(t,Math.min(s,e.length));for(let t=0;a<e.length&&t<20;a++)!i[a]&&t++;return{visible:o,revealed:l,nextShown:a-t}}function X(e,t){if(!Object.hasOwn(e,t))return 0;let n=e[t];return"number"==typeof n&&Number.isFinite(n)&&n>0?Math.floor(n):0}function Q(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function ee(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function et(e,t,n,r){let i=r-n,s=[];for(let n of o(e.sessions)){if(Z(n)!==t||H(n,e.uiState,e.runningIds)||_(n,e.uiState,e.runningIds))continue;let r=K(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let l=Date.parse(n.latestModified);Number.isNaN(l)||l>=i||s.push(n.root.id)}return s}function en(e,t){let n=[],r=0;for(let i of o(e.sessions))if(Z(i)===t&&!i.root.transient){if(B(i,e.runningIds)||e.awaitingIds&&B(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function er(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),l=i["up"===n?s-1:s+1];return l?{anchorKey:l.key,position:"up"===n?"before":"after"}:null}function ei(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],l=e[t+1];return"start"===i?s===n?null:s:s>=n&&l<=n+r?null:Math.max(0,s-Math.max(0,(r-(l-s))/2))}let es="pi-web:sidebar-tab",el="pi-web:sidebar-groups-v2",eo="pi-web:sidebar-groups",ea="pi-web:sidebar-archive-collapsed",ed="pi-web:sidebar-pins-collapsed",ec="pi-web:sidebar-files-show-ignored",eu="pi-web:sidebar-files-collapsed",ep="pi-web:sidebar-non-git-cwds",eh=["pi-web:file-explorer:open","pi-web:sidebar-session-pane-height",eo];function ef(){try{return window.localStorage}catch{return null}}function em(e){let t={};if(null===e||"object"!=typeof e||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))"__proto__"!==n&&"boolean"==typeof r&&(t[n]=r);return t}function eg(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ef();if(t)try{let n=Object.entries(em(e)),r=n.length>300?n.slice(n.length-300):n;t.setItem(el,JSON.stringify(Object.fromEntries(r)))}catch{}}function ex(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ef();if(t)try{t.setItem(ea,JSON.stringify([...new Set(e)].slice(-300)))}catch{}}function ev(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!e)return[];try{let t=e.getItem(ep),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];return n.filter(e=>"string"==typeof e&&""!==e).slice(-50)}catch{return[]}}async function eb(e,t){let n={deletedRoots:[],deleted:[],running:[],error:null};for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500);try{let e=await t("/api/sessions/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:i})}),r=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(r.deleted)){n.error=r.error??`HTTP ${e.status}`;break}let s=new Set(r.deleted);n.deleted.push(...r.deleted),n.deletedRoots.push(...i.filter(e=>s.has(e))),n.running.push(...r.running??[])}catch(e){n.error=e instanceof Error?e.message:String(e);break}}return n}function ey(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function ew(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:ey(e)}let ej=/ · [0-9a-f]{4}$/;function ek(e){let t=ej.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function eS(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function eC(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eN(e,t){let{key:n,root:r}=e,i=t&&Object.hasOwn(t,n)?t[n]:void 0;return void 0===i?{key:n,root:r}:{key:n,root:r,alias:i}}function e$(e){let t=e.map(e=>({choice:e,name:e.alias??U(e.root)})),n=new Map;for(let{name:e}of t)n.set(e,(n.get(e)??0)+1);return t.map(e=>{let t,r,{choice:i,name:s}=e;return{choice:i,name:s,note:void 0===i.alias&&(n.get(s)??0)>1&&(r=Math.max((t=i.root.replace(/[\\/]+$/,"")).lastIndexOf("/"),t.lastIndexOf("\\")))>0?U(t.slice(0,r)):null}})}function eE(e){return e.isComposing||229===e.keyCode}function eI(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let eM=Symbol.for("pi-web:page-id");function eT(){let e=globalThis,t=e[eM];if("string"==typeof t)return t;let n=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return e[eM]=n,n}let eR=new Set,eA=1;function eL(e){let t=e.source.deref();return t&&2!==t.readyState?t:void 0}function ez(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(let e of eR)eL(e)||eR.delete(e);let r={id:eA++,kind:e,label:n,source:new WeakRef(t),createdAt:Date.now(),opens:0,errors:0,lastOpenAt:null,lastErrorAt:null};return eR.add(r),"function"==typeof t.addEventListener&&(t.addEventListener("open",()=>{r.opens+=1,r.lastOpenAt=Date.now()}),t.addEventListener("error",()=>{r.errors+=1,r.lastErrorAt=Date.now()})),t}function eP(){let e=[];for(let t of eR){let n=eL(t);if(!n){eR.delete(t);continue}e.push({id:t.id,kind:t.kind,label:t.label,state:1===n.readyState?"open":"connecting",createdAt:t.createdAt,opens:t.opens,errors:t.errors,lastOpenAt:t.lastOpenAt,lastErrorAt:t.lastErrorAt})}return e}let eW={trackingSince:null,lastHiddenAt:null,lastVisibleAt:null,hiddenCount:0};function eO(){"u">typeof document&&("hidden"===document.visibilityState?(eW.lastHiddenAt=Date.now(),eW.hiddenCount+=1):eW.lastVisibleAt=Date.now())}function eF(){return{state:"u">typeof document&&"hidden"===document.visibilityState?"hidden":"visible",trackingSince:eW.trackingSince,lastHiddenAt:eW.lastHiddenAt,lastVisibleAt:eW.lastVisibleAt,hiddenCount:eW.hiddenCount}}let eD={count:0,failures:0,last:null};function eB(){return{...eD,last:eD.last?{...eD.last}:null}}function eH(){if("u"<typeof performance||"function"!=typeof performance.getEntriesByType)return null;let e=performance.getEntriesByType("navigation")[0],t=e?.nextHopProtocol;return t||("u">typeof location&&"http:"===location.protocol?"http/1.1":null)}let e_="pi-web:sidebar-files-placement",eU="below";function eq(){try{var e;return e=window.localStorage.getItem(e_),"tab"===e?"tab":eU}catch{return eU}}let eK=null,eV=new Set;function eZ(){return null===eK&&(eK=eq()),eK}function eJ(){eV.forEach(e=>e())}function eY(e){if(null!==e.key&&e.key!==e_)return;let t=eq();t!==eK&&(eK=t,eJ())}function eG(e){return 0===eV.size&&(window.addEventListener("storage",eY),eK=eq()),eV.add(e),()=>{eV.delete(e),0===eV.size&&window.removeEventListener("storage",eY)}}function eX(e){if(e!==eZ()){eK=e;try{window.localStorage.setItem(e_,e)}catch{}eJ()}}function eQ(){return(0,i.useSyncExternalStore)(eG,eZ,()=>eU)}var e0=n(21278);let e1="(max-width: 640px)",e2="(max-width: 480px)";function e4(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function e8(e){return!!window.matchMedia&&window.matchMedia(e).matches}let e3=e=>e4(e1,e),e5=()=>e8(e1),e6=e=>e4(e2,e),e9=()=>e8(e2);function e7(){return!1}function te(){return(0,i.useSyncExternalStore)(e3,e5,e7)}function tt(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function tn(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function tr(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:s,getDefaultWidth:l,getMaxWidth:o,growthDirection:a,maxWidth:d,minWidth:c,persistClamp:u=!0,storageKey:p,widthRef:h}=e,f=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(!1),x=(0,i.useRef)(s),[v,b]=(0,i.useState)(s),[y,w]=(0,i.useState)(!1),[j,k]=(0,i.useState)(!1);(0,i.useEffect)(()=>{k(!0)},[]);let S=(0,i.useCallback)(()=>Math.min(d,Math.max(c,o())),[o,d,c]),C=(0,i.useCallback)(e=>tt(e,c,S()),[S,c]),N=(0,i.useCallback)(e=>{h.current=e,f.current?.style.setProperty(r,`${e}px`)},[r,h]),$=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=C(e),s=i!==h.current;return N(i),b(i),u?r&&(s||n)&&tn(p,i):n&&(x.current=tt(e,c,d),tn(p,x.current)),i},[N,C,d,c,u,p,h]),E=(0,i.useCallback)(()=>{$(u||m.current?h.current:x.current)},[$,u,h]),I=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),M=(0,i.useCallback)(e=>{let t=m.current;if(t&&t.pointerId===e){m.current=null,I(t),w(!1),$(h.current,{forcePersist:u||h.current!==t.startWidth});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[$,u,I,h]),T=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=m.current;t&&M(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),m.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:h.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",w(!0)},[n,M,h]),R=(0,i.useCallback)(e=>{let t=m.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void M(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX,s=C(t.startWidth+(i-t.startPosition)*r);N(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",`${s} px`)},[N,n,C,M,a]),A=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),L=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),z=(0,i.useCallback)(e=>{M(e.pointerId)},[M]),P=(0,i.useCallback)(()=>{$(l?.()??s,{forcePersist:!0})},[$,s,l]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",s="vertical"===n?"ArrowUp":"ArrowLeft",l=u?h.current:Math.max(h.current,x.current);e.key===(r?i:s)?(e.preventDefault(),$(l+t,{forcePersist:!0})):e.key===(r?s:i)?(e.preventDefault(),$(h.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),$(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),$(Math.max(l,S()),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),P())},[n,$,S,a,c,u,P,h]);return(0,i.useEffect)(()=>{if(g.current)return;g.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(p),t=e??l?.()??s;if(!u){x.current=tt(t,c,d),$(x.current,{persist:!1});return}let n=$(t,{persist:!1});null!==e&&e!==n&&tn(p,n)},[$,s,l,d,c,u,p]),(0,i.useEffect)(()=>{if(!g.current)return;E();let e=()=>{E()};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[E]),(0,i.useEffect)(()=>{if(!y)return;let e=()=>{let e=m.current;e&&M(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[M,y]),(0,i.useEffect)(()=>()=>{let e=m.current;e&&(m.current=null,I(e))},[I]),{isResizing:y,panelRef:f,reclampWidth:E,resetWidth:P,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":j?S():d,"aria-valuemin":c,"aria-valuenow":v,"aria-valuetext":`${v} px`,onDoubleClick:P,onKeyDown:W,onLostPointerCapture:z,onPointerCancel:L,onPointerDown:T,onPointerMove:R,onPointerUp:A,role:"separator",tabIndex:0},width:v}}function ti(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,i.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,l=()=>{null!==s&&(clearTimeout(s),s=null)},o=()=>{n&&(l(),n.classList.add("scrollbar-visible"))},a=()=>{n&&(l(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{o(),a()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",o),n.addEventListener("pointerleave",a),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",o),n?.removeEventListener("pointerleave",a),n?.removeEventListener("scroll",d),l(),n?.classList.remove("scrollbar-visible")}},[t,e])}let ts="/api/sessions/ui-state";async function tl(e){try{let t=await e.json();if(t&&"object"==typeof t&&"string"==typeof t.error)return t.error}catch{}return`HTTP ${e.status}`}function to(e){return e instanceof Error?e.message:String(e)}async function ta(e){if(!e.ok)throw Error(await tl(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!v(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!v(e.sessions)||void 0!==e.projects&&!v(e.projects))return null;let t=M(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!("string"==typeof r&&g.test(r)))continue;let e=function(e){if(!v(e))return null;let t={};return b(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),b(e.archivedAt)&&(t.archivedAt=e.archivedAt),void 0===t.pinnedAt&&void 0===t.archivedAt?null:t}(i);e&&(t.sessions[r]=e)}for(let[n,r]of Object.entries(e.projects??{})){if(!y(n))continue;let e=v(r)&&b(r.pinnedAt)&&y(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=$(e.projectOrder.filter(e=>!(!y(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(v(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=j(s);if(!y(t)||"string"!=typeof e)continue;let l=E(t,e);I(r+1,i+l)&&(n[t]=e,r++,i+=l)}r>0&&(t.projectNames=n)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function td(){let[e,t]=(0,i.useState)(null),n=(0,i.useRef)(null),r=(0,i.useCallback)(()=>{null!==n.current&&(clearTimeout(n.current),n.current=null)},[]),s=(0,i.useCallback)(()=>{r(),t(null)},[r]),l=(0,i.useCallback)(e=>{(r(),function(){try{return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}catch{return!1}}())?t(null):(t(e),n.current=setTimeout(()=>{n.current=null,t(null)},300))},[r]);return(0,i.useEffect)(()=>r,[r]),{phase:e,start:l,end:s}}var tc=n(47650);let tu={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},tp={height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12},th={padding:"6px 16px",borderRadius:6,fontSize:13},tf={...th,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},tm={...th,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function tg(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}async function tx(e,t){let n=await fetch("/api/cwd/browse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,name:t})}),r=await n.json();if(!n.ok||r.error||!r.path)throw Error(r.error??`HTTP ${n.status}`);return r.path}function tv(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function tb(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function ty(e){let{onCancel:t,onSelect:n,initialPath:s,busy:l=!1,error:o}=e,{t:a}=(0,e0.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(s??""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[$,E]=(0,i.useState)(""),[I,M]=(0,i.useState)(null),[T,R]=(0,i.useState)(!1),A=(0,i.useCallback)(async e=>{S(!0),j(null);try{let t=await tg(e),n=t.path??e??"/";p(n),f(t.parentPath??null),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){j(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),A(s||void 0)},[s,A]);let L=()=>{T||(N(!1),E(""),M(null))},z=async()=>{let e=$.trim();if(u&&e&&!T){R(!0),M(null);try{let t=await tx(u,e);N(!1),E(""),await A(t)}catch(e){M(e instanceof Error?e.message:String(e))}finally{R(!1)}}},P=m.trim()!==u,W=!!u&&!P&&!l,O=W&&!k,F=!!h||/^[a-zA-Z]:[\\/]?$/.test(u);return d?(0,tc.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:e=>{e.target!==e.currentTarget||l||t()},onKeyDown:e=>{"Escape"!==e.key||l||t()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{...tu,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:l,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:l?"default":"pointer",opacity:l?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&A(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void A(h??void 0),disabled:k||!F,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:F?"pointer":"default",opacity:F?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),j(null)},style:{...tp,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:k||!m.trim(),title:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:k||!m.trim()?"default":"pointer",opacity:k||!m.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[k?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void A(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(tb,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void A(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(tv,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(w||o)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??o})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{N(!0),M(null)},disabled:!O,style:{...tm,marginRight:"auto",opacity:O?1:.6,cursor:O?"pointer":"default"},children:a("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:l,style:{...tm,cursor:l?"default":"pointer"},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>n(u),disabled:!W,title:a(P?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{...tf,opacity:W?1:.6,cursor:W?"pointer":"default"},children:a(l?"i18n.checking":"directoryPicker.selectThisFolder")})]}),C&&(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:12,background:"rgba(0,0,0,0.35)"},onClick:e=>{e.target===e.currentTarget&&L()},onKeyDown:e=>{e.stopPropagation(),"Escape"===e.key&&L()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),z()},style:{...tu,width:400,maxWidth:"100%"},children:[(0,r.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:a("directoryPicker.createDirectory")}),(0,r.jsxs)("div",{style:{padding:"12px 18px"},children:[(0,r.jsx)("label",{htmlFor:"new-directory-name",style:{display:"block",marginBottom:6,color:"var(--text-muted)",fontSize:11},children:a("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:$,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:a("directoryPicker.directoryNamePlaceholder"),onChange:e=>{E(e.target.value),M(null)},disabled:T,className:"directory-picker-path",style:{...tp,width:"100%",boxSizing:"border-box"}}),I&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:I}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:T||!$.trim(),style:{...tf,flex:1,opacity:T?.65:1,cursor:T||!$.trim()?"default":"pointer"},children:a(T?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:L,disabled:T,style:{...tm,flex:1,cursor:T?"default":"pointer"},children:a("i18n.cancel")})]})]})]})})]})}),d):null}function tw(e){let{onClick:t,title:n}=e;return(0,r.jsx)("button",{type:"button",onClick:t,title:n,"aria-label":n,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}let tj="/icons/catppuccin";function tk(e){let{name:t,size:n=14}=e,i={width:n,height:n,"--catppuccin-icon-light":`url(${tj}/latte/${t}.svg)`,"--catppuccin-icon-dark":`url(${tj}/mocha/${t}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:i})}function tS(e){let{size:t=14,open:n=!1}=e;return(0,r.jsx)(tk,{name:n?"_folder_open":"_folder",size:t})}function tC(e){let{size:t=14}=e;return(0,r.jsx)(tk,{name:"_file",size:t})}let tN={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function t$(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:14,n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(tk,{name:i,size:t});let s=tN[n.split(".").pop()??""];return s?(0,r.jsx)(tk,{name:s,size:t}):(0,r.jsx)(tC,{size:t})}function tE(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tI(e){let t=tE(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function tM(e){let t=tE(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tT(e){let t=tE(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function tR(e,t){if(!t)return e;let n=tE(e),r=tE(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function tA(e,t){return`${tE(e).replace(/\/$/,"")}/${t}`}function tL(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function tz(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function tP(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function tW(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function tO(e,t,n,r){return new Promise((i,s)=>{let l=new FormData;t.forEach(e=>l.append("files",e,e.name));let o=new XMLHttpRequest;o.open("POST",`/api/files/${tI(e)}?type=upload&conflict=${n}`),o.upload.onprogress=e=>{r&&e.lengthComputable&&e.total>0&&r(Math.round(e.loaded/e.total*100))},o.onerror=()=>s(Error("Network error while uploading files")),o.onabort=()=>s(Error("Upload cancelled")),o.onload=()=>{let e={};try{e=JSON.parse(o.responseText)}catch{o.responseText&&(e.error=o.responseText)}i({status:o.status,data:e})},o.send(l)})}function tF(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function tD(e){let t=[];for(let n of Array.from(e.items)){if("file"!==n.kind)continue;let e=n.webkitGetAsEntry?.();if(e?.isDirectory){t.push({kind:"folder",name:e.name});continue}let r=n.getAsFile();r&&t.push({kind:"file",file:r})}return t.length>0?t:Array.from(e.files).map(e=>({kind:"file",file:e}))}let tB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=new Map;return{save(n,r){if(t.delete(n),0!==r.size)for(let i of(t.set(n,new Set(r)),t.keys())){if(t.size<=e)break;t.delete(i)}},restore:e=>new Set(t.get(e))}}();async function tH(e,t){let n=`${t} (HTTP ${e.status})`;try{let t=await e.json();t.error&&(n=t.error)}catch{}return Error(n)}async function t_(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=tI(e),r=await fetch(`/api/files/${n}?type=list${t?"&hidden=1":""}`);if(!r.ok)throw await tH(r,"Failed to load files");return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:tA(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir,outsideLinkTarget:t.outsideLinkTarget,outsideLinkEncloses:t.outsideLinkEncloses,hidden:t.hidden}))}async function tU(e,t){let n=await fetch(`/api/files/${tI(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await tH(n,"Failed to allow the linked folder")}async function tq(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let tK={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},tV={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function tZ(e){let{status:t,t:n}=e;return(0,r.jsx)("span",{title:n(tK[t.status]),"aria-label":n(tK[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:tV[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function tJ(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function tY(e){let{size:t=11}=e;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})}let tG={ignored:"files.hiddenIgnored",excluded:"files.hiddenExcluded"};function tX(e){let{node:t,depth:n,cwd:s,onOpenFile:l,onAtMention:o,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f=!1,parentHidden:m,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b}=e,y=a.has(t.fullPath),w=t.hidden??m,j=t.isDir&&g===t.fullPath,k=u.has(t.fullPath),S=tE(t.fullPath),C=p.get(S),N=t.isDir&&(void 0!==C||h.has(S)),[$,E]=(0,i.useState)(t.children??[]),[I,M]=(0,i.useState)(t.loaded??!1),[T,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[W,O]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(null),_=t.outsideLinkTarget&&t.outsideLinkTarget!==W?t.outsideLinkTarget:null;(0,i.useEffect)(()=>{O(null),H(null)},[t.outsideLinkTarget]);let U=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!I||e){R(!0),L(null);try{let e=await t_(t.fullPath,f);E(e),M(!0)}catch(e){L(e instanceof Error?e.message:String(e))}finally{R(!1)}}},[I,t.fullPath,f]),q=(0,i.useRef)(f);(0,i.useEffect)(()=>{q.current===f||(q.current=f,I&&(y&&!_?U(!0):M(!1)))},[f]),(0,i.useEffect)(()=>{t.isDir&&y&&!I&&!_&&U()},[]),(0,i.useEffect)(()=>{void 0!==c&&I&&!_&&(y?U(!0):M(!1))},[c]);let K=(0,i.useCallback)(()=>{if(t.isDir){let e=!y;d(t.fullPath,e),!e||I||_||U()}else l(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,I,y,_,U,l,d]),V=(0,i.useCallback)(async e=>{if((e.stopPropagation(),_)&&(!t.outsideLinkEncloses||window.confirm(b("files.allowEnclosingLinkConfirm",{target:_})))){D(!0),H(null);try{await tU(t.fullPath,_),O(_),await U(!0)}catch(e){H(e instanceof Error?e.message:String(e))}finally{D(!1)}}},[t.fullPath,t.outsideLinkEncloses,_,U,b]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:K,onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),onDragOver:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="copy",v?.(t.fullPath))}:void 0,onDrop:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),v?.(null),x?.(t.fullPath,tD(e.dataTransfer)))}:void 0,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:24,cursor:"pointer",background:j?"color-mix(in srgb, var(--accent) 16%, transparent)":z?"var(--bg-hover)":"transparent",outline:j?"1px dashed var(--accent)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none"},children:[t.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:y?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!t.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:w?.55:1},children:t.isDir?(0,r.jsx)(tS,{size:14,open:y}):t$(t.name,14)}),(0,r.jsx)("span",{"data-hidden-reason":w,style:{fontSize:12,color:w?"var(--text-muted)":"var(--text)",opacity:w?.55:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:w?`${t.fullPath}
2
- ${b(tG[w])}`:t.fullPath,children:t.name}),!z&&_&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:_}),"aria-label":b("files.outsideLink",{target:_}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(tY,{})}),k&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!z&&!t.isDir&&C&&(0,r.jsx)(tZ,{status:C,t:b}),!z&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),T&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),o&&z&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(tR(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tJ,{}),b("files.mention")]}),z&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${tI(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&_&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:_})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:_}),style:{height:20,padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!_&&(0,r.jsxs)("div",{children:[$.map(e=>(0,r.jsx)(tX,{node:e,depth:n+1,cwd:s,onOpenFile:l,onAtMention:o,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f,parentHidden:w,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===$.length&&I&&!A&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function tQ(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:l,t:o}=e,[a,d]=(0,i.useState)(!1),c=tM(t.filePath),u=tR(t.filePath,n),p=u.lastIndexOf("/"),h=p>=0?u.slice(0,p+1):"",f=p>=0?u.slice(p+1):u;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,c,{modeHint:"diff"}),onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:24,cursor:"pointer",background:a?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(tZ,{status:t,t:o}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:t$(c,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[h&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:0,maxWidth:"100%"},children:f})]}),l&&a&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l(u,!1)},title:o("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tJ,{}),o("files.mention")]})]})}let t0=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:l,onAtMention:o,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:f=!1}=e,{t:m}=(0,e0.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,$]=(0,i.useState)(new Set),[E,I]=(0,i.useState)([]),[M,T]=(0,i.useState)({additions:0,deletions:0}),[R,A]=(0,i.useState)("idle"),[L,z]=(0,i.useState)(0),[P,W]=(0,i.useState)(null),[O,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(""),[U,q]=(0,i.useState)([]),[K,V]=(0,i.useState)(!1),[Z,J]=(0,i.useState)(!1),[Y,G]=(0,i.useState)(new Set),X=(0,i.useRef)(null),[Q,ee]=(0,i.useState)(!1),[et,en]=(0,i.useState)(null),er=(0,i.useRef)(0),ei=(0,i.useRef)(null),es=(0,i.useRef)(j),el=(0,i.useRef)(null),eo=`${l??0}:${S}`,ea="idle"!==R,ed=H.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=H.trim();if(!e){q([]),V(!1),J(!1);return}let t=new AbortController;V(!0),J(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>q((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(q([]),J(!0))}).finally(()=>{t.signal.aborted||V(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,H]),(0,i.useEffect)(()=>{p&&X.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===U.length)return;let e=new Set;for(let t of U){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(tA(n,i))}G(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,U]);let ec=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:tA(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t})(U).map(e)},[n,U]),eu=(0,i.useMemo)(()=>new Map(E.map(e=>[tE(e.filePath),e])),[E]),ep=(0,i.useMemo)(()=>{let e=new Set,t=tE(n).replace(/\/$/,"");for(let n of E){let r=tT(tE(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=tT(r);if(e===r)break;r=e}}return e},[n,E]),eh=(0,i.useCallback)((e,t)=>{k(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ef=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];F({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&($(new Set(n.map(e=>tA(t,e)))),C(e=>e+1))},[]),em=(0,i.useCallback)(async(e,t,n)=>{B(null),W(null),z(0),A("uploading");try{let{status:r,data:i}=await tO(n,e,t,z);if(409===r&&i.conflicts?.length)return void B({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);z(100),ef(i,n)}catch(e){W(e instanceof Error?e.message:String(e))}finally{A("idle")}},[ef]),eg=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ea){F(null),$(new Set),B(null),W(null),z(0),A("checking");try{let n=await fetch(`/api/files/${tI(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void B({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await em(e,"error",t)}catch(e){W(e instanceof Error?e.message:String(e))}finally{A("idle")}}},[em,ea]),ex=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eg(t,n)},[n,eg]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ea||el.current?.click()}}),[ea]);let ev=(0,i.useCallback)(()=>{er.current=0,ee(!1),en(null)},[]),eb=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),er.current+=1,ee(!0))},[]),ey=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",en(e=>null===e?e:null))},[]),ew=(0,i.useCallback)(()=>{er.current<=0||(er.current-=1,0===er.current&&(er.current=0,ee(!1),en(null)))},[]),ej=(0,i.useCallback)((e,t)=>{ev();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);eg(n,e).then(()=>{if(0===r.length)return;let e=m("chat.dropFoldersUnsupported",{names:r.join(", ")});W(t=>t&&n.length>0?t:e)})},[eg,ev,m]),ek=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),ej(et??n,tD(e.dataTransfer)))},[n,et,ej]),eS=(0,i.useCallback)(e=>{en(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{d?.(ea)},[d,ea]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{es.current=j},[j]),(0,i.useEffect)(()=>()=>{null!==ei.current&&tB.save(ei.current,es.current)},[]),(0,i.useEffect)(()=>{let e=ei.current,t=e!==n;if(ei.current=n,t){null!==e&&tB.save(e,es.current);let t=tB.restore(n);es.current=t,k(t),$(new Set),F(null),B(null),W(null)}b(t),w(null);let r=!1;return t_(n,f).then(e=>{r||x(e)}).catch(e=>{r||w(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,l,S,f]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1;return tq(n).then(t=>{e||(I(t.isGitRepository?t.files:[]),T(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),T({additions:0,deletions:0}))}),()=>{e=!0}},[n,l,S]),(0,i.useEffect)(()=>{u?.(E.length)},[E,u]);let eC=ea||null!==D||null!==P||null!==O,eN=(0,i.useCallback)(()=>{O&&0!==O.uploaded.length&&a?.(O.uploaded.map(e=>tR(tA(O.directory,e),n)))},[n,a,O]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eb,onDragOver:ey,onDragLeave:ew,onDrop:ek,children:[(0,r.jsx)("input",{ref:el,type:"file",multiple:!0,hidden:!0,onChange:ex}),eC&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ea&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===R?m("files.checking"):m("files.uploading",{progress:L}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===R?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===R&&(0,r.jsxs)("span",{style:{fontSize:10},children:[L,"%"]})]}),"uploading"===R&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${L}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),D&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.conflictSummary",{count:D.conflicts.length,countSuffix:1===D.conflicts.length?"":"s",files:D.conflicts.join(", ")})}),D.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.cannotReplace",{files:D.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void em(D.files,"overwrite",D.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:m("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void em(D.files,"skip",D.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:m("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>B(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:m("files.cancel")})]})]}),P&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:P}),(0,r.jsx)(tw,{onClick:()=>W(null),title:m("files.dismissError")})]}),O&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[O.uploaded.length>0&&(0,r.jsxs)("span",{title:m("files.uploadedCount",{count:O.uploaded.length}),"aria-label":m("files.uploadedCount",{count:O.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:O.uploaded.length})]}),O.skipped.length>0&&(0,r.jsxs)("span",{title:m("files.skippedCount",{count:O.skipped.length}),"aria-label":m("files.skippedCount",{count:O.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:O.skipped.length})]}),O.errors.length>0&&(0,r.jsxs)("span",{title:m("files.failedCount",{count:O.errors.length}),"aria-label":m("files.failedCount",{count:O.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:O.errors.length})]})]}),O.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eN,title:1===O.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),"aria-label":1===O.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tJ,{}),m("files.mention")]}),(0,r.jsx)(tw,{onClick:()=>F(null),title:m("files.dismissUploadResults")})]}),O.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:X,id:"file-search-input",value:H,onChange:e=>_(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),h?.(!1))},placeholder:m("sidebar.searchFilesPlaceholder"),"aria-label":m("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),H&&(0,r.jsx)("button",{type:"button",onClick:()=>_(""),title:m("sidebar.clearSearch"),"aria-label":m("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),ed&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[K&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.searchingFiles")}),!K&&Z&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:m("i18n.networkError")}),!K&&!Z&&0===U.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.noMatchingFiles")}),!K&&!Z&&U.length>0&&(0,r.jsx)("div",{children:ec.map(e=>(0,r.jsx)(tX,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:o,expandedPaths:Y,onToggleExpanded:(e,t)=>{G(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:eu,changedDirectoryPaths:ep,dropTargetPath:et,onDropFiles:ej,onDropTargetChange:eS,t:m},`${H}:${e.fullPath}`))})]})]}),!c&&E.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":m("files.changeStats",{count:E.length,additions:M.additions,deletions:M.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:m("files.changedCount",{count:E.length})}),(0,r.jsxs)("span",{style:{color:tV.added,fontFamily:"var(--font-mono)"},children:["+",M.additions]}),(0,r.jsxs)("span",{style:{color:tV.deleted,fontFamily:"var(--font-mono)"},children:["-",M.deletions]})]}),E.map(e=>(0,r.jsx)(tQ,{status:e,cwd:n,onOpenFile:s,onAtMention:o,t:m},e.filePath))]}),(c||0===E.length)&&(!p||!ed)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.loading")}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(tX,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:o,expandedPaths:j,onToggleExpanded:eh,refreshToken:eo,highlightedPaths:N,gitStatusByPath:eu,changedDirectoryPaths:ep,showHidden:f,dropTargetPath:et,onDropFiles:ej,onDropTargetChange:eS,t:m},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.noFiles")})]}),Q&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),m("files.dropToUpload",{directory:et?tR(et,n)||et:tM(n)||n})]})]})}),t1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function t2(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:t1[Math.floor(n()*t1.length)]}return s}function t4(e){let{onWidthChange:t}=e,{t:n}=(0,e0.s)(),[s,l]=(0,i.useState)(!1),o=(0,i.useRef)(null),a="0.12.7",d="1.4.0",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,l=()=>{n(t2(e,i+=1)),i<t&&(s=requestAnimationFrame(l))};return n(t2(e,0)),s=requestAnimationFrame(l),()=>cancelAnimationFrame(s)},[e]),t}(s?`${a??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:a??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(o.current&&clearTimeout(o.current),o.current=null,s)?l(!1):(l(!0),o.current=setTimeout(()=>{o.current=null,l(!1)},3e3))},children:c})}var t8=n(2730);let t3=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function t5(e){let t=e.match(t3);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let t6={desktop:32,mobile:48};function t9(e,t,n,r){return Math.hypot(n-e,r-t)}function t7(e){return e.getClientRects().length>0}function ne(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:l}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:l})}function nt(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function nn(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function nr(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function ni(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function ns(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function nl(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function no(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(ne,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function na(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function nd(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function nc(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function nu(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function np(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function nh(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function nf(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function nm(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function ng(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function nx(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function nv(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function nb(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function ny(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function nw(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function nj(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nk(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function nS(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function nC(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function nN(e){let{className:t,...n}=e;return(0,r.jsx)(ne,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function n$(e){let t=t5(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function nE(e){return e.nativeEvent.isComposing||229===e.keyCode}function nI(e){let{rows:t,layout:n,emptyLabel:s,loading:l,error:o,renamingRootId:a,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,e0.s)(),f=(0,i.useRef)(e);f.current=e;let m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);ti(g);let[b,y]=(0,i.useState)(0),[w,j]=(0,i.useState)(0),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),$=(0,i.useRef)(null),E=(0,i.useCallback)(()=>{null===$.current&&($.current=requestAnimationFrame(()=>{$.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),j(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),j(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==$.current&&cancelAnimationFrame($.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let I=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),M=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),T=(0,i.useMemo)(()=>(function(e,t){let n=z[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let l=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let l=r;for(;l>0&&"spacer"===e[l-1].kind;)l--;let o=r+1;for(;o<e.length&&("group-more"===(i=e[o]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)o++;let a=o;for(;a<e.length&&"spacer"===e[a].kind;)a++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[o],gapAbove:t[r]-t[l],gapBelow:t[a]-t[o]}),r=o}return n})(t,n),[t,n]),o=(0,i.useRef)(l);o.current=l;let a=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),l=i.filter(e=>e!==r);if(0===l.length)return null;let o=l.filter(e=>(e.top+e.bottom)/2<n).length;if(o===s)return null;let a=l[l.length-1],d=Math.max(3,o<l.length?l[o].top-l[o].gapAbove/2:a.bottom+a.gapBelow/2);return o>0?{anchorKey:l[o-1].key,position:"after",lineY:d}:{anchorKey:l[0].key,position:"before",lineY:d}}(o.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let l=n.getBoundingClientRect().top,o=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:l,maxTop:o}=e,a=Math.max(l,o),d=t-i-r,c=null!==n&&n>=l&&n<=a+r?n:null,u=e=>e>=l&&e<=a,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,l,t+i,a]:[d,c-s-r,l,t+i,c+s,a],f=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return f(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??f(e=>u(e)&&!p(e))??Math.min(a,Math.max(l,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:o.top,maxTop:o.bottom-d});t.style.top=`${c-l}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",w,!0),window.removeEventListener("blur",j),document.removeEventListener("visibilitychange",k),u(null))},l=()=>{let e=a.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],o=a.current;if(!o||"dragging"!==o.phase)return;let d=s.current.scrollRef.current;if(!d||!t7(d))return void l();let c=t(o),u=i||c!==(r=o.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);o.drop=c,n(),u&&e(o)};function p(){c()}let h=()=>{let e=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!t7(t))return void l();let n=t.getBoundingClientRect(),r=function(e,t,n,r){let i=Math.min(r,(n-t)/2);if(!(i>0)||!Number.isFinite(e))return 0;let s=e=>Math.ceil(14*Math.min(1,e/i));return e<t+i?-s(t+i-e):e>n-i?s(e-(n-i)):0}(e.clientY,n.top,n.bottom,t6[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},f=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!t7(t)||!e.element.isConnected)return void l();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},m=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=t9(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&f(t):n>8&&i();break;case"armed":t9(t.armX,t.armY,e.clientX,e.clientY)>=4&&f(t);break;case"dragging":c()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&i()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&l()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),l())}function w(e){let t=a.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function j(){i()}function k(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",w,!0),window.addEventListener("blur",j),document.addEventListener("visibilitychange",k),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(m,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:l,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let f=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),m=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?l.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,l]),handlers:p.handlers,onClickCapture:f,onPointerDownCapture:m}}({rows:t,offsets:T,layout:n,enabled:R&&!l,scrollRef:g,innerRef:x,treeRef:m,ghostRef:v,onMove:(e,t,n)=>f.current.onMoveGroup?.(e,t,n)}),W=L.view,O=W?`group:${W.projectKey}`:null,[F,D]=(0,i.useState)(null),B=p&&p.id!==F?p:null,H=B?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===k||t.key===u||t.key===H||t.key===O||"session"===t.kind&&(t.family.root.id===a||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,k,u,H,O,a,d,c]),U=(0,i.useMemo)(()=>l?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),l=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)&&n>0?n:600,a=Number.isFinite(r)&&r>0?r:0,d=l-a,c=l+o+a,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let f=u,m=[];for(let e=h;e<f;e++)m.push(e);if(0===i.length)return m;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=f));return 0===g.length?m:[...new Set([...m,...g])].sort((e,t)=>e-t)}(T,b,w,240,_),[l,T,b,w,_]),q=(0,i.useRef)(null),K=(0,i.useRef)(null),V=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");q.current={rowKey:e,fallbackKey:t===P?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?f.current.onShowMore(t):f.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;q.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=ei(T,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(K.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,T]);let Z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!B)return;let e=t.findIndex(e=>e.key===B.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(Z.current,B,e>=0,Date.now());if(Z.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=ei(T,e,t.scrollTop,t.clientHeight,B.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}B.takeFocusFrom&&(K.current={rowKey:B.rowKey,fallbackKey:B.rowKey,tries:0,takeFocusFrom:B.takeFocusFrom})}D(B.id),f.current.onRevealHandled?.(B.id)}},[B,t,T]),(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){K.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),K.current=null):++e.tries>2&&(K.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind),Y=!l&&!o&&null!==s&&!J,G=W?.source??null,X=W?.drop?.lineY??null,Q=W?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===W.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:m,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[l&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),o&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:o}),Y&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:E,onFocus:I,onBlur:M,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!l&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:T[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=T[e],l=T[e+1]-s,o=i.key===u;if("session"===i.kind)return(0,r.jsx)(nT,{row:i,layout:n,top:s,height:l,now:C,renaming:i.family.root.id===a,confirming:i.family.root.id===c,menuOpen:o,handlers:f},i.key);if("archive-group"===i.kind)return(0,r.jsx)(nW,{row:i,top:s,height:l,menuOpen:o,handlers:f},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(nz,{row:i,top:s,height:l,menuOpen:o,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:W?.projectKey===i.project.key?W.phase:null,drag:L.handlers,handlers:f},i.key)}return(0,r.jsx)(nP,{row:i,top:s,height:l,handlers:f,onMoreAction:V},i.key)}),G&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:G.top,height:G.bottom-G.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function nM(e,t){return{top:e,height:t}}let nT=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:l,height:o,now:a,renaming:c,confirming:u,menuOpen:p,handlers:h}=e,{locale:f,t:m}=(0,e0.s)(),{family:g,context:x,status:v}=i,b=g.root,y=n$(b),w=new Date(a),j=["session-tree-row session-tree-session",v.selected?"is-selected":"",v.running?"is-running":"","archive"===x?"is-archived":"",p?"is-menu-open":"",u?"is-confirming":"",c?"is-renaming":""].filter(Boolean).join(" ");if(u){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:j,style:nM(l,o),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||nE(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(nA,{label:m("sidebar.deleteSession",{title:e}),deleteLabel:m("sidebar.delete"),cancelLabel:m("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(g,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(c)return(0,r.jsx)("div",{className:j,style:nM(l,o),"data-row-key":i.key,children:(0,r.jsx)(nR,{initialValue:y,label:m("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(g,e),onCancel:()=>h.current.onRenameCancel()})});let k=b.isWorktree&&b.branch?b.branch:null,S=b.name&&b.relation?.kind==="fork"?ek(b.name):null,C=b.detailsPending?"…":m("sidebar.messagesCount",{count:b.messageCount}),N=`${y}
2
+ ${b(tG[w])}`:t.fullPath,children:t.name}),!z&&_&&(0,r.jsx)("span",{title:b("files.outsideLink",{target:_}),"aria-label":b("files.outsideLink",{target:_}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,r.jsx)(tY,{})}),k&&(0,r.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!z&&!t.isDir&&C&&(0,r.jsx)(tZ,{status:C,t:b}),!z&&N&&(0,r.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),T&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),o&&z&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(tR(t.fullPath,s),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tJ,{}),b("files.mention")]}),z&&!t.isDir&&(0,r.jsx)("a",{href:`/api/files/${tI(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&_&&(0,r.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:_})}),t.outsideLinkEncloses&&(0,r.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,r.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:_}),style:{height:20,padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),B&&(0,r.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:B})]}),t.isDir&&y&&!_&&(0,r.jsxs)("div",{children:[$.map(e=>(0,r.jsx)(tX,{node:e,depth:n+1,cwd:s,onOpenFile:l,onAtMention:o,expandedPaths:a,onToggleExpanded:d,refreshToken:c,highlightedPaths:u,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:f,parentHidden:w,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===$.length&&I&&!A&&(0,r.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,r.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function tQ(e){let{status:t,cwd:n,onOpenFile:s,onAtMention:l,t:o}=e,[a,d]=(0,i.useState)(!1),c=tM(t.filePath),u=tR(t.filePath,n),p=u.lastIndexOf("/"),h=p>=0?u.slice(0,p+1):"",f=p>=0?u.slice(p+1):u;return(0,r.jsxs)("div",{onClick:()=>s(t.filePath,c,{modeHint:"diff"}),onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:24,cursor:"pointer",background:a?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(tZ,{status:t,t:o}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:t$(c,13)}),(0,r.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[h&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:0,maxWidth:"100%"},children:f})]}),l&&a&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),l(u,!1)},title:o("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tJ,{}),o("files.mention")]})]})}let t0=(0,i.forwardRef)(function(e,t){let{cwd:n,onOpenFile:s,refreshKey:l,onAtMention:o,onAtMentions:a,onUploadBusyChange:d,changesCollapsed:c,onChangesCountChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,showHidden:f=!1}=e,{t:m}=(0,e0.s)(),[g,x]=(0,i.useState)([]),[v,b]=(0,i.useState)(!0),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(0),[N,$]=(0,i.useState)(new Set),[E,I]=(0,i.useState)([]),[M,T]=(0,i.useState)({additions:0,deletions:0}),[R,A]=(0,i.useState)("idle"),[L,z]=(0,i.useState)(0),[P,W]=(0,i.useState)(null),[O,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(null),[H,_]=(0,i.useState)(""),[U,q]=(0,i.useState)([]),[K,V]=(0,i.useState)(!1),[Z,J]=(0,i.useState)(!1),[Y,G]=(0,i.useState)(new Set),X=(0,i.useRef)(null),[Q,ee]=(0,i.useState)(!1),[et,en]=(0,i.useState)(null),er=(0,i.useRef)(0),ei=(0,i.useRef)(null),es=(0,i.useRef)(j),el=(0,i.useRef)(null),eo=`${l??0}:${S}`,ea="idle"!==R,ed=H.trim().length>0;(0,i.useEffect)(()=>{if(!p)return;let e=H.trim();if(!e){q([]),V(!1),J(!1);return}let t=new AbortController;V(!0),J(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>q((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(q([]),J(!0))}).finally(()=>{t.signal.aborted||V(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,p,H]),(0,i.useEffect)(()=>{p&&X.current?.focus()},[p]),(0,i.useEffect)(()=>{if(0===U.length)return;let e=new Set;for(let t of U){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(tA(n,i))}G(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,U]);let ec=(0,i.useMemo)(()=>{let e=t=>({name:t.name,fullPath:tA(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t})(U).map(e)},[n,U]),eu=(0,i.useMemo)(()=>new Map(E.map(e=>[tE(e.filePath),e])),[E]),ep=(0,i.useMemo)(()=>{let e=new Set,t=tE(n).replace(/\/$/,"");for(let n of E){let r=tT(tE(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=tT(r);if(e===r)break;r=e}}return e},[n,E]),eh=(0,i.useCallback)((e,t)=>{k(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ef=(0,i.useCallback)((e,t)=>{let n=e.uploaded??[];F({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&($(new Set(n.map(e=>tA(t,e)))),C(e=>e+1))},[]),em=(0,i.useCallback)(async(e,t,n)=>{B(null),W(null),z(0),A("uploading");try{let{status:r,data:i}=await tO(n,e,t,z);if(409===r&&i.conflicts?.length)return void B({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);z(100),ef(i,n)}catch(e){W(e instanceof Error?e.message:String(e))}finally{A("idle")}},[ef]),eg=(0,i.useCallback)(async(e,t)=>{if(0!==e.length&&!ea){F(null),$(new Set),B(null),W(null),z(0),A("checking");try{let n=await fetch(`/api/files/${tI(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void B({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await em(e,"error",t)}catch(e){W(e instanceof Error?e.message:String(e))}finally{A("idle")}}},[em,ea]),ex=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eg(t,n)},[n,eg]);(0,i.useImperativeHandle)(t,()=>({openUploadPicker(){ea||el.current?.click()}}),[ea]);let ev=(0,i.useCallback)(()=>{er.current=0,ee(!1),en(null)},[]),eb=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),er.current+=1,ee(!0))},[]),ey=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",en(e=>null===e?e:null))},[]),ew=(0,i.useCallback)(()=>{er.current<=0||(er.current-=1,0===er.current&&(er.current=0,ee(!1),en(null)))},[]),ej=(0,i.useCallback)((e,t)=>{ev();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);eg(n,e).then(()=>{if(0===r.length)return;let e=m("chat.dropFoldersUnsupported",{names:r.join(", ")});W(t=>t&&n.length>0?t:e)})},[eg,ev,m]),ek=(0,i.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),ej(et??n,tD(e.dataTransfer)))},[n,et,ej]),eS=(0,i.useCallback)(e=>{en(t=>t===e?t:e)},[]);(0,i.useEffect)(()=>{d?.(ea)},[d,ea]),(0,i.useEffect)(()=>()=>d?.(!1),[d]),(0,i.useEffect)(()=>{es.current=j},[j]),(0,i.useEffect)(()=>()=>{null!==ei.current&&tB.save(ei.current,es.current)},[]),(0,i.useEffect)(()=>{let e=ei.current,t=e!==n;if(ei.current=n,t){null!==e&&tB.save(e,es.current);let t=tB.restore(n);es.current=t,k(t),$(new Set),F(null),B(null),W(null)}b(t),w(null);let r=!1;return t_(n,f).then(e=>{r||x(e)}).catch(e=>{r||w(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)}),()=>{r=!0}},[n,l,S,f]),(0,i.useEffect)(()=>{let e=()=>C(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,i.useEffect)(()=>{let e=!1;return tq(n).then(t=>{e||(I(t.isGitRepository?t.files:[]),T(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),T({additions:0,deletions:0}))}),()=>{e=!0}},[n,l,S]),(0,i.useEffect)(()=>{u?.(E.length)},[E,u]);let eC=ea||null!==D||null!==P||null!==O,eN=(0,i.useCallback)(()=>{O&&0!==O.uploaded.length&&a?.(O.uploaded.map(e=>tR(tA(O.directory,e),n)))},[n,a,O]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eb,onDragOver:ey,onDragLeave:ew,onDrop:ek,children:[(0,r.jsx)("input",{ref:el,type:"file",multiple:!0,hidden:!0,onChange:ex}),eC&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ea&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===R?m("files.checking"):m("files.uploading",{progress:L}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===R?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===R&&(0,r.jsxs)("span",{style:{fontSize:10},children:[L,"%"]})]}),"uploading"===R&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${L}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),D&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.conflictSummary",{count:D.conflicts.length,countSuffix:1===D.conflicts.length?"":"s",files:D.conflicts.join(", ")})}),D.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:m("files.cannotReplace",{files:D.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void em(D.files,"overwrite",D.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:m("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void em(D.files,"skip",D.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:m("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>B(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:m("files.cancel")})]})]}),P&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:P}),(0,r.jsx)(tw,{onClick:()=>W(null),title:m("files.dismissError")})]}),O&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[O.uploaded.length>0&&(0,r.jsxs)("span",{title:m("files.uploadedCount",{count:O.uploaded.length}),"aria-label":m("files.uploadedCount",{count:O.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:O.uploaded.length})]}),O.skipped.length>0&&(0,r.jsxs)("span",{title:m("files.skippedCount",{count:O.skipped.length}),"aria-label":m("files.skippedCount",{count:O.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:O.skipped.length})]}),O.errors.length>0&&(0,r.jsxs)("span",{title:m("files.failedCount",{count:O.errors.length}),"aria-label":m("files.failedCount",{count:O.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:O.errors.length})]})]}),O.uploaded.length>0&&a&&(0,r.jsxs)("button",{type:"button",onClick:eN,title:1===O.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),"aria-label":1===O.uploaded.length?m("files.addUploadedFile"):m("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(tJ,{}),m("files.mention")]}),(0,r.jsx)(tw,{onClick:()=>F(null),title:m("files.dismissUploadResults")})]}),O.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),p&&(0,r.jsxs)("div",{style:{padding:"2px 8px 6px"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:X,id:"file-search-input",value:H,onChange:e=>_(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),h?.(!1))},placeholder:m("sidebar.searchFilesPlaceholder"),"aria-label":m("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),H&&(0,r.jsx)("button",{type:"button",onClick:()=>_(""),title:m("sidebar.clearSearch"),"aria-label":m("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),ed&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[K&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.searchingFiles")}),!K&&Z&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:m("i18n.networkError")}),!K&&!Z&&0===U.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:m("sidebar.noMatchingFiles")}),!K&&!Z&&U.length>0&&(0,r.jsx)("div",{children:ec.map(e=>(0,r.jsx)(tX,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:o,expandedPaths:Y,onToggleExpanded:(e,t)=>{G(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:N,gitStatusByPath:eu,changedDirectoryPaths:ep,dropTargetPath:et,onDropFiles:ej,onDropTargetChange:eS,t:m},`${H}:${e.fullPath}`))})]})]}),!c&&E.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":m("files.changeStats",{count:E.length,additions:M.additions,deletions:M.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:m("files.changedCount",{count:E.length})}),(0,r.jsxs)("span",{style:{color:tV.added,fontFamily:"var(--font-mono)"},children:["+",M.additions]}),(0,r.jsxs)("span",{style:{color:tV.deleted,fontFamily:"var(--font-mono)"},children:["-",M.deletions]})]}),E.map(e=>(0,r.jsx)(tQ,{status:e,cwd:n,onOpenFile:s,onAtMention:o,t:m},e.filePath))]}),(c||0===E.length)&&(!p||!ed)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.loading")}):y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:y}):g.map(e=>(0,r.jsx)(tX,{node:e,depth:0,cwd:n,onOpenFile:s,onAtMention:o,expandedPaths:j,onToggleExpanded:eh,refreshToken:eo,highlightedPaths:N,gitStatusByPath:eu,changedDirectoryPaths:ep,showHidden:f,dropTargetPath:et,onDropFiles:ej,onDropTargetChange:eS,t:m},e.fullPath)),!v&&!y&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:m("files.noFiles")})]}),Q&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),m("files.dropToUpload",{directory:et?tR(et,n)||et:tM(n)||n})]})]})}),t1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function t2(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=4*e.length;if(t>=r)return e;let i=Math.floor(t/r*e.length),s="";for(let t=0;t<e.length;t++){let r=e[t];s+=" "===r||t<i?r:t1[Math.floor(n()*t1.length)]}return s}function t4(e){let{onWidthChange:t}=e,{t:n}=(0,e0.s)(),[s,l]=(0,i.useState)(!1),o=(0,i.useRef)(null),a="0.12.8",d="1.4.0",c=function(e){let[t,n]=(0,i.useState)(e),r=(0,i.useRef)(e);return(0,i.useEffect)(()=>{if(r.current===e)return;if(r.current=e,window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return void n(e);let t=4*e.length,i=0,s=0,l=()=>{n(t2(e,i+=1)),i<t&&(s=requestAnimationFrame(l))};return n(t2(e,0)),s=requestAnimationFrame(l),()=>cancelAnimationFrame(s)},[e]),t}(s?`${a??"0.0.0"}p${d??"0.0.0"}`:"Pi Web");return(0,i.useLayoutEffect)(()=>{t?.()},[c.length,t]),(0,i.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]),(0,r.jsx)("button",{type:"button",className:`sidebar-brand${s?" is-version":""}`,"aria-label":n("sidebar.brandLabel",{app:a??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(o.current&&clearTimeout(o.current),o.current=null,s)?l(!1):(l(!0),o.current=setTimeout(()=>{o.current=null,l(!1)},3e3))},children:c})}var t8=n(2730);let t3=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function t5(e){let t=e.match(t3);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let t6={desktop:32,mobile:48};function t9(e,t,n,r){return Math.hypot(n-e,r-t)}function t7(e){return e.getClientRects().length>0}function ne(e){let{size:t=13,className:n,label:i,strokeWidth:s=2,children:l}=e;return(0,r.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",className:n,...i?{role:"img","aria-label":i}:{"aria-hidden":!0},children:l})}function nt(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})}function nn(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function nr(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,r.jsx)("path",{d:"M10 13h4"})]})}function ni(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function ns(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function nl(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,r.jsx)("path",{d:"m2 2 20 20"}),(0,r.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function no(e){let{strokeWidth:t,...n}=e;return(0,r.jsx)(ne,{...n,strokeWidth:t,children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}function na(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function nd(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,r.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,r.jsx)("path",{d:"M12 12v4.5"})]})}function nc(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function nu(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function np(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function nh(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function nf(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function nm(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function ng(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function nx(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function nv(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,r.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function nb(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function ny(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}function nw(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}function nj(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}function nk(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function nS(e){return(0,r.jsxs)(ne,{...e,children:[(0,r.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function nC(e){return(0,r.jsx)(ne,{...e,children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function nN(e){let{className:t,...n}=e;return(0,r.jsx)(ne,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}function n$(e){let t=t5(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function nE(e){return e.nativeEvent.isComposing||229===e.keyCode}function nI(e){let{rows:t,layout:n,emptyLabel:s,loading:l,error:o,renamingRootId:a,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,e0.s)(),f=(0,i.useRef)(e);f.current=e;let m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null);ti(g);let[b,y]=(0,i.useState)(0),[w,j]=(0,i.useState)(0),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),$=(0,i.useRef)(null),E=(0,i.useCallback)(()=>{null===$.current&&($.current=requestAnimationFrame(()=>{$.current=null;let e=g.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=()=>{let t=`${Math.max(0,e.offsetWidth-e.clientWidth)}px`;e.style.setProperty("--session-tree-scrollbar",t),e.offsetWidth>0&&e.closest(".session-sidebar")?.style.setProperty("--session-tree-scrollbar",t)};if(t(),j(e.clientHeight),y(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),j(e.clientHeight),y(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>()=>{null!==$.current&&cancelAnimationFrame($.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let I=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),M=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),T=(0,i.useMemo)(()=>(function(e,t){let n=z[t],r=Array(e.length+1);r[0]=0;for(let t=0;t<e.length;t++)r[t+1]=r[t]+n[e[t].kind];return r})(t,n),[t,n]),R=!!e.onMoveGroup,A=(0,i.useMemo)(()=>{let e={pinned:0,other:0};for(let n of t)"group"===n.kind&&e[n.project.pinned?"pinned":"other"]++;return e},[t]),L=function(e){let{rows:t,offsets:n,enabled:r}=e,s=(0,i.useRef)(e);s.current=e;let l=(0,i.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let l=r;for(;l>0&&"spacer"===e[l-1].kind;)l--;let o=r+1;for(;o<e.length&&("group-more"===(i=e[o]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)o++;let a=o;for(;a<e.length&&"spacer"===e[a].kind;)a++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[o],gapAbove:t[r]-t[l],gapBelow:t[a]-t[o]}),r=o}return n})(t,n),[t,n]),o=(0,i.useRef)(l);o.current=l;let a=(0,i.useRef)(null),d=(0,i.useRef)(0),[c,u]=(0,i.useState)(null),p=(0,i.useMemo)(()=>{let e=e=>{u("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=s.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),l=i.filter(e=>e!==r);if(0===l.length)return null;let o=l.filter(e=>(e.top+e.bottom)/2<n).length;if(o===s)return null;let a=l[l.length-1],d=Math.max(3,o<l.length?l[o].top-l[o].gapAbove/2:a.bottom+a.gapBelow/2);return o>0?{anchorKey:l[o-1].key,position:"after",lineY:d}:{anchorKey:l[0].key,position:"before",lineY:d}}(o.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.current,t=s.current.ghostRef.current,n=s.current.treeRef.current,r=s.current.innerRef.current,i=s.current.scrollRef.current;if(!e?.ghost||!t||!n||!i)return;let l=n.getBoundingClientRect().top,o=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:l,maxTop:o}=e,a=Math.max(l,o),d=t-i-r,c=null!==n&&n>=l&&n<=a+r?n:null,u=e=>e>=l&&e<=a,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,l,t+i,a]:[d,c-s-r,l,t+i,c+s,a],f=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-d)<Math.abs(t-d))&&(t=n);return t};return f(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??f(e=>u(e)&&!p(e))??Math.min(a,Math.max(l,d))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:d,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:o.top,maxTop:o.bottom-d});t.style.top=`${c-l}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,s.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},i=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",w,!0),window.removeEventListener("blur",j),document.removeEventListener("visibilitychange",k),u(null))},l=()=>{let e=a.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&i();return}e.phase="cancelled",e.drop=null,r(e),u(null)}},c=function(){var r;let i=arguments.length>0&&void 0!==arguments[0]&&arguments[0],o=a.current;if(!o||"dragging"!==o.phase)return;let d=s.current.scrollRef.current;if(!d||!t7(d))return void l();let c=t(o),u=i||c!==(r=o.drop)&&(null===c||null===r||c.anchorKey!==r.anchorKey||c.position!==r.position||c.lineY!==r.lineY);o.drop=c,n(),u&&e(o)};function p(){c()}let h=()=>{let e=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!t7(t))return void l();let n=t.getBoundingClientRect(),r=function(e,t,n,r){let i=Math.min(r,(n-t)/2);if(!(i>0)||!Number.isFinite(e))return 0;let s=e=>Math.ceil(14*Math.min(1,e/i));return e<t+i?-s(t+i-e):e>n-i?s(e-(n-i)):0}(e.clientY,n.top,n.bottom,t6[s.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(s.current.offsets[s.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,c())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},f=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!t7(t)||!e.element.isConnected)return void l();if(e.phase="dragging","touch"!==e.pointerType)try{e.element.setPointerCapture(e.pointerId)}catch{}e.ghost={left:e.element.getBoundingClientRect().left-n.getBoundingClientRect().left+4},e.expectedScrollTop=t.scrollTop,t.addEventListener("scroll",p,{passive:!0}),e.frame=requestAnimationFrame(h),c(!0)},m=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=s.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void i();t.clientX=e.clientX,t.clientY=e.clientY;let n=t9(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&f(t):n>8&&i();break;case"armed":t9(t.armX,t.armY,e.clientX,e.clientY)>=4&&f(t);break;case"dragging":c()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&s.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(d.current=e.timeStamp+600),i()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&i()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&l()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),l())}function w(e){let t=a.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function j(){i()}function k(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",w,!0),window.addEventListener("blur",j),document.addEventListener("visibilitychange",k),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(m,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=s.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&i()}},cancel:l,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,i.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,i.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,i.useEffect)(()=>()=>p.teardown(),[p]);let f=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),m=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?l.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,l]),handlers:p.handlers,onClickCapture:f,onPointerDownCapture:m}}({rows:t,offsets:T,layout:n,enabled:R&&!l,scrollRef:g,innerRef:x,treeRef:m,ghostRef:v,onMove:(e,t,n)=>f.current.onMoveGroup?.(e,t,n)}),W=L.view,O=W?`group:${W.projectKey}`:null,[F,D]=(0,i.useState)(null),B=p&&p.id!==F?p:null,H=B?.rowKey??null,_=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===k||t.key===u||t.key===H||t.key===O||"session"===t.kind&&(t.family.root.id===a||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,k,u,H,O,a,d,c]),U=(0,i.useMemo)(()=>l?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),l=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)&&n>0?n:600,a=Number.isFinite(r)&&r>0?r:0,d=l-a,c=l+o+a,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>d?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=c?p=t:u=t+1}let f=u,m=[];for(let e=h;e<f;e++)m.push(e);if(0===i.length)return m;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=f));return 0===g.length?m:[...new Set([...m,...g])].sort((e,t)=>e-t)}(T,b,w,240,_),[l,T,b,w,_]),q=(0,i.useRef)(null),K=(0,i.useRef)(null),V=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");q.current={rowKey:e,fallbackKey:t===P?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?f.current.onShowMore(t):f.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;q.current=null;let n=g.current,r=t.findIndex(t=>t.key===e.rowKey);if(r<0&&(r=t.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&n&&r>=0){let e=ei(T,r,n.scrollTop,n.clientHeight);null!==e&&(n.scrollTop=e),y(n.scrollTop)}e.focus&&(K.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[t,T]);let Z=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!B)return;let e=t.findIndex(e=>e.key===B.rowKey),n=function(e,t,n,r){let i=e?.id===t.id?e:{id:t.id,misses:0};if(!(r-t.at<=3e3))return{misses:i,action:"drop"};if(n)return{misses:i,action:"reveal"};let s={id:t.id,misses:i.misses+1};return{misses:s,action:s.misses>=3?"drop":"wait"}}(Z.current,B,e>=0,Date.now());if(Z.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=g.current;if(t&&t.getClientRects().length>0){let n=ei(T,e,t.scrollTop,t.clientHeight,B.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}B.takeFocusFrom&&(K.current={rowKey:B.rowKey,fallbackKey:B.rowKey,tries:0,takeFocusFrom:B.takeFocusFrom})}D(B.id),f.current.onRevealHandled?.(B.id)}},[B,t,T]),(0,i.useLayoutEffect)(()=>{let e=K.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){K.current=null;return}let n=g.current,r=e=>n?.querySelector(`[data-row-key="${CSS.escape(e)}"]`)??null,i=r(e.rowKey),s=i?.querySelector('[data-more-action="more"]')??i?.querySelector("a[href], button")??r(e.fallbackKey)?.querySelector("a[href], button");s?(s.focus({preventScroll:!0}),K.current=null):++e.tries>2&&(K.current=null)},[U]);let J=t.some(e=>"session"===e.kind||"group"===e.kind),Y=!l&&!o&&null!==s&&!J,G=W?.source??null,X=W?.drop?.lineY??null,Q=W?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===W.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:m,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[l&&(0,r.jsx)("div",{className:"session-tree-message",children:h("sidebar.loading")}),o&&(0,r.jsx)("div",{className:"session-tree-message is-error",children:o}),Y&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:g,className:"session-tree-scroll scrollbar-subtle",onScroll:E,onFocus:I,onBlur:M,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!l&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:T[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=T[e],l=T[e+1]-s,o=i.key===u;if("session"===i.kind)return(0,r.jsx)(nT,{row:i,layout:n,top:s,height:l,now:C,renaming:i.family.root.id===a,confirming:i.family.root.id===c,menuOpen:o,handlers:f},i.key);if("archive-group"===i.kind)return(0,r.jsx)(nW,{row:i,top:s,height:l,menuOpen:o,handlers:f},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(nz,{row:i,top:s,height:l,menuOpen:o,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:W?.projectKey===i.project.key?W.phase:null,drag:L.handlers,handlers:f},i.key)}return(0,r.jsx)(nP,{row:i,top:s,height:l,handlers:f,onMoreAction:V},i.key)}),G&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:G.top,height:G.bottom-G.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:v,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function nM(e,t){return{top:e,height:t}}let nT=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:l,height:o,now:a,renaming:c,confirming:u,menuOpen:p,handlers:h}=e,{locale:f,t:m}=(0,e0.s)(),{family:g,context:x,status:v}=i,b=g.root,y=n$(b),w=new Date(a),j=["session-tree-row session-tree-session",v.selected?"is-selected":"",v.running?"is-running":"","archive"===x?"is-archived":"",p?"is-menu-open":"",u?"is-confirming":"",c?"is-renaming":""].filter(Boolean).join(" ");if(u){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:j,style:nM(l,o),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||nE(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(nA,{label:m("sidebar.deleteSession",{title:e}),deleteLabel:m("sidebar.delete"),cancelLabel:m("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(g,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(c)return(0,r.jsx)("div",{className:j,style:nM(l,o),"data-row-key":i.key,children:(0,r.jsx)(nR,{initialValue:y,label:m("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(g,e),onCancel:()=>h.current.onRenameCancel()})});let k=b.isWorktree&&b.branch?b.branch:null,S=b.name&&b.relation?.kind==="fork"?ek(b.name):null,C=b.detailsPending?"…":m("sidebar.messagesCount",{count:b.messageCount}),N=`${y}
3
3
  ${C} \xb7 ${(0,t8.fw)(b.modified,f,w)}${k?` \xb7 ⑂ ${k}`:""}`,$="";v.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":m("sidebar.agentAwaitingInput")}),$=" is-awaiting",n=m("sidebar.agentAwaitingInput")):v.running?(t=(0,r.jsx)(nN,{size:12,label:m("sidebar.agentRunning")}),$=" is-running",n=m("sidebar.agentRunning")):v.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":m("sidebar.newSessionActivity")}),$=" is-unread",n=m("sidebar.newActivity")):t="pinned"===x?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):(0,t8.Rg)(g.latestModified,f,w);let E="desktop"===s&&("archive"===x||!v.running),I=(0,r.jsxs)(r.Fragment,{children:[S?(0,r.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,r.jsx)("span",{className:"session-tree-title-base",children:S.base}),(0,r.jsx)("span",{className:"session-tree-title-suffix",children:S.suffix})]}):(0,r.jsx)("span",{className:"session-tree-title",children:y}),k&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(na,{size:10,className:"session-tree-branch-icon"}),k]}),(0,r.jsx)("span",{className:`session-tree-meta${$}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:j,style:nM(l,o),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(g),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[v.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":v.selected?"true":void 0,children:I}):(0,r.jsx)("a",{className:"session-tree-main",href:d(b.id),title:N,"aria-current":v.selected?"true":void 0,onClick:e=>{e.stopPropagation(),e.defaultPrevented||0!==e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||(e.preventDefault(),h.current.onSelectFamily(g))},children:I}),!v.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[E&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.restore"),title:m("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(g)},children:(0,r.jsx)(ni,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.archive"),title:m("sidebar.archive"),onClick:e=>{e.stopPropagation(),h.current.onArchiveFamily(g)},children:(0,r.jsx)(nr,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${p?" is-active":""}`,"aria-label":m("sidebar.moreActions"),title:m("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":p,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;h.current.onOpenRowMenu(i,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,r.jsx)(nn,{size:14})})]})]})});function nR(e){let{initialValue:t,label:n,maxLength:s,onCommit:l,onCancel:o}=e,[a,d]=(0,i.useState)(t),c=(0,i.useRef)(null),u=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let p=e=>{u.current||(u.current=!0,l(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:a,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!nE(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),u.current)return;u.current=!0,o()}}}})}function nA(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:l,onCancel:o}=e,a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||a.current?.focus()},[]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,r.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:l,children:[(0,r.jsx)(nu,{size:12}),n]}),(0,r.jsx)("button",{ref:a,type:"button",className:"session-tree-confirm-cancel",onClick:o,children:s})]})}function nL(e){let{running:t,awaiting:n=0,unread:i,t:s}=e;return 0===t&&0===n&&0===i?null:(0,r.jsxs)("span",{className:"session-tree-summary",children:[t>0&&(0,r.jsxs)("span",{className:"session-tree-summary-running",role:"img",title:s("sidebar.agentRunning"),"aria-label":`${s("sidebar.agentRunning")} (${t})`,children:[(0,r.jsx)(nN,{size:10}),t]}),n>0&&(0,r.jsxs)("span",{className:"session-tree-summary-awaiting",role:"img",title:s("sidebar.agentAwaitingInput"),"aria-label":`${s("sidebar.agentAwaitingInput")} (${n})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot is-awaiting"}),n]}),i>0&&(0,r.jsxs)("span",{className:"session-tree-summary-unread",role:"img",title:s("sidebar.newSessionActivity"),"aria-label":`${s("sidebar.newSessionActivity")} (${i})`,children:[(0,r.jsx)("span",{className:"session-tree-summary-dot"}),i]})]})}let nz=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:l,renaming:o,canDrag:a,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,e0.s)(),{project:h,expanded:f}=t,m=(0,i.useRef)(null),g=["session-tree-row session-tree-group",h.current?"is-current":"",l?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=m.current;if(!a||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[a,c]),o)?(0,r.jsx)("div",{ref:m,className:`${g} is-renaming`,style:nM(n,s),"data-row-key":t.key,children:(0,r.jsx)(nR,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>u.current.onRenameProjectCommit(h,e),onCancel:()=>u.current.onRenameProjectCancel()})}):(0,r.jsxs)("div",{ref:m,className:g,style:nM(n,s),"data-row-key":t.key,onPointerDown:a?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":f,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(no,{size:12,strokeWidth:3,className:`session-tree-chevron${f?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(ns,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!f&&(0,r.jsx)(nL,{running:t.running,awaiting:t.awaiting,unread:t.unread,t:p})]}),(0,r.jsxs)("span",{className:"session-tree-group-actions",children:[(0,r.jsx)("button",{type:"button",className:"session-tree-group-action","aria-label":p("sidebar.newSessionInProject",{name:h.name}),title:p("sidebar.newSessionInProject",{name:h.name}),onClick:e=>{e.stopPropagation(),u.current.onGroupNew(h)},children:(0,r.jsx)(nt,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${l?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":l,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(nn,{size:13})})]})]})}),nP=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:l}=e,{t:o}=(0,e0.s)(),a=nM(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>s.current.onTogglePinned(),children:[(0,r.jsx)(no,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,r.jsx)("span",{className:"session-tree-pinned-label",children:o("sidebar.pinned")}),(0,r.jsxs)("span",{className:"session-tree-pinned-count",children:["\xb7 ",t.count]}),t.collapsed&&t.running>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-running",role:"img",title:o("sidebar.agentRunning"),"aria-label":`${o("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.awaiting>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-awaiting",role:"img",title:o("sidebar.agentAwaitingInput"),"aria-label":`${o("sidebar.agentAwaitingInput")} (${t.awaiting})`}),t.collapsed&&t.unread>0&&(0,r.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:o("sidebar.newSessionActivity"),"aria-label":`${o("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?P:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:a,"data-row-key":t.key,children:[t.hidden>0&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>l(t.key,e,"more",n.currentTarget),children:o("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>l(t.key,e,"less",n.currentTarget),children:o("sidebar.showLess")})]})}case"group-empty":return(0,r.jsx)("div",{className:"session-tree-row session-tree-group-empty",style:a,"data-row-key":t.key,children:o("sidebar.noLiveSessions")});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:e=>s.current.onOpenOtherProject(e.currentTarget),children:[(0,r.jsx)(nv,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:o("sidebar.openOtherProject")})]})});case"footer-archived":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,r.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>s.current.onOpenArchive(),children:[(0,r.jsx)(nr,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:o("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(no,{size:10,className:"session-tree-footer-chevron"})]})})}}),nW=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:l}=e,{t:o}=(0,e0.s)(),{project:a,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",a.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:nM(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:a.root,onClick:e=>l.current.onToggleArchiveGroup?.(a.key,e.altKey),children:[(0,r.jsx)(no,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:a.name}),(0,r.jsxs)("span",{className:"session-tree-archive-group-count",children:["\xb7 ",t.count]})]}),(0,r.jsx)("span",{className:"session-tree-group-actions",children:(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${s?" is-active":""}`,"aria-label":o("sidebar.archivedProjectActions",{name:a.name}),title:o("sidebar.archivedProjectActions",{name:a.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),l.current.onArchiveGroupMenu?.(a,e.currentTarget)},children:(0,r.jsx)(nn,{size:13})})})]})}),nO="[data-sidebar-menu-filter]",nF="[data-sidebar-menu-autofocus]",nD="button, input, textarea, select, a[href], [tabindex]";function nB(e){return i.Children.toArray(e).length>0}function nH(e){return"item"===e.type&&void 0!==e.checked}function n_(e){return e.getClientRects().length>0}function nU(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&n_(e)}function nq(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(nU)}function nK(e){let t=Array.from(e.querySelectorAll(nF)).find(nU);if(t)return t;let n=nq(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(nD)).filter(e=>e.tabIndex>=0&&nU(e))[0]??null}function nV(e){e.stopPropagation()}let nZ={onClick:nV,onDoubleClick:nV,onMouseDown:nV,onMouseUp:nV,onPointerDown:nV,onPointerUp:nV,onKeyDown:nV,onKeyUp:nV,onFocus:nV,onBlur:nV,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function nJ(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function nY(e){let{item:t,onActivate:n}=e,i=void 0!==t.checked,s=["sidebar-menu-item",i?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),l=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),o=null;t.disabled&&t.disabledReason?o=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?o=(0,r.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(o=(0,r.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let a=(0,r.jsxs)("button",{type:"button",role:i?"menuitemradio":"menuitem","aria-checked":i?t.checked:void 0,"aria-disabled":!!t.disabled||void 0,"aria-keyshortcuts":t.shortcut&&!t.disabled?t.shortcut.toUpperCase():void 0,tabIndex:-1,title:t.title,"data-sidebar-menu-item":"",className:s,onClick:e=>n(t,e.shiftKey),onKeyDown:nJ(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(nm,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:l,children:t.path?(0,r.jsx)("span",{children:t.label}):t.label}),t.badge,o]}),d=t.secondary;return d?(0,r.jsxs)("div",{className:i?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[a,(0,r.jsx)("button",{type:"button",role:"menuitem","aria-label":d.label,"aria-disabled":!!d.disabled||void 0,tabIndex:-1,title:d.label,"data-sidebar-menu-item":"",className:d.danger?"sidebar-menu-secondary is-danger":"sidebar-menu-secondary",onClick:e=>n(d,e.shiftKey),onKeyDown:nJ(d,n),children:d.icon})]}):a}function nG(e){var t;let n,{sheet:i,ariaLabel:s,title:l,items:o,filter:a,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:f=208,classic:m=!1,footer:g,surfaceRef:x,onActivate:v,onClose:b}=e,y=nB(u),w=!y&&nB(g),j=void 0!==a&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(nH).length>=t}(o,a.minChoices),k=j?(t=o??[],(n=d.trim().toLowerCase())?t.filter(e=>"item"!==e.type||void 0===e.checked||[e.label,e.note,e.title].some(e=>e?.toLowerCase().includes(n))):[...t]):o??[],S=k.map(e=>"separator"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-separator",role:"separator"},e.id):"header"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-header",role:"presentation",children:e.label},e.id):"custom"===e.type?(0,r.jsx)("div",{className:"sidebar-menu-custom",role:"none",children:e.content},e.id):(0,r.jsx)(nY,{item:e,onActivate:v},e.id)),C=y?u:j||w?(0,r.jsxs)(r.Fragment,{children:[j&&(0,r.jsx)("div",{className:"sidebar-menu-filter",children:(0,r.jsx)("input",{className:"sidebar-menu-filter-input",value:d,placeholder:a.placeholder,"aria-label":a.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":i?void 0:"",onChange:e=>c?.(e.target.value)})}),j&&(0,r.jsx)("div",{role:"status",children:d.trim()&&!k.some(nH)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:a.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),w&&g]}):S,N=y||j||w?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...nZ,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>b("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[l?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:l}):null,(0,r.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?s:void 0,children:C}),(0,r.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>b("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:m?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:f},...nZ,children:C})}function nX(e){let{open:t,anchor:n,sheet:s,ariaLabel:l,title:o,items:a,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:f,width:m,classic:g=!1,footer:x,focusKey:v=""}=e,[b,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(""),k=(0,i.useRef)(w);k.current=w;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(a);N.current=a;let $=(0,i.useRef)(f??null);$.current=f??null;let E=(0,i.useRef)(n);E.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let I=t&&null!==b&&(s||null!==n),M=nB(c),T=n?JSON.stringify(n):"",R=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||C.current("select")},A=(0,i.useRef)(R);A.current=R,(0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||s||!e)return;let t=window.visualViewport,n=()=>{let n=E.current;if(!n)return;let r=e.getBoundingClientRect(),{left:i,top:s}=function(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,l=n.left+s,o=n.top+s,a=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>a&&e.x-t.width>=l?e.x-t.width:e.x,i=e.y+t.height>d&&e.y-t.height>=o?e.y-t.height:e.y;else{let{rect:n}=e;r="end"===e.align?n.right-t.width:n.left;let s=n.bottom+4,l=n.top-4-t.height;i=s+t.height>d&&l>=o?l:s}return{left:Math.max(l,Math.min(r,a-t.width)),top:Math.max(o,Math.min(i,d-t.height))}}(n,{width:r.width,height:r.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});e.style.left=`${i}px`,e.style.top=`${s}px`};n();let r="u"<typeof ResizeObserver?null:new ResizeObserver(n);return r?.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r?.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[I,s,T,M]),(0,i.useEffect)(()=>{j("")},[I,M]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?nK(e):Array.from(e.querySelectorAll(nF)).filter(e=>!e.matches(nO)&&nU(e))[0]??nK(e))?.focus({preventScroll:!0})},[I,s,M,v]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!I||!e)return;let t=$.current;return()=>{let n=document.activeElement;if(n&&n!==document.body&&!e.contains(n))return;let r=function(e){if(!e||!e.isConnected)return null;if(n_(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(nD)))if(e.tabIndex>=0&&nU(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&n_(t)&&t.focus({preventScroll:!0}))}},[I,s]),(0,i.useEffect)(()=>{if(!I)return;let e=e=>{let t=S.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(nO);if(n&&k.current){j(""),n.focus({preventScroll:!0});return}C.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,l;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(nD)).filter(e=>e!==n&&e.tabIndex>=0&&nU(e)),l=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&l)!=0))||C.current("outside");return}let l=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(nO);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!l)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=nq(t);if(0===i.length)return;e.preventDefault(),e.stopPropagation();let s=n?i.indexOf(n):-1;r="Home"===e.key?0:"End"===e.key?i.length-1:"ArrowDown"===e.key?s<0?0:(s+1)%i.length:s<0?i.length-1:(s-1+i.length)%i.length,i[r].focus({preventScroll:!1});return}if(1!==e.key.length||e.ctrlKey||e.metaKey||e.altKey)return;let o=function(e,t){if(!e||1!==t.length)return null;let n=t.toLowerCase();for(let t of e)if("item"===t.type&&!t.disabled&&t.shortcut&&t.shortcut.toLowerCase()===n)return t;return null}(N.current,e.key);o&&!M&&(e.preventDefault(),e.stopPropagation(),A.current(o,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[I,M]),(0,i.useEffect)(()=>{if(!I||s)return;let e=e=>{let t=S.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=$.current;r&&n&&0===e.button&&r.contains(n)&&function(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return;let r=0,i=()=>{t.removeEventListener("click",s,!0),n.clearTimeout(r)};function s(t){i(),t.target instanceof Node&&e.contains(t.target)&&(t.preventDefault(),t.stopPropagation())}t.addEventListener("click",s,!0),r=n.setTimeout(i,1e3)}(r),C.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[I,s]),I&&b)?(0,tc.createPortal)((0,r.jsx)(nG,{sheet:s,ariaLabel:l,title:o,items:a,filter:d,filterQuery:w,onFilterQueryChange:j,cancelLabel:u,focusCancel:p,width:m,classic:g,footer:x,surfaceRef:S,onActivate:(e,t)=>A.current(e,t),onClose:e=>C.current(e),children:c}),b):null}function nQ(e){let{heading:t,busy:n,error:s,showCancel:l,onCreate:o,onCancel:a}=e,{t:d}=(0,e0.s)(),[c,u]=(0,i.useState)(""),p=c.trim(),h=()=>{p&&!n&&o(p)};return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,r.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:c,readOnly:n,placeholder:d("sidebar.branchName"),"aria-label":d("sidebar.branchName"),onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:d(n?"sidebar.creating":"sidebar.create")}),l&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function n0(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function n1(e){return e.branch??U(e.path)}function n2(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:l,onForce:o,onCancel:a}=e,{t:d}=(0,e0.s)();return(0,r.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,r.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,r.jsx)("div",{className:"sidebar-worktree-message",children:d("sidebar.forceRemoveCheckout")}),(n||l)&&(0,r.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:i,onClick:o,children:d("sidebar.force")}),l&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:a,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function n4(e){let{busy:t,onForce:n,onCancel:s}=e,{t:l}=(0,e0.s)(),o=(0,i.useId)();return(0,r.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,r.jsx)("span",{id:o,className:"sidebar-worktree-confirm-text",title:l("sidebar.forceRemoveCheckout"),children:l("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":o,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:l("sidebar.force")}),(0,r.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:s,children:l("sidebar.cancel")})]})}function n8(e){let t,n,{layout:s,context:l,mobile:o,label:a,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:f,onPick:m,onUseDefaultDirectory:g,onOpenFolder:x,onRefreshWorktrees:v,onCreateWorktree:b,onRemoveWorktree:y}=e,{t:w}=(0,e0.s)(),[j,k]=(0,i.useState)(null),S=(0,i.useRef)(j);S.current=j;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),$=(0,i.useRef)(null),E=(0,i.useRef)(!1),I=(0,i.useRef)(m);I.current=m;let M="inline"!==s,T=!M,R=!o,{project:A,worktrees:L}=l,z=(t=l.worktrees??[]).find(e=>e.path===l.currentWorktreePath)??t.find(e=>e.isMain)??null,P=T&&A?e$(eC(l)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>(E.current=!0,()=>{E.current=!1}),[]);let W=()=>(C.current+=1,C.current),O=()=>k(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(M?220:"project"===e?260:240,Math.round(n.width));k({id:W(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===s&&"worktree"===e?"end":"start"},opener:t,width:r,body:null,removing:!1}),"worktree"===e&&v()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(f,()=>({button:e=>("worktree"===e?$:N).current,openMenu:e=>{let t=("worktree"===e?$:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{k(n=>n?.id===e?t(n):n)},H=e=>{let t=W();k(n=>n?.kind==="worktree"?{...n,id:t,body:e,removing:!1}:n)},_=async e=>{let t,n=S.current;if(!n||n.body?.kind!=="create"||!A)return;let{id:r}=n,i=(e,t)=>{B(r,n=>({...n,body:{kind:"create",busy:e,error:t}}))};i(!0,null);try{t=await b(A,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}E.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(k(null),I.current({cwd:t.path,projectKey:A.key,projectRoot:A.root},"worktree")))},q=async(e,t)=>{let n,r=S.current;if(!r||!A||!y)return;let{id:i}=r;B(i,e=>({...e,removing:!0,body:e.body?.kind==="remove"?{...e.body,busy:!0,error:null}:e.body}));try{n=await y(A,e.path,t)}catch(e){n={error:e instanceof Error?e.message:String(e)}}E.current&&B(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},K=()=>[...(L??[]).map(e=>R&&V?.kind==="remove"&&V.dirty&&V.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(n4,{busy:V.busy,onForce:()=>{q(e,!0)},onCancel:()=>H(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??n0(e.path,c):n1(e),mono:R,path:R,note:e.isMain?w("sidebar.main"):void 0,title:e.path,checked:e.path===z?.path,secondary:y&&!e.isMain?{label:w("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(nu,{size:12}),danger:!0,disabled:j?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),q(e,!1)}}:void 0,onSelect:()=>{A&&e.path!==z?.path&&m({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&V?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:w("sidebar.newWorktree"),icon:(0,r.jsx)(nt,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),H({kind:"create",busy:!1,error:null})}}]],V=j?.kind==="worktree"?j.body:null,Z="",J=null,Y=null;if(R&&j?.kind==="worktree")Z=w("sidebar.switchWorktree"),n=K(),V?.kind==="create"?Y=(0,r.jsx)(nQ,{heading:null,busy:V.busy,error:V.error,showCancel:!0,onCreate:e=>{_(e)},onCancel:()=>H(null)}):V?.kind==="remove"&&V.error&&(Y=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:V.error}));else if(V?.kind==="create")Z=h,J=(0,r.jsx)(nQ,{heading:o?null:Z,busy:V.busy,error:V.error,showCancel:!o,onCreate:e=>{_(e)},onCancel:O});else if(V?.kind==="remove")Z=w("sidebar.removeWorktreeHeading",{name:n1(V.worktree)}),J=(0,r.jsx)(n2,{heading:o?null:Z,dirty:V.dirty,busy:V.busy,error:V.error,showCancel:!o,onForce:()=>{q(V.worktree,!0)},onCancel:O});else if(j?.kind==="project"){let e,t;Z=w("workspace.project"),t=(e=e$(eC(l)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),l=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:l?n0(t.root,c):n,note:l?void 0:i??void 0,mono:R,path:l,title:t.root,checked:t.key===A?.key,badge:s?(0,r.jsx)(nL,{running:s.running,unread:s.unread,t:w}):void 0,onSelect:()=>{t.key===A?.key&&L||m({cwd:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:w("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(nx,{size:13}),onSelect:()=>g()},{type:"item",id:"open-folder",label:w(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(nt,{size:13}):(0,r.jsx)(nv,{size:13}),onSelect:()=>x(j?.opener??null)}]}else j?.kind==="worktree"&&(Z=w("sidebar.switchWorktree"),n=K());let G=j?.kind==="project"?{placeholder:w("sidebar.filterProjects"),emptyLabel:w("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:w("sidebar.filterWorktrees"),emptyLabel:w("sidebar.noMatchingWorktrees")},X=M&&void 0!==u&&[...u].some(e=>{let[t,{running:n,unread:r}]=e;return t!==A?.key&&(n>0||r>0)});return(0,r.jsxs)("div",{className:`project-picker is-${s}`,role:"group","aria-label":a,children:[(0,r.jsxs)("button",{ref:N,type:"button",className:A?"project-picker-button is-project":"project-picker-button is-project is-empty",title:A?.root??"","aria-haspopup":"menu","aria-expanded":j?.kind==="project",onClick:e=>F("project",e.currentTarget),children:[T&&(0,r.jsx)(nx,{size:12,className:"project-picker-icon"}),T&&A?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&P?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:P.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:A.alias??P?.name??U(A.root)})]}):A?.alias!==void 0?(0,r.jsx)("span",{className:"project-picker-label is-alias",children:A.alias}):A?(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:n0(A.root,c)})}):(0,r.jsx)("span",{className:"project-picker-label",children:d}),X&&(0,r.jsx)("span",{className:"project-picker-activity",role:"img",title:w("sidebar.newActivity"),"aria-label":w("sidebar.newActivity")}),T&&(0,r.jsx)(no,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,r.jsxs)("button",{ref:$,type:"button",className:"project-picker-button",title:z?w("sidebar.worktreePath",{path:z.path}):w("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":j?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(na,{size:11,className:z&&!z.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:z?z.branch??n0(z.path,c):"…"})}),z?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:w("sidebar.main")}),M&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(no,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&M&&p&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:p.title,className:"project-picker-button is-inactive",children:[(0,r.jsx)(na,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(nX,{open:null!==j,anchor:j?.anchor??null,sheet:o,ariaLabel:Z,title:Z,items:n,filter:G,cancelLabel:w("sidebar.cancel"),focusCancel:V?.kind==="remove",onClose:O,returnFocusTo:j?.opener??null,width:j?.width,classic:R,footer:Y,focusKey:V?`${V.kind}:${"remove"===V.kind&&V.dirty}`:"list",children:J})]})}function n3(e){let{open:t,query:n,children:s,selectedSessionId:l,onSelectSession:o,archivedSessionIds:a}=e,{t:d,locale:c}=(0,e0.s)(),[u,p]=(0,i.useState)({query:""}),h=n.trim(),f=u.query===h?u.response:void 0,m=u.query===h&&u.failed;return(0,i.useEffect)(()=>{if(!t||!h)return;let e=new AbortController;p({query:h});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:h})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||p({query:h,response:n})}catch{e.signal.aborted||p({query:h,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,h]),t&&h?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!f&&!m,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:m?d("sidebar.sessionSearchFailed"):f?0===f.results.length?d("sidebar.sessionSearchEmpty"):d("sidebar.sessionSearchCount",{count:f.results.length}):d("sidebar.sessionSearching")}),f?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:d("sidebar.sessionSearchPartial")}),f?.results.map(e=>{let{session:t,entryId:n,blockIndex:i,titleMatch:s,before:u,match:p,after:h}=e;return(0,r.jsxs)("button",{type:"button",onClick:()=>o(t,n,i),"aria-current":t.id===l?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${t.id===l?"bg-bg-selected":""}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-text",children:s?(0,r.jsxs)(r.Fragment,{children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]}):t.name||t.firstMessage}),a?.has(t.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:d("sidebar.archived")})]}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:t.cwd,children:t.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,t8.fw)(t.modified,c)})]}),!s&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[u,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:p}),h]})]},t.id)})]}):s}function n5(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:l}=e,o=(0,i.useRef)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=a||c;return(0,i.useLayoutEffect)(()=>{let e=o.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&d(!0)},[]),(0,i.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>l.current(),s);return()=>window.clearTimeout(e)},[p,s,l]),(0,r.jsxs)("div",{ref:o,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&d(!0)},onPointerLeave:()=>d(!1),onFocus:()=>u(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||u(!1)},children:[t.tail?(0,r.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,r.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,r.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,r.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,r.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{l.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>l.current(),children:(0,r.jsx)(ng,{size:12})})]})}function n6(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:l=1e4}=e,o=(0,i.useRef)(n);return o.current=n,(0,r.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,r.jsx)(n5,{toast:t,dismissLabel:s,durationMs:l,onDismissRef:o},t.id):null})}let n9={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function n7(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:l,expanded:o,controls:a,done:d,className:c,children:u}=e;return(0,r.jsx)("button",{ref:t,type:"button",onClick:n,disabled:s,title:i,"aria-label":i,"aria-pressed":l,"aria-expanded":o,"aria-controls":a,className:`sidebar-tool-button${l||o?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let re="pi-web:unread-session-ids",rt="pi-web:last-custom-cwd",rn={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename",fork:"sidebar.fork","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function rr(){try{return window.localStorage.getItem(rt)??""}catch{return""}}function ri(e){if(!e)return new Set;try{let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e))}catch{}return new Set}function rs(e,t){let n=new Set(t);if(n.size!==e.size)return n;for(let t of n)if(!e.has(t))return n;return e}function rl(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function ro(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):eI(document,e)}function ra(e,t){let n=e.getBoundingClientRect();return{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:t}}function rd(e){var t,n,s;let l,a,c,u,p,h,g,v,{selectedSessionId:b,onSelectSession:y,onNewSession:w,controlRef:k,onNewSessionContextChange:z,initialSessionId:B,initialSessionLinked:K,skipInitialProjectSelection:ei,onInitialRestoreDone:ew,refreshKey:ej,onSessionDeleted:eC,selectedCwd:e$,onCwdChange:eE,onOpenFile:eM,onOpenTerminal:eT,explorerRefreshKey:eR,onExplorerRefresh:eA,onAtMention:eL,onAtMentions:ez,onBackgroundTaskDone:eP,onRunningSessionIdsChange:eW,onSessionsChange:eO}=e,{t:eF}=(0,e0.s)(),eB=te(),[eH,e_]=(0,i.useState)([]),eU=(0,i.useRef)(null),eq=(0,i.useRef)(0),[eK,eV]=(0,i.useState)(!0),[eZ,eJ]=(0,i.useState)(!1),[eY,eG]=(0,i.useState)(null),[eX,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(""),[e8,e3]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(rr),[e9,e7]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(!1),[tl,tc]=(0,i.useState)(null),tu=(0,i.useRef)(null),[tp,th]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null);tg.current??=new Set(ev());let[tx,tv]=(0,i.useState)(0),[tb,tj]=(0,i.useState)(!1),[tk,tS]=(0,i.useState)(!1),[tC,tN]=(0,i.useState)(!1),[t$,tE]=(0,i.useState)(""),[tI,tM]=(0,i.useState)(0),[tT,tR]=(0,i.useState)(!0),[tA,tL]=(0,i.useState)(!1),[tz,tP]=(0,i.useState)(!1),[tW,tO]=(0,i.useState)(null),[tF,tD]=(0,i.useState)(null),[tB,tH]=(0,i.useState)(()=>new Set),[t_,tU]=(0,i.useState)(()=>new Set),[tq,tK]=(0,i.useState)(()=>new Set),[tV,tZ]=(0,i.useState)(()=>(function(){try{return ri(window.localStorage.getItem(re))}catch{return new Set}})()),tJ=(0,i.useRef)(new Set),tY=(0,i.useRef)(new Set),tG=(0,i.useRef)(new Set),tX=(0,i.useRef)(new Set),tQ=(0,i.useRef)(!1),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t3=eQ(),t5=!eB&&"below"===t3,[t6,t9]=(0,i.useState)("sessions"),[t7,ne]=(0,i.useState)(!1),na=(0,i.useRef)(null),ng=(0,i.useRef)(null),nv=(0,i.useRef)(null),nN=(0,i.useRef)(null),nE=(0,i.useRef)(new WeakMap),[nM,nT]=(0,i.useState)({}),[nR,nA]=(0,i.useState)(()=>new Set),[nL,nz]=(0,i.useState)({}),[nP,nW]=(0,i.useState)(!1),[nO,nF]=(0,i.useState)([]),[nD,nB]=(0,i.useState)(!1),{phase:nH,start:n_,end:nU}=td(),{phase:nq,start:nK,end:nV}=td(),nZ=(0,i.useRef)(t7);nZ.current=t7;let nJ=(0,i.useRef)(nD);nJ.current=nD;let nY=(0,i.useCallback)(e=>{e!==nJ.current&&nK(e?"in":"out"),nB(e)},[nK]),nG=(l=t7&&"out"===nH,a=!t7&&"in"===nH,{bodyHidden:t7&&!l,bodyInert:l,moving:l||a,open:!t7&&!a}),nQ=(c=nD&&"in"===nq,u=!nD&&"out"===nq,{mainHidden:nD&&!c,mainInert:c,archiveMounted:nD||u,archiveInert:u,archiveClass:c?"is-entering":u?"is-leaving":null}),[n0,n1]=(0,i.useState)(null),[n2,n4]=(0,i.useState)(null),[n5,rd]=(0,i.useState)(null),[rc,ru]=(0,i.useState)(null),[rp,rh]=(0,i.useState)(null),rf=(0,i.useRef)(0),rm=(0,i.useCallback)(e=>{rh(t=>t?.id===e?null:t)},[]),[rg,rx]=(0,i.useState)(null),rv=(0,i.useCallback)(e=>{rx(t=>t?.id===e?null:t)},[]),rb=(0,i.useRef)(b);rb.current=b;let[ry,rw]=(0,i.useState)(null),rj=(0,i.useRef)(0),rk=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rj.current+=1,rw({id:rj.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rS,rC]=(0,i.useState)(0),rN=(0,i.useRef)(0),r$=(0,i.useRef)(null),[rE,rI]=(0,i.useState)(0),rM=(0,i.useRef)(null),rT=(0,i.useRef)(null),rR=(0,i.useRef)(null),rA=(0,i.useRef)(null),[rL,rz]=(0,i.useState)(0),rP=(0,i.useCallback)(e=>{rA.current=e,rz(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=rA.current;rA.current=null,e&&eI(document,e())},[rL]);let{state:rW,loaded:rO,synced:rF,error:rD,apply:rB,snapshot:rH,noteRevision:r_}=function(){let[e,t]=(0,i.useState)(M),[n,r]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),[o,a]=(0,i.useState)(null),d=(0,i.useRef)(e),c=(0,i.useRef)(e),u=(0,i.useRef)([]),p=(0,i.useRef)(Promise.resolve()),h=(0,i.useRef)(0),f=(0,i.useRef)(null),m=(0,i.useCallback)(()=>{let e=d.current;for(let{request:t,now:n}of u.current)e=function(e,t,n){var r,i,s,l;let o=function(e){let t={};for(let[n,r]of Object.entries(e.sessions))t[n]={...r};let n={};for(let[t,r]of Object.entries(e.projects))n[t]={...r};let r={...e,sessions:t,projects:n};return e.projectOrder&&(r.projectOrder=[...e.projectOrder]),e.projectNames&&(r.projectNames={...e.projectNames}),r}(e),a=!1;switch(t.action){case"set":for(let e of t.ids){let r=x(o.sessions,e)?o.sessions[e]:void 0;T(o.sessions,e,function(e,t,n){let r={...e};return"pinned"in t?t.pinned?(void 0===r.pinnedAt||void 0!==r.archivedAt)&&(r.pinnedAt=n,delete r.archivedAt):delete r.pinnedAt:t.archived?(r.archivedAt=n,delete r.pinnedAt):delete r.archivedAt,r}(r,t,n))&&(a=!0)}break;case"restore":for(let e of t.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),T(o.sessions,e.id,t)&&(a=!0)}break;case"pin-project":{let{projectKey:e,root:l}=t,d=x(o.projects,e)?o.projects[e]:void 0;if(t.pinned?d?.root!==l&&(o.projects[e]={pinnedAt:n,root:l},a=!0):d&&(delete o.projects[e],a=!0),(t.pinned?void 0===d:void 0!==d)&&o.projectOrder){let n,l,d=(r=o.projectOrder,i=o.projects,s=t.pinned,l=r.filter(t=>t!==e),s?(n=0,l.forEach((e,t)=>{x(i,e)&&(n=t+1)})):(n=l.findIndex(e=>!x(i,e)))<0&&(n=l.length),l.splice(n,0,e),l);N(d.length,C(d))&&R(o,d)&&(a=!0)}break}case"add-projects":R(o,function(e,t){let n=A(e,t),r=e.length,i=C(e),s=n.length;for(;s>0;){let e=S(n[s-1]);if(!N(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(o.projectOrder??[],t.keys))&&(a=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=o.projectOrder??[];R(o,function(e,t){let n=e.length,r=C(e);if(N(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!N(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=S(e[s]));let s=e.filter((e,t)=>!i.has(t));return N(n,r)?s:$(s)}((l=[...A(c,d),...c],(e=l.filter(e=>e!==r)).includes(i)||e.unshift(i),n=e.indexOf(i),e.splice("before"===s?n:n+1,0,r),e),new Set([r,i,...d])))&&(a=!0);break}case"rename-project":{let e=j(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((x(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!I(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=E(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(o,t.projectKey,e)&&(a=!0)}}return{state:o,changed:a}}(e,t,n).state;c.current=e,t(e)},[]),g=(0,i.useCallback)(async e=>{let t=++h.current;f.current=t;try{let n=await fetch(ts,{cache:"no-store"}),i=await ta(n);if(t!==h.current)return;d.current=i,m(),e||a(null),r(!0),l(!0)}catch(e){if(t!==h.current)return;a(to(e)),r(!0)}finally{f.current===t&&(f.current=null)}},[m]),v=(0,i.useCallback)(()=>g(!1),[g]),b=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===d.current.revision||(null===f.current||f.current!==h.current)&&v()},[v]),y=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],m();let n=async()=>{let n=!1;try{let t=await fetch(ts,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await ta(t);h.current++,d.current=i,a(null),r(!0),l(!0),n=!0}catch(e){a(to(e))}return u.current=u.current.filter(e=>e!==t),m(),n||await g(!0),n},i=p.current.then(n,n);return p.current=i,i},[g,m]),w=(0,i.useCallback)(e=>(function(e,t){let n=new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=x(e.sessions,i)?e.sessions[i]:void 0;r.push({id:i,pinnedAt:t?.pinnedAt??null,archivedAt:t?.archivedAt??null})}return r})(c.current,e),[]);return(0,i.useEffect)(()=>{v()},[v]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:o,refresh:v,noteRevision:b,apply:y,snapshot:w}),[e,n,s,o,v,b,y,w])}(),rU=(0,i.useMemo)(()=>new Set(Object.keys(rW.projects)),[rW]),rq=(0,i.useMemo)(()=>new Set(Object.entries(rW.sessions).filter(e=>{let[,t]=e;return null!=t.pinnedAt}).map(e=>{let[t]=e;return t})),[rW]),rK=(0,i.useRef)(null),rV=(0,i.useRef)(null);ti(rV);let rZ=(0,i.useRef)(null),rJ=(0,i.useRef)(null),rY=(0,i.useRef)(320),rG=(0,i.useCallback)(()=>{let e=rJ.current,t=rK.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),rX=(0,i.useCallback)(()=>Math.round(.45*rG()),[rG]),rQ=(0,i.useCallback)(()=>rG()-120,[rG]),r0=tr({ariaLabel:eF("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:rX,getMaxWidth:rQ,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:rY}),r1=r0.panelRef,r2=(0,i.useCallback)(e=>{rJ.current=e,r1.current=e},[r1]),r4=r0.reclampWidth;(0,i.useEffect)(()=>{let e=rJ.current;if(!t5||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>r4());return t.observe(e),()=>t.disconnect()},[r4,t5]),(0,i.useEffect)(()=>{let e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!e)return"sessions";try{return"files"===e.getItem(es)?"files":"sessions"}catch{return"sessions"}}();"sessions"!==e&&t9(e);let t=function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!t)return{};try{let e=t.getItem(el);if(null!==e)return em(JSON.parse(e))}catch{return{}}try{let n=t.getItem(eo);if(null===n)return{};e=em(JSON.parse(n))}catch{e={}}let n=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return!t}));return eg(n,t),n}();Object.keys(t).length>0&&nT(t),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!e)return!1;try{return"true"===e.getItem(ed)}catch{return!1}}()&&nW(!0);let n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!e)return[];try{let t=e.getItem(ea),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e&&""!==e);return[...new Set(r)].slice(-300)}catch{return[]}}();n.length>0&&nF(n),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!e)return!1;try{return"true"===e.getItem(eu)}catch{return!1}}()&&ne(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(!e)return!1;try{return"true"===e.getItem(ec)}catch{return!1}}()&&tL(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ef();if(e)for(let t of eh)try{e.removeItem?.(t)}catch{}}()},[]);let r8=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=++eq.current;try{e&&eV(!0);let i=await fetch(n?"/api/sessions?summary=1":t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(r!==eq.current)return;eU.current=s.sessionListVersion,e_(s.sessions),n||eJ(!0),tQ.current||(tG.current=new Set(s.completionNotificationSuppressedSessionIds??[]),tH(e=>rs(e,s.runningSessionIds??[])),tU(e=>rs(e,s.awaitingInputSessionIds??[])));let l=new Set(s.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));tZ(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>l.has(e)));return t.size===e.size?e:t}),eG(null)}catch(e){r===eq.current&&eG(String(e))}finally{r===eq.current&&eV(!1)}},[]),r3=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!r3.current;r3.current=!0;let t=!0;return e?r8(!0,!1,!0).then(()=>{t&&(t1.current=setTimeout(()=>{t1.current=null,t&&r8(!1,!0)},750))}):r8(),()=>{t=!1,t1.current&&(clearTimeout(t1.current),t1.current=null)}},[r8,ej]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&tO(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{tD(null)},[eX,e$]);let r5=(0,i.useCallback)(async()=>{let e=eX??e$;if(!e)return!1;try{let t=await fetch("/api/open-in-explorer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})});if(t.ok)return tD(null),!1;let n=await t.json().catch(()=>({}));tD(n.error??`HTTP ${t.status}`)}catch(e){tD(e instanceof Error?e.message:String(e))}return!0},[eX,e$]),r6=eF(tW?.platform==="darwin"?"sidebar.openInFinder":tW?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),r9=tW?.supported===!1,r7=tF?eF(n9[tF]??tF):null;(0,i.useEffect)(()=>{try{0===tV.size?window.localStorage.removeItem(re):window.localStorage.setItem(re,JSON.stringify([...tV]))}catch{}},[tV]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===re)&&tZ(t=>rs(t,[...ri(e.newValue)]))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;let l=Date.now(),o=null,a="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;a="ok";let r=await t.json();if(o=Date.now(),e||n!==s)return;tQ.current=!0,tG.current=new Set(r.completionNotificationSuppressedSessionIds??[]),tH(e=>rs(e,r.runningSessionIds??[])),tU(e=>rs(e,r.awaitingInputSessionIds??[])),tK(e=>rs(e,r.subagentsActiveSessionIds??[])),r_(r.sessionUiStateRevision),r.sessionListVersion!==eU.current&&await r8()}catch{a=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=Date.now();eD.count+=1,"error"===t&&(eD.failures+=1),eD.last={at:i,durationMs:Math.max(0,(r??i)-e),outcome:t,httpStatus:n}}(l,a,d,o)}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[r8,r_]),(0,i.useEffect)(()=>{eW?.(tB)},[eW,tB]),(0,i.useEffect)(()=>{eO?.(eH)},[eH,eO]),(0,i.useEffect)(()=>{let e=tJ.current,t=[...e].filter(e=>!tB.has(e)&&e!==b),n=new Set([...tB,...tq]),r=[...tY.current].filter(e=>!n.has(e)&&e!==b),i=new Set(eH.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),s=r.filter(e=>!tX.current.has(e)&&!i.has(e)),l=[...tB].filter(t=>!e.has(t));(s.length>0||l.length>0)&&tZ(e=>{let t=new Set(e);return tB.forEach(e=>t.delete(e)),s.forEach(e=>t.add(e)),t});let o=l.some(e=>!eH.some(t=>t.id===e));(t.length>0||o)&&r8(),s.length>0&&eP?.(),tJ.current=tB,tY.current=n;let a=tX.current;tX.current=new Set([...n].filter(e=>tG.current.has(e)||i.has(e)||a.has(e)&&!tB.has(e)))},[tB,tq,b,eH,r8,eP]),(0,i.useEffect)(()=>{b&&tZ(e=>{if(!e.has(b))return e;let t=new Set(e);return t.delete(b),t})},[b]),(0,i.useEffect)(()=>{void 0!==eR&&tv(e=>e+1)},[eR]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&e4(e.home)}).catch(()=>{})},[]);let ie=(0,i.useRef)(!1),it=(0,i.useCallback)(e=>e?function(e,t){let{validated:n,listing:r,sessions:i}=t;if(n?.cwd===e)return{root:n.root,key:n.key};if(r?.forCwd===e||r?.isTopLevel&&r.worktrees.some(t=>t.path===e))return{root:r.projectRoot,key:r.projectKey};let s=i.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return s?{root:s.projectRoot??s.cwd,key:f(s)}:{root:e,key:e}}(e,{validated:tl,listing:tp,sessions:eH}):null,[tl,tp,eH]),ir=(0,i.useMemo)(()=>it(eX),[it,eX]),ii=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=it(eX),t=ii.current;(t?.cwd!==eX||t.key!==(e?.key??null))&&(ii.current={cwd:eX,key:e?.key??null},eE?.(eX,e?.root??null,e?.key??null))},[eX,eE,it]);let is=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!e$){is.current=null;return}e$!==is.current&&(is.current=e$,e1(e$))},[e$]);let[il,io]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!eX){th(null),tm(null);return}let e=!1;return tm(eX),fetch(`/api/worktrees?cwd=${encodeURIComponent(eX)}`).then(e=>e.json()).then(t=>{if(!e){if(tm(null),t.error||!t.projectRoot)return void th(null);t.isGit?tg.current?.delete(eX):tg.current?.add(eX),function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ef();if(!n||!e)return;let r=ev(n),i=r.indexOf(e);if(t?-1===i:-1!==i&&i===r.length-1)return;let s=r.filter(t=>t!==e);t||s.push(e);try{n.setItem(ep,JSON.stringify(s.slice(-50)))}catch{}}(eX,!!t.isGit),th({forCwd:eX,projectRoot:t.projectRoot,projectKey:t.projectKey??t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,currentWorktreePath:t.currentWorktreePath??null,worktrees:t.worktrees??[]})}}).catch(()=>{e||(tm(null),th(null))}),()=>{e=!0}},[eX,il,ej]),(0,i.useEffect)(()=>{if(0!==eH.length&&!ei&&null===eX){if(B&&!ie.current){ie.current=!0;let e=eH.find(e=>e.id===B);if(e){e1(e.cwd),y(e,!0);return}ew?.(),K&&rk(eF("sidebar.sessionNotFound"))}let e=m(eH,rU);e.length>0&&e1(e[0].root)}},[eH,rU,eX,B,K,ei,y,ew,rk,eF]);let ia=tp?tp.worktrees.find(e=>e.path===eX)??(tp.forCwd===eX&&tp.currentWorktreePath?tp.worktrees.find(e=>e.path===tp.currentWorktreePath):void 0)??tp.worktrees.find(e=>e.isMain):void 0,id=ia?.path??null,ic=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=e8}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??e5).trim();if(r&&!tt){tn(!0),e7(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r})}),s=await e.json().catch(()=>({}));if(!e.ok||s.error||!s.cwd||!s.projectRoot||!s.projectKey)return void e7(s.error??`HTTP ${e.status}`);if(t){var i=s.cwd;try{window.localStorage.setItem(rt,i)}catch{}e6(s.cwd)}if(e3(!1),"new-session"===n){let e=rT.current,t=rR.current;rT.current=null,rR.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),rP(()=>t?.isConnected?t:null);return}tc({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),e1(s.cwd)}catch(e){e7(e instanceof Error?e.message:String(e))}finally{tn(!1)}}},[e8,e5,tt,rP]),iu=(0,i.useCallback)(()=>{e3("files"),e7(null)},[]),ip=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"files";try{let t=await fetch("/api/default-cwd",{method:"POST"}),n=await t.json();n.cwd&&await ic(n.cwd,{remember:!1,purpose:e})}catch{}},[ic]),ih=(0,i.useRef)(ip);ih.current=ip;let im=(0,i.useCallback)(async(e,t)=>{try{let r=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,branch:t})}),i=await r.json().catch(()=>({}));if(!r.ok||i.error||!i.path){var n;let e,t=(n=r.status,(e="branch_in_use"===i.code?"sidebar.worktreeBranchInUse":"branch_worktree_missing"===i.code?"sidebar.worktreeBranchMissing":null)&&i.branch&&i.worktreePath?{key:e,params:{branch:i.branch,path:i.worktreePath}}:{error:i.error??`HTTP ${n}`});return"key"in t?{error:eF(t.key,{...t.params,path:ey(t.params.path)})}:t}let s=i.path;return th(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),io(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[eF]),ig=(0,i.useCallback)(async(e,t,n)=>{try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e.root,path:t,force:n})}),i=await r.json().catch(()=>({}));if(!r.ok){if(i.dirty&&!n)return"dirty";return{error:i.error??`HTTP ${r.status}`}}return id===t&&e1(e.root),io(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[id]),ix=(0,i.useCallback)(()=>io(e=>e+1),[]),iv=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&tc({cwd:t,root:r,key:n}),e1(t)},[]),ib=(0,i.useCallback)((e,t,n,r)=>{e_(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&e1(e.cwd),y(e,!1,t,n,r)},[y]),iy=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&tc({cwd:t,root:r,key:n}),e1(t),w?.("function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,t,n,i?{carryComposer:!0}:void 0)},[w]),iw=(0,i.useRef)(iy);iw.current=iy,(0,i.useImperativeHandle)(k,()=>({startNewSessionIn:e=>iw.current(e),openFolderForNewSession:(e,t)=>{rT.current=e,rR.current=t,e7(null),e3("new-session")},openDefaultDirectoryForNewSession:e=>{rT.current=e,rR.current=null,ih.current("new-session")},refreshWorktrees:ix,createWorktree:im}),[im,ix]);let ij=(0,i.useCallback)(()=>{eX&&iy({cwd:eX})},[eX,iy]),ik=(0,i.useMemo)(()=>m(eH,rU),[eH,rU]),iS=(0,i.useMemo)(()=>o(eH,rq),[eH,rq]),iC=(0,i.useMemo)(()=>new Map(iS.map(e=>[e.root.id,e])),[iS]),iN=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of iS){if(!H(n,rW,tB))continue;for(let t of D(n))e.add(t);let r=f(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[iS,rW,tB]),i$=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=f(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(0===iN.ids.size?eH:eH.filter(e=>!iN.ids.has(e.id)),tB,tV),[eH,iN,tB,tV]),iE=!!(tp?.isGit&&tp.isTopLevel&&eX&&ir?.key===tp.projectKey),iI=eX&&tp?.isGit&&ir?.key===tp.projectKey&&!iE?{label:eF("sidebar.openRepoRoot"),title:eF("sidebar.openRepoRootTitle")}:null,iM=!!(eX&&tf===eX),iT=iI??(!iM||iE||eX&&tg.current?.has(eX)?null:{label:eF("sidebar.worktrees"),title:eF("sidebar.checkingWorktrees")}),iR=ir?.key??null,iA=ir?.root??null,iL=(0,i.useMemo)(()=>iR&&iA?{key:iR,root:iA}:null,[iR,iA]),iz=(0,i.useMemo)(()=>0===nR.size?nM:Object.fromEntries([...[...nR].filter(e=>!Object.hasOwn(nM,e)).map(e=>[e,!0]),...Object.entries(nM)]),[nM,nR]),iP=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=o(e.sessions),s=J(t,r),l=0,a=[],d=new Map,c=new Map,u=new Set;for(let e of i){if(H(e,t,n)){l++;continue}s.noteFamily(e);let r=Z(e),i=function(e){let t=Date.parse(e);return Number.isNaN(t)?-1/0:t}(e.latestModified);if(c.set(r,Math.max(c.get(r)??-1/0,i)),e.root.transient||u.add(r),_(e,t,n)){a.push(e);continue}let o=d.get(r);o?o.push(e):d.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(a.length>0){let n=e=>O(W(t,e.root.id)?.pinnedAt)??0,r=a.map((e,t)=>({family:e,index:t})).sort((e,t)=>F(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:l,unread:o}=V(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:l,unread:o}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=G(r,8,X(e.moreShown,P),e);for(let n of t)p.push(Y(n,"pinned",s.get(Z(n)),e));let l=ee(r.length,t.length,n);l&&p.push({kind:"pinned-more",key:"pinned-more",...l,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...d.keys()],f=new Set(h),m=e=>{f.has(e)||(f.add(e),h.push(e))};for(let e of(r&&m(r.key),Object.keys(t.projects)))m(e);let g=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let v=e=>e.pinned||u.has(e.key),b=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(v(e.project))-Number(v(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return x.has(t.key)}).sort((e,t)=>(x.get(e.project.key)??0)-(x.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),y=e=>c.get(e.key)??(e.current?1/0:-1/0),w=e=>O(t.projects[e.key]?.pinnedAt)??0,j=g.map((e,t)=>({project:e,index:t})),k=b(j.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>F(w(t.project),w(e.project))||e.index-t.index),S=b(j.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>F(y(e.project),y(t.project))||e.index-t.index),C=[...k,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),$={pinned:N(k),other:N(S)},E=C.filter(e=>!x.has(e.key)&&v(e)).map(e=>e.key);for(let[t,n]of C.entries()){t>0&&p.push({kind:"spacer",key:`group-spacer:${n.key}`});let r=d.get(n.key)??[],i=q(n,e.groupExpansion),{running:s,awaiting:l,unread:o}=V(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:l,unread:o}),i)if(0===r.length)p.push({kind:"group-empty",key:`empty:${n.key}`,project:n});else{let{visible:t,revealed:i,nextShown:s}=G(r,6,X(e.moreShown,n.key),e);for(let r of t)p.push(Y(r,"group",n,e));let l=ee(r.length,t.length,i);l&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...l,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),l>0&&p.push({kind:"footer-archived",key:"footer-archived",count:l}),{rows:p,projects:C,archivedCount:l,unorderedKeysByBand:$,projectKeysToRecord:E}})({sessions:eH,uiState:rW,runningIds:tB,awaitingIds:t_,unreadIds:tV,selectedSessionId:b,currentProject:iL,groupExpansion:iz,moreShown:nL,pinnedCollapsed:nP}),[eH,rW,tB,t_,tV,b,iL,iz,nL,nP]),iW=nQ.archiveMounted,iO=(0,i.useMemo)(()=>new Set(nO),[nO]),iF=(0,i.useMemo)(()=>iW?function(e){let{uiState:t,runningIds:n}=e,r=J(t,e.currentProject),i=new Map;for(let s of o(e.sessions)){if(!H(s,t,n))continue;r.noteFamily(s);let e=O(W(t,s.root.id)?.archivedAt)??0,l=Z(s),o=i.get(l);o?(o.families.push({family:s,archivedAt:e}),o.newest=Math.max(o.newest,e)):i.set(l,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>F(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),l=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:l}),l)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>F(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(Y(t,"archive",i,e))}return s}({sessions:eH,uiState:rW,runningIds:tB,awaitingIds:t_,unreadIds:tV,selectedSessionId:b,currentProject:iL,collapsed:iO}):[],[iW,eH,rW,tB,t_,tV,b,iL,iO]),iD=(0,i.useMemo)(()=>iF.flatMap(e=>"archive-group"===e.kind?[e]:[]),[iF]),iB=(0,i.useMemo)(()=>new Map(iP.projects.map(e=>[e.key,e])),[iP.projects]),iH=(0,i.useRef)(new Set),i_=iP.projectKeysToRecord,iU=rW.projectOrder?.length??0;(0,i.useEffect)(()=>{if(eK||!rF||!eZ||iU>=1e3)return;let e=iH.current,t=function(e,t){let n=e.length;for(;n>0&&e.length-n<500&&!t.has(e[n-1]);)n--;return e.slice(n)}(i_,e);if(0!==t.length){for(let n of t)e.add(n);rB({action:"add-projects",keys:t})}},[rB,eK,i_,eZ,iU,rF]);let iq=rW.projectNames,iK=(0,i.useMemo)(()=>(function(e,t,n){let r=new Set,i=[];for(let s of[...e,...t])r.has(s.key)||(r.add(s.key),i.push(eN(s,n)));return i})(iP.projects,ik,iq),[iP.projects,ik,iq]),iV=(0,i.useMemo)(()=>{if(!eX||!ir)return null;let e=iE&&null!==tp;return{cwd:eX,project:eN(ir,iq),worktrees:e?tp.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?id:null,projects:iK}},[eX,ir,iE,tp,id,iK,iq]),iZ=(0,i.useRef)(iV);iZ.current=iV;let iJ=iV?JSON.stringify([iV.cwd,iV.project.key,iV.project.root,iV.project.alias??null,iV.currentWorktreePath,iV.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,iV.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{z?.(iZ.current)},[iJ,z]);let iY=(0,i.useRef)(iR);(0,i.useLayoutEffect)(()=>{let e=iY.current;if(iY.current=iR,null===e||e===iR)return;let t=iB.get(e);nA(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nM,t.key)?e:new Set(e).add(t.key))},[iR,nM,iB]);let iG=(0,i.useCallback)((e,t)=>{nT(e),eg(e),nA(e=>(function(e,t){if(0===e.size)return e;if(null===t)return new Set;if(!t.some(t=>e.has(t)))return e;let n=new Set(e);for(let e of t)n.delete(e);return n})(e,t)),nz(n=>(function(e,t,n){let r=(n??Object.keys(t)).filter(n=>!1===t[n]&&Object.hasOwn(e,n));if(0===r.length)return e;let i={...e};for(let e of r)delete i[e];return i})(n,e,t))},[]),iX=(0,i.useCallback)(()=>(nv.current?.hidden?ng:na).current??rZ.current,[]),iQ=(0,i.useCallback)(e=>{let t=nv.current;for(let n of["pinned","group","archive"]){let r=CSS.escape(`session:${n}:${e}`),i=t?.querySelector(`[data-row-key="${r}"] .session-tree-main`);if(i&&i.getClientRects().length>0)return i}return iX()},[iX]),i0=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nv.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:iX()},[iX]),i1=(0,i.useCallback)(async e=>{let t=await rB(e);return t||rC(e=>e+1),t},[rB]);(0,i.useEffect)(()=>{rS!==rN.current&&(rN.current=rS,rk(eF("sidebar.uiStateFailed",{error:rD??""})))},[rS,rD,rk,eF]);let i2=(0,i.useCallback)((e,t,n)=>{let r=iB.get(e),i=iB.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(i1({action:"move-project",projectKey:e,anchorKey:t,position:n,add:iP.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rf.current+=1,rh({id:rf.current,at:Date.now(),rowKey:`group:${e}`}))},[i1,iP.unorderedKeysByBand,iB]),i4=(0,i.useCallback)(e=>{t5||(t9(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ef();if(t)try{t.setItem(es,e)}catch{}}(e))},[t5]),i8=(0,i.useCallback)(e=>{e!==nZ.current&&n_(e?"out":"in"),ne(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ef();if(t)try{t.setItem(eu,String(e))}catch{}}(e)},[n_]),i3=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nE.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nv.current,nN.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nE.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[t6,nD,t5,t7]);let i5=(0,i.useCallback)(e=>{if(ru(null),nY(!0),tN(!1),i4("sessions"),void 0!==e){if(nO.includes(e)){let t=nO.filter(t=>t!==e);nF(t),ex(t)}rf.current+=1,rx({id:rf.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[nO,nY,i4]),i6=(0,i.useRef)(null),i9=(0,i.useRef)(nD),i7=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(i9.current===nD)return;if(i9.current=nD,nD)return void ro(i6.current);let e=nv.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:iX();ro(t),t&&document.activeElement===t&&(i7.current=t)},[nD,iX]);let se=(0,i.useRef)(null),st=(0,i.useRef)(t5);(0,i.useLayoutEffect)(()=>{if(st.current===t5)return;st.current=t5;let e=se.current;e&&(!e.isConnected||0===e.getClientRects().length)&&ro(iX())},[t5,iX]);let sn=e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault();let t="Home"===e.key?"sessions":"End"===e.key||"sessions"===t6?"files":"sessions";i4(t),("sessions"===t?na:ng).current?.focus()},sr=(0,i.useCallback)((e,t)=>{i1({action:"set",ids:[e.root.id],pinned:t})},[i1]),si=(0,i.useCallback)((e,t)=>{tZ(n=>{let r=new Set(n);if(t)for(let t of D(e))r.delete(t);else r.add(e.root.id);return r})},[]),ss=(0,i.useCallback)(e=>{0!==e.length&&tZ(t=>{let n=new Set(t);for(let t of e)t!==rb.current&&n.add(t);return n.size===t.size?t:n})},[]),sl=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=rH(t.map(e=>e.root.id)),r=t.flatMap(e=>D(e)),i=r.filter(e=>tV.has(e));for(let e of L(t))i1({action:"set",ids:e.map(e=>e.root.id),archived:!0}).then(t=>{if(t||0===i.length)return;let n=new Set(e.flatMap(e=>D(e)));ss(i.filter(e=>n.has(e)))});i.length>0&&tZ(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),rk(1===t.length?eF("sidebar.archivedToast",{title:rl(n$(t[0].root),28)}):eF("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eF("sidebar.undo"),onClick:()=>{for(let e of L(n))i1({action:"restore",entries:e});ss(i),rP(()=>iQ(t[0].root.id))}},{id:"view",label:eF("sidebar.viewArchive"),onClick:()=>i5()}])},[i1,rP,iQ,i5,ss,rk,rH,eF,tV]),so=(0,i.useCallback)(e=>{D(e).some(e=>tB.has(e))||sl([e])},[sl,tB]),sa=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=rH(t);for(let e of L(t))i1({action:"set",ids:e,archived:!1});rk(1===e.length?eF("sidebar.restoredToast",{title:rl(n$(e[0].root),28)}):eF("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eF("sidebar.undo"),onClick:()=>{for(let e of L(n))i1({action:"restore",entries:e});rP(()=>iQ(e[0].root.id))}}])},[i1,iQ,rP,rk,rH,eF]),sd=(0,i.useCallback)(e=>sa([e]),[sa]),sc=(0,i.useCallback)(e=>{e.root.transient||(rd(null),n1(e.root.id))},[]),su=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=n$(n),i=t.trim();if(n1(e=>e===n.id?null:e),t!==r&&i!==(n.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(n.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i})}),r8()}catch{}},[r8]),sp=(0,i.useCallback)(e=>{n4(e.key)},[]),sh=(0,i.useCallback)(e=>{n4(t=>t===e?null:t),rP(()=>i0(e))},[rP,i0]),sf=(0,i.useCallback)((e,t)=>{sh(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===U(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&i1(n)},[i1,sh]),sm=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){rd(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),eC?.(t.id),r8()}catch{}}},[r8,eC]),sg=(0,i.useCallback)((e,t)=>{t?sm(e):(n1(null),rd(e.root.id))},[sm]),sx=(e,t)=>{if(i7.current=null,nD){let e=nv.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nE.current.delete(e),nY(!1)}let n=f(e);if(Object.hasOwn(iz,n)&&!1===iz[n]){let e={...nM};delete e[n],e[n]=!0,iG(e,[n])}ib(e,void 0,void 0,{keepSidebarOpen:null!==t}),r8();let r=t?`[data-row-key="${CSS.escape(t)}"]`:null;rf.current+=1,rh({id:rf.current,at:Date.now(),rowKey:`session:group:${e.id}`,takeFocusFrom:e=>null!==r&&null!==e.closest(r)||e===i7.current})},sv=(0,i.useRef)(sx);sv.current=sx;let sb=(0,i.useRef)(new Set),sy=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sb.current.has(t.id))return;sb.current.add(t.id);let n=rb.current;try{var r;let i,s,l=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),o=await l.json().catch(()=>({}));if(!l.ok||!o.session){let{key:e,params:t}=function(e,t){switch(e){case"not_found":return{key:"sidebar.forkNotFound"};case"unsaved":return{key:"sidebar.forkUnsaved"};case"empty":return{key:"sidebar.forkEmpty"};case"subagent":case"request-denied":return{key:"sidebar.forkUnavailable"};default:return{key:"sidebar.forkFailed",params:{error:t}}}}(o.code,o.error??`HTTP ${l.status}`);rk(eF(e,t)),"not_found"===o.code&&r8();return}let a=o.session,d=n$(a),{head:c,tail:u}=(r=eF("sidebar.forkedToast",{title:d}),((s=(i=ek(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eF("sidebar.forkedToast",{title:rl(d,28)}),tail:void 0});if(rb.current!==n){e_(e=>e.some(e=>e.id===a.id)?e:[a,...e]),tZ(e=>new Set(e).add(a.id)),r8(),rk(c,[{id:"open",label:eF("sidebar.open"),onClick:()=>sv.current(a,null)}],u);return}sv.current(a,e.key),rk(c,[],u)}catch(e){rk(eF("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{sb.current.delete(t.id)}},[r8,rk,eF]),sw=(0,i.useCallback)(e=>{e.root.transient||window.open(d(e.root.id),"_blank","noopener,noreferrer")},[]),sj=(0,i.useCallback)((e,t,n)=>{e.status.transient||ru({kind:"row",row:e,anchor:t,opener:n})},[]),sk=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===n0||n.id===n5)return;if(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:window,n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)}({id:n.id,path:n.path,cwd:n.cwd,name:n.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{r8()}})){t.preventDefault(),t.stopPropagation();return}if(n.transient)return;t.preventDefault();let r=t.currentTarget instanceof HTMLElement?t.currentTarget:null,i=0===t.clientX&&0===t.clientY&&r?ra(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,l=s instanceof HTMLElement&&null!==r&&r.contains(s);rM.current=!l&&s instanceof HTMLElement&&s!==document.body?s:null,sj(e,i,l?s:null)},[n5,r8,sj,n0]),sS=(0,i.useMemo)(()=>({sessions:eH,uiState:rW,runningIds:tB,awaitingIds:t_,unreadIds:tV,selectedSessionId:b}),[eH,rW,tB,t_,tV,b]),sC=(0,i.useCallback)((e,t)=>{let n=et(sS,e.key,6048e5,Date.now()).length;ru({kind:"group",project:e,olderCount:n,anchor:ra(t,"end"),opener:t})},[sS]),sN=(0,i.useCallback)(e=>{sl(et(sS,e.key,6048e5,Date.now()).flatMap(e=>{let t=iC.get(e);return t?[t]:[]}))},[sl,iC,sS]),s$=(0,i.useCallback)((e,t)=>{ru(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),sE=(0,i.useRef)(new Set),sI=(0,i.useCallback)(async(e,t,n)=>{if(ru(null),!(0===t.length||sE.current.has(e))){sE.current.add(e),rk(eF("sidebar.deletingSessions"));try{let e=await eb(t,fetch);for(let t of e.deleted)eC?.(t);if(r8().then(()=>rP(n)),null!==e.error)return void rk(eF("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eF("sidebar.deletedOneToast"):eF("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eF("sidebar.keptRunningToast",{count:e.running.length})),rk(i.join(" \xb7 "))}finally{sE.current.delete(e)}}},[rP,r8,eC,rk,eF]),sM=(0,i.useCallback)(e=>{let{ids:t}=en(sS,e.key);sI(`project:${e.key}`,t,()=>i0(e.key))},[sI,i0,sS]),sT=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nv.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=i6.current;return r&&r.getClientRects().length>0?r:iX()},[iX]),sR=(0,i.useCallback)(e=>e.flatMap(e=>{let t=iC.get(e);return t?[t]:[]}),[iC]),sA=(0,i.useCallback)((e,t)=>{ru({kind:"archive-group",project:e,anchor:ra(t,"end"),opener:t})},[]),sL=(0,i.useCallback)(e=>{ru(t=>t?.kind==="archive"?null:{kind:"archive",anchor:ra(e,"end"),opener:e})},[]),sz=(0,i.useCallback)(e=>{ru(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),sP=(0,i.useCallback)(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];for(let r of o(e.sessions))if((void 0===t.projectKey||Z(r)===t.projectKey)&&H(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=O(W(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(sS,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[sS]),sW=(0,i.useCallback)(e=>{let t=sP(e);sI("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?sT(null):sT(e.projectKey))},[sP,sT,sI]),sO=(0,i.useCallback)(e=>{nF(e),ex(e)},[]),sF=(0,i.useCallback)(e=>{let t=iD.map(e=>e.project.key),n=nO.filter(e=>!t.includes(e));sO(e?n:[...n,...t])},[nO,iD,sO]),sD=(0,i.useCallback)((e,t)=>{let n=nO.includes(e);if(t)return void sF(n);let r=nO.filter(t=>t!==e);sO(n?r:[...r,e])},[nO,sO,sF]),sB=(0,i.useCallback)(e=>{ru(null),iy(eS(e,eX))},[eX,iy]),sH=(0,i.useCallback)(()=>ru(null),[]);(0,i.useEffect)(()=>{if(null!==rc)return;let e=rM.current;if(rM.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rc]);let s_=nD?iF:iP.rows;(0,i.useEffect)(()=>{rc?.kind!=="row"||s_.some(e=>e.key===rc.row.key)||ru(null),rc?.kind!=="archive-group"||s_.some(e=>e.key===`archive:${rc.project.key}`)||ru(null)},[rc,s_]);let sU=rc?.kind==="row"?s_.find(e=>"session"===e.kind&&e.key===rc.row.key)??rc.row:null,sq=(0,i.useCallback)(e=>{ib(e.root)},[ib]),sK=(0,i.useCallback)(e=>{let t={...nM};for(let n of iP.projects)delete t[n.key],t[n.key]=e(n);iG(t,null)},[nM,iP.projects,iG]),sV=(0,i.useCallback)((e,t)=>{let n=iB.get(e);if(!n)return;let r=!q(n,iz);if(t)return void sK(()=>r);let i={...nM};delete i[e],i[e]=r,iG(i,[e])},[nM,iB,iG,sK,iz]),sZ=(0,i.useCallback)(e=>{let t=iP.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===P);(t?.kind==="group-more"||t?.kind==="pinned-more")&&nz(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(X(n,e),Math.floor(r))}})},[iP.rows]),sJ=(0,i.useCallback)(e=>{nz(t=>Q(t,e))},[]),sY=(0,i.useCallback)(e=>{r$.current=e,rI(e=>e+1),t5?i8(!1):i4("files")},[i8,t5,i4]),sG=t5?nG.open:"files"===t6;(0,i.useEffect)(()=>{let e=r$.current;e&&sG&&(r$.current=null,"project-list"===e?tu.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tu.current?.button("project")?.focus({preventScroll:!0}))},[sG,rE]);let sX=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:l,onCancel:o}=e;return(0,r.jsxs)("div",{className:"sidebar-menu-question",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),i.map(e=>(0,r.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,r.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===s,onClick:l,children:eF("sidebar.deleteCount",{count:s})}),!eB&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:o,children:eF("sidebar.cancel")})]})]})},sQ=(e,t)=>sX({heading:t?eF("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eF("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eF("sidebar.deleteArchivedMessage")],count:sP(e).length,onConfirm:()=>sW(e),onCancel:()=>sz(void 0)}),s0="",s1=null;if(rc?.kind==="row"&&sU)h=n$(sU.family.root),s0=eF("sidebar.sessionActions"),v=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(sU.context,sU.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eF(rn[e.id]);return{type:"item",id:e.id,label:"delete"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,r.jsx)(nc,{});case"pin":return(0,r.jsx)(ns,{});case"unpin":return(0,r.jsx)(nl,{});case"rename":return(0,r.jsx)(np,{});case"fork":return(0,r.jsx)(nd,{});case"mark-read":return(0,r.jsx)(nf,{});case"mark-unread":return(0,r.jsx)(nh,{});case"archive":return(0,r.jsx)(nr,{});case"unarchive":return(0,r.jsx)(ni,{});case"delete":return(0,r.jsx)(nu,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?eF("sidebar.cannotArchiveRunning"):void 0,onSelect:t=>{let{shiftKey:n}=t;return((e,t,n)=>{let{family:r}=t;switch(e){case"open-new-tab":sw(r);break;case"pin":sr(r,!0);break;case"unpin":sr(r,!1);break;case"rename":sc(r);break;case"fork":sy(t);break;case"mark-read":si(r,!0);break;case"mark-unread":si(r,!1);break;case"archive":so(r);break;case"unarchive":sd(r);break;case"delete":sg(r,n)}})(e.id,sU,n)}}});else if(rc?.kind==="group"){let e,t,i,l,o,a=iB.get(rc.project.key)??rc.project;h=a.name,s0=eF("sidebar.projectActions",{name:a.name}),n=a,s=rc.olderCount,e=iN.countByProject.get(n.key)??0,t=en(sS,n.key),i=er(iP.projects,n.key,"up"),l=er(iP.projects,n.key,"down"),o=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:eF("sidebar.renameProject"),icon:(0,r.jsx)(np,{}),onSelect:()=>sp(n)}:{type:"item",id:e,label:eF("sidebar.resetProjectName"),icon:(0,r.jsx)(ni,{}),onSelect:()=>{i1({action:"rename-project",projectKey:n.key,name:null})}}),v=[{type:"item",id:"pin-project",label:eF(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(nl,{}):(0,r.jsx)(ns,{}),onSelect:()=>{i1({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...o,{type:"item",id:"open-in-files",label:eF("sidebar.openInFilesTab"),icon:(0,r.jsx)(nx,{}),onSelect:()=>{n.current||e1(n.root),sY("project-button")}},{type:"item",id:"open-new-tab",label:eF("sidebar.openInNewTab"),icon:(0,r.jsx)(nc,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=eS(e,eX);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eF("sidebar.moveProjectUp"),icon:(0,r.jsx)(no,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&i2(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eF("sidebar.moveProjectDown"),icon:(0,r.jsx)(no,{className:"sidebar-icon-down"}),disabled:null===l,onSelect:()=>{l&&i2(n.key,l.anchorKey,l.position)}},{type:"item",id:"collapse-others",label:eF("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(no,{}),disabled:iP.projects.every(e=>q(e,iz)===(e.key===n.key)),onSelect:()=>sK(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eF("sidebar.expandAllGroups"),icon:(0,r.jsx)(no,{className:"sidebar-icon-down"}),disabled:iP.projects.every(e=>q(e,iz)),onSelect:()=>sK(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:eF("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(nr,{}),disabled:0===s,onSelect:()=>sN(n)},{type:"item",id:"view-archived",label:eF("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(nr,{}),disabled:0===e,onSelect:()=>i5(n.key)},{type:"item",id:"delete-all",label:eF("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(nu,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),s$(n.key,!0)}}],rc.askDelete&&(s1=(e=>{let{ids:t,running:n}=en(sS,e.key);return sX({heading:eF("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eF("sidebar.deleteProjectSessionsMessage"),...n>0?[eF("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>sM(e),onCancel:()=>s$(e.key,!1)})})(a)),g=264}else if(rc?.kind==="archive-group"){let e,t=iD.find(e=>e.project.key===rc.project.key)?.project??rc.project;h=t.name,s0=eF("sidebar.archivedProjectActions",{name:t.name}),v=[{type:"item",id:"restore-all",label:eF("sidebar.restoreAllArchived",{count:(e=sP({projectKey:t.key})).length}),icon:(0,r.jsx)(ni,{}),disabled:0===e.length,onSelect:()=>sa(sR(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eF("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(nu,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sz("all")}}],rc.askDelete&&(s1=sQ({projectKey:t.key},t)),g=248}else if(rc?.kind==="archive"){let e,t,n;h=eF("sidebar.archived"),s0=eF("sidebar.archiveActions"),e=sP("all"),t=sP("old"),n=iD.filter(e=>!e.expanded).length,v=[{type:"item",id:"collapse-all",label:eF("sidebar.collapseAllGroups"),icon:(0,r.jsx)(no,{}),disabled:n===iD.length,onSelect:()=>sF(!1)},{type:"item",id:"expand-all",label:eF("sidebar.expandAllGroups"),icon:(0,r.jsx)(no,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>sF(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eF("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(ni,{}),disabled:0===e.length,onSelect:()=>sa(sR(e))},{type:"item",id:"delete-old",label:eF("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(nu,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),sz("old")}},{type:"item",id:"delete-all",label:eF("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(nu,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sz("all")}}],rc.askDelete&&(s1=sQ(rc.askDelete,null)),g=280}let s2={layout:eB?"mobile":"desktop",loading:eK||!rO,error:eY,renamingRootId:n0,renamingProjectKey:n2,confirmDeleteRootId:n5,activeMenuRowKey:rc?.kind==="row"?rc.row.key:rc?.kind==="group"?`group:${rc.project.key}`:rc?.kind==="archive-group"?`archive:${rc.project.key}`:null,onSelectFamily:sq,onToggleGroup:sV,onShowMore:sZ,onShowLess:sJ,onTogglePinned:()=>{let e=!nP;nW(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ef();if(t)try{t.setItem(ed,String(e))}catch{}}(e),e&&nz(e=>Q(e,P))},onArchiveFamily:so,onRestoreFamily:sd,onOpenRowMenu:sj,onRowContextMenu:sk,onRenameCommit:(e,t)=>{su(e,t)},onRenameCancel:()=>n1(null),onRenameProjectCommit:sf,onRenameProjectCancel:()=>{n2&&sh(n2)},onDeleteConfirm:e=>{sm(e)},onDeleteCancel:()=>{rd(null),n5&&rP(()=>iQ(n5))},onGroupNew:sB,onGroupMenu:sC,onToggleArchiveGroup:sD,onArchiveGroupMenu:sA,onOpenOtherProject:()=>{sY("project-list")},onOpenArchive:()=>i5(),onMoveGroup:i2},s4=eX??e$??null,s8=s4&&tI>0?eF("sidebar.changedFiles",{count:tI}):void 0,s3=(0,i.useRef)(null),s5=!s4||0===tI;(0,i.useLayoutEffect)(()=>{let e=s3.current;if(s5&&e&&se.current===e){var t,n;let r;t=document,n=iX(),(r=function(e){let t=e=>e?.tagName==="BUTTON"&&!e.disabled;for(let n=e.nextElementSibling;n;n=n.nextElementSibling)if(t(n))return n;for(let n=e.previousElementSibling;n;n=n.previousElementSibling)if(t(n))return n;return null}(e)??n)&&t.activeElement===e?r.focus({preventScroll:!0}):eI(t,r)}},[s5,iX]);let s6=t5||"sessions"===t6,s9=!t5&&"files"===t6&&null!==s4,s7=(t=(t5?["below",eF("sidebar.new")]:["tabs",eF("sidebar.tabSessions"),eF("sidebar.tabFiles"),eF("sidebar.new"),s4&&tI>0?tI:"",t6]).join("\n"),p=(0,i.useCallback)(()=>{let e=rK.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[rK]),(0,i.useLayoutEffect)(()=>{let e=rK.current;if(!e)return;p();let t=new ResizeObserver(p);return t.observe(e),()=>t.disconnect()},[rK,p,t]),p),le=iP.archivedCount,lt=t5?13:14,ln=(0,r.jsx)(n7,{onClick:()=>{s4&&eT?.(s4)},disabled:!s4||!eT,title:eF("terminal.open"),children:(0,r.jsx)(nb,{size:lt})}),lr=(0,r.jsx)(n7,{onClick:()=>{r5().then(e=>{e&&t5&&i8(!1)})},disabled:!s4||r9,title:r9?eF(tW?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):r6,children:(0,r.jsx)(nx,{size:lt})}),li=(0,r.jsx)(n7,{onClick:()=>{t5&&t7&&i8(!1),t8.current?.openUploadPicker()},disabled:!s4||tb,title:eF("sidebar.uploadFilesTitle"),children:(0,r.jsx)(nw,{size:lt})}),ls=(0,r.jsx)(n7,{onClick:()=>{eA?eA():tv(e=>e+1),tP(!0),t2.current&&clearTimeout(t2.current),t2.current=setTimeout(()=>tP(!1),2e3)},disabled:!s4,title:eF("sidebar.refreshExplorer"),done:tz,children:tz?(0,r.jsx)(nm,{size:lt}):(0,r.jsx)(nj,{size:lt})}),ll=e=>(0,r.jsx)(n7,{onClick:()=>{let e=!tA;tL(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ef();if(t)try{t.setItem(ec,String(e))}catch{}}(e)},disabled:!s4,title:eF("sidebar.showIgnoredFiles"),pressed:tA,className:e,children:(0,r.jsx)(nS,{size:lt})}),lo=(0,r.jsx)(n7,{ref:s3,onClick:()=>{if(t5&&t7){i8(!1),tR(!1);return}tR(e=>!e)},disabled:s5,title:eF("sidebar.changedFiles",{count:tI}),pressed:!s5&&!tT,children:(0,r.jsx)(nk,{size:lt})});return(0,r.jsxs)("div",{ref:r2,className:`session-sidebar${t5?" is-files-below":""}${t5&&t7?" is-files-collapsed":""}${t5&&nG.moving?" is-files-folding":""}${ry?" has-toast":""}`,style:{"--sidebar-files-height":`${r0.width}px`},onFocus:e=>{se.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(se.current=null))},children:[e8&&(0,r.jsx)(ty,{initialPath:e5,busy:tt,error:e9,onCancel:()=>{let e="new-session"===e8?rR.current:null;rT.current=null,rR.current=null,e3(!1),e7(null),e&&rP(()=>e.isConnected?e:null)},onSelect:e=>void ic(e)}),(0,r.jsxs)("div",{ref:rK,className:"sidebar-header",children:[t5&&(0,r.jsx)(t4,{onWidthChange:s7}),!t5&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eF("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:na,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===t6,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===t6?0:-1,className:`sidebar-tab${"sessions"===t6?" is-selected":""}`,onClick:()=>i4("sessions"),onKeyDown:sn,children:[(0,r.jsx)(nC,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eF("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:ng,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===t6,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===t6?0:-1,title:s8,className:`sidebar-tab${"files"===t6?" is-selected":""}`,onClick:()=>i4("files"),onKeyDown:sn,children:[(0,r.jsx)(nx,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eF("sidebar.tabFiles")}),s4&&tI>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tI})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:ij,disabled:!eX,title:eX?eF("sidebar.newSessionTitle",{path:eX}):eF("sidebar.selectProject"),children:[(0,r.jsx)(nt,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eF("sidebar.new")})]}),(0,r.jsx)("button",{ref:rZ,type:"button",onClick:()=>{if(s9)return void tS(e=>!e);if(!s6){i4("sessions"),tN(!0);return}tN(e=>!e)},title:s9?eF("sidebar.searchFiles"):eF("sidebar.toggleSessionSearch"),"aria-label":s9?eF("sidebar.searchFiles"):eF("sidebar.toggleSessionSearch"),"aria-expanded":s9?tk:tC,"aria-controls":s9?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(s9?tk:tC)?" is-active":""}`,children:(0,r.jsx)(ny,{size:16})})]}),(0,r.jsxs)("div",{ref:nv,id:"session-sidebar-panel-sessions",role:t5?"region":"tabpanel","aria-label":t5?eF("sidebar.tabSessions"):void 0,"aria-labelledby":t5?void 0:"session-sidebar-tab-sessions",hidden:!t5&&"sessions"!==t6,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:i3,children:[tC&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:t$,maxLength:200,"aria-label":eF("sidebar.searchSessions"),placeholder:eF("sidebar.searchSessions"),onChange:e=>tE(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tE(""))},className:"sidebar-search-input"})}),(0,r.jsx)(n3,{open:tC,query:t$,selectedSessionId:b,onSelectSession:ib,archivedSessionIds:iN.ids,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:nQ.mainHidden,inert:nQ.mainInert,children:(0,r.jsx)(nI,{...s2,rows:iP.rows,emptyLabel:eF("sidebar.noSessions"),reveal:rp,onRevealHandled:rm})}),nQ.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${nQ.archiveClass?` ${nQ.archiveClass}`:""}`,inert:nQ.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&nV()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:i6,type:"button",className:"sidebar-archive-back",title:eF("sidebar.backToSessions"),"aria-label":`${eF("sidebar.backToSessions")}: ${eF("sidebar.archivedCount",{count:le})}`,onClick:()=>nY(!1),children:[(0,r.jsx)(no,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eF("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",le]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rc?.kind==="archive"?" is-active":""}`,title:eF("sidebar.archiveActions"),"aria-label":eF("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rc?.kind==="archive",disabled:0===iD.length,onClick:e=>sL(e.currentTarget),children:(0,r.jsx)(nn,{size:13})})]}),(0,r.jsx)(nI,{...s2,rows:iF,emptyLabel:eF("sidebar.noArchived"),reveal:rg,onRevealHandled:rv})]})]})})]}),t5&&nG.open&&(0,r.jsx)("div",{...r0.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${r0.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eF("sidebar.resizeFiles")}: ${eF("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:nN,id:"session-sidebar-panel-files",role:t5?"region":"tabpanel","aria-label":t5?eF("sidebar.tabFiles"):void 0,"aria-labelledby":t5?void 0:"session-sidebar-tab-files",hidden:!t5&&"files"!==t6,className:"sidebar-panel sidebar-files-panel",onScrollCapture:i3,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&nU()},children:[t5&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!t7,"aria-controls":"session-sidebar-files-body",title:s8,onClick:()=>i8(!t7),children:[(0,r.jsx)(no,{size:12,strokeWidth:3,className:`session-tree-chevron${t7?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eF("sidebar.tabFiles")}),s8&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tI]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eF("sidebar.fileActions"),children:[ln,lr,li,ls,ll(),lo,(0,r.jsx)(n7,{onClick:()=>{if(t7){tS(!0),sY("file-search");return}tS(e=>!e)},disabled:!s4,title:eF("sidebar.searchFiles"),expanded:tk,controls:"file-search-input",children:(0,r.jsx)(ny,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:t5&&nG.bodyHidden,inert:t5&&nG.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(n8,{handleRef:tu,layout:t5?"row":"stacked",context:iV??{project:null,worktrees:null,currentWorktreePath:null,projects:iK},mobile:eB,label:eF("sidebar.projectAndWorktree"),placeholder:B&&!ie.current?"":eF("sidebar.selectProject"),homeDir:e2,projectActivity:i$,worktreeHint:iT,newWorktreeTitle:eF("sidebar.createWorktreeTitle"),onPick:iv,onUseDefaultDirectory:()=>{ip()},onOpenFolder:iu,onRefreshWorktrees:ix,onCreateWorktree:im,onRemoveWorktree:ig}),!t5&&s4&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eF("sidebar.fileActions"),children:[eT&&ln,lr,li,ls,ll("sidebar-files-views-start"),lo]})]}),s4&&r7&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:r7}),(0,r.jsx)(tw,{onClick:()=>tD(null),title:eF("files.dismissError")})]}),(0,r.jsx)("div",{ref:rV,className:"sidebar-files-scroll scrollbar-subtle",children:s4&&(0,r.jsx)(t0,{ref:t8,cwd:s4,onOpenFile:eM??(()=>{}),refreshKey:tx,onAtMention:eL,onAtMentions:ez,onUploadBusyChange:tj,changesCollapsed:tT,onChangesCountChange:tM,fileSearchOpen:tk,onFileSearchOpenChange:tS,showHidden:tA})})]})]}),(0,r.jsx)(nX,{open:null!==rc,anchor:rc?.anchor??null,sheet:eB,ariaLabel:s0,title:h,items:v,cancelLabel:eF("sidebar.cancel"),focusCancel:null!==s1,onClose:sH,returnFocusTo:rc?.opener??null,width:g,children:s1}),(0,r.jsx)(n6,{toast:ry,onDismiss:()=>rw(null),dismissLabel:eF("sidebar.dismiss")})]})}var rc=n(5772);let ru=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,rp=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,rh=/\x1B_pi:c\x07/g;function rf(e){return e.replace(rh,"").replace(ru,"")}function rm(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(rp);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function rg(e,t){let n=rm(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function rx(e){return rm(e)[0]?.char}let rv=/[▀-▟]/,rb={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},ry={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function rw(e){return"custom"===e.role&&!e.display}function rj(e){return"user"===e.role||"custom"===e.role&&!rw(e)&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType||"subagent-notification"===e.customType)}function rk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function rS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!rk(e,t))}function rC(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function rN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function r$(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function rE(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=rS(e,t),r=n.findLastIndex(e=>"text"!==e.type&&"image"!==e.type);return -1===r?{answerBlocks:n,processBlocks:[]}:{answerBlocks:n.slice(r+1),processBlocks:n.slice(0,r+1)}}function rI(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function rM(e){try{return decodeURIComponent(e)}catch{return e}}function rT(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function rR(e){let t=rT(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let l=s.join("/");return n?l:r?`//${l}`:i?`/${l}`:l}function rA(e,t){let n,r,i,s,l,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=rM(a),p=u.startsWith("\\\\"),h=rT(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=rM(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(a))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${rT(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let m=rR(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&o&&(n=rR(m).replace(/\/+$/,""),r=rR(o).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(r))?n.toLowerCase():n,!(s===(l=i?r.toLowerCase():r)||s.startsWith(`${l}/`)))?null:m}let rL=/^page=(\d+)$/i;function rz(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(rL);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function rP(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function rW(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function rO(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function rF(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function rD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rB(e){if(!rD(e)||!rD(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function rH(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let s=0;s<i;s++)e.push({type:"line",left:t[s]??r(),right:n[s]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},gap(){i(),e.length>0&&"gap"!==e[e.length-1].type&&e.push({type:"gap",count:null})},finish(){i(),e.length>0&&"gap"===e[e.length-1].type&&e.pop()}}}function r_(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let s of e.split(/\r?\n/)){let e=s.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let s=e[1]?.toLowerCase()??"update",l=(e[2]??"").trim();n?.finish(),i=s,r={oldPath:"add"===s?void 0:l,newPath:"delete"===s?void 0:l,rows:(n=rH()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(s)){let e=s.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let l=n;if(!s.startsWith("*** ")){if("update"===i&&s.startsWith("@@")){l.gap();continue}if("update"===i){let e=s[0],t=s.slice(1);"+"===e?l.added(t,null):"-"===e?l.removed(t,null):" "===e?l.context(t,null):""!==s&&l.context(s,null)}else if("add"===i){if(""===s)continue;n.added(s.startsWith("+")?s.slice(1):s,null)}else if("delete"===i){if(""===s)continue;n.removed(s.startsWith("-")?s.slice(1):s,null)}}}n?.finish();let s=t.filter(e=>e.rows.length>0);return s.length>0?s:null}function rU(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=rH();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,s]=e,l=Number(i);"+"===r?t.added(s,l):"-"===r?t.removed(s,l):t.context(s,l)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function rq(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function rK(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function rV(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function rZ(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m ${r}s`}function rJ(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
4
4
 
5
5
  ${r}
@@ -8,7 +8,7 @@ ${n}`}var rY=n(32316);function rG(e){if(navigator.clipboard?.writeText)return na
8
8
  ${t}`,x=d&&!s;(0,i.useEffect)(()=>{if(!x)return;let e=!1;return p({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:o?"dark":"default"}),!await r.parse(t,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,s=await r.render(i,t);e||p({key:g,status:"ready",svg:s.svg})})().catch(()=>{e||p({key:g,status:"error"})}),()=>{e=!0}},[t,g,o,x]);let v=(0,i.useMemo)(()=>(0,r.jsx)(sd,{isStreaming:s,previewVisible:x,onToggle:()=>c(e=>!e),title:x?a("i18n.showMermaidSource"):a("i18n.previewMermaid")}),[s,x,a]);if(!x)return(0,r.jsx)(sm,{code:t,lang:"mermaid",headerAction:v,isStreaming:s});let b=u?.key===g&&"error"===u.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:a("i18n.invalidMermaid")}):u?.key!==g||"ready"!==u.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":a("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!h&&(0,r.jsx)("button",{ref:m,type:"button",className:"mermaid-block mermaid-preview-button",title:a("i18n.openMermaidViewer"),"aria-label":a("i18n.openMermaidViewer"),onClick:()=>f(!0),dangerouslySetInnerHTML:{__html:u.svg}}),h&&(0,r.jsx)(sp,{title:a("i18n.mermaidDiagram"),label:a("i18n.mermaidViewer"),onClose:()=>f(!1),children:(0,r.jsx)("div",{dangerouslySetInnerHTML:{__html:u.svg}})})]});return(0,r.jsx)(su,{lang:"mermaid",actions:(0,r.jsxs)(r.Fragment,{children:[u?.key===g&&"ready"===u.status&&(0,r.jsx)(sc,{onClick:()=>{let e=m.current?.querySelector("svg");e&&so(new XMLSerializer().serializeToString(e),"mermaid-diagram.svg")}}),v]}),children:b})}function sd(e){let{isStreaming:t,previewVisible:n,onToggle:i,title:s}=e,{t:l}=(0,e0.s)();return(0,r.jsx)("button",{type:"button",onClick:i,disabled:t,title:t?l("i18n.previewAfterStreaming"):s,className:["markdown-code-action",n?"is-active":""].filter(Boolean).join(" "),children:l(n?"i18n.source":"i18n.preview")})}function sc(e){let{onClick:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${n("i18n.downloadFile")} (SVG)`,"aria-label":`${n("i18n.downloadFile")} (SVG)`,onClick:t,children:"SVG"})}function su(e){let{lang:t,actions:n,children:i}=e;return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t}),(0,r.jsx)("div",{className:"markdown-code-actions",children:n})]}),i]})}function sp(e){let{title:t,label:n,onClose:s,children:l}=e,{t:o}=(0,e0.s)(),a=(0,i.useRef)(null),[d,c]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n,onCancel:e=>{e.preventDefault(),s()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),s())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:t}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>Math.max(.5,e-.25)),disabled:d<=.5,title:o("i18n.zoomOut"),"aria-label":o("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*d),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>Math.min(3,e+.25)),disabled:d>=3,title:o("i18n.zoomIn"),"aria-label":o("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>c(1),title:o("i18n.fitToWidth"),"aria-label":o("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:s,title:o("i18n.close"),"aria-label":o("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&s()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*d}%`},children:l})})]})})}let sh={...iH.xJ,'pre[class*="language-"]':{...iH.xJ['pre[class*="language-"]']}};function sf(e){let{rows:t,stylesheet:n,useInlineStyles:i}=e;return t.map((e,t)=>{let s=e.children??[],l=s[0]?.properties?.className.includes("react-syntax-highlighter-line-number")?s[0]:null,o={...e,properties:{...e.properties,className:[...e.properties?.className??[],"markdown-code-line-text"]},children:l?s.slice(1):s};return(0,r.jsxs)("span",{className:"markdown-code-line",children:[l&&(0,iD.Ay)({node:l,stylesheet:n,useInlineStyles:i,key:"number"}),(0,iD.Ay)({node:o,stylesheet:n,useInlineStyles:i,key:"text"})]},t)})}delete sh['pre[class*="language-"]'].background;let sm=(0,i.memo)(function(e){let{code:t,lang:n,headerAction:s,isStreaming:l}=e,{isDark:o}=i5(),{t:a}=(0,e0.s)(),[d,c]=(0,i.useState)(!1),u=se(),[p,h]=(0,i.useState)(()=>{var e;return!l&&i7()&&(e=t.length,sn||(sn=!0,setTimeout(()=>{st=2e3,sn=!1},0)),!(e>st)&&(st-=e,!0))});return(0,i.useEffect)(()=>{if(!l&&!p&&u){var e;return e=()=>h(!0),sr.push(e),sl(),()=>{let t=sr.indexOf(e);-1!==t&&sr.splice(t,1)}}},[l,p,u]),(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:n||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[s,(0,r.jsx)("button",{onClick:()=>{rG(t).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:a(d?"i18n.copied":"i18n.copy")})]})]}),l?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,whiteSpace:"pre-wrap",overflowWrap:"anywhere",backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:t})}):(0,r.jsx)(iB.A,{language:p&&n||"text",style:o?sh:iH.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",flexShrink:0},renderer:sf,customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,fontWeight:"var(--font-mono-weight)",border:"none",borderRadius:0,backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t})]})}),sg="http://www.w3.org/2000/svg";function sx(e,t){let n=t.parseFromString(e,"image/svg+xml");return n.getElementsByTagName("parsererror").length>0?null:n.documentElement}function sv(e){let{code:t,isStreaming:n}=e,{t:s}=(0,e0.s)(),[l,o]=(0,i.useState)(!0),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),f=l&&!n,m=(0,i.useMemo)(()=>{var e;let n,r;return f&&"u">typeof DOMParser?(e=new DOMParser,r=sx(n=t,e),r?.localName!=="svg"||null!==r.namespaceURI||r.hasAttribute("xmlns")||(r=sx(n=t.replace(/<svg(?=[\s/>])/,`<svg xmlns="${sg}"`),e)),r?.localName==="svg"&&r.namespaceURI===sg?n:null):void 0},[t,f]),g=(0,i.useMemo)(()=>m?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(m)}`:null,[m]),x=(0,i.useMemo)(()=>(0,r.jsx)(sd,{isStreaming:n,previewVisible:f,onToggle:()=>o(e=>!e),title:f?s("i18n.showSvgSource"):s("i18n.previewSvg")}),[n,f,s]);if(!f)return(0,r.jsx)(sm,{code:t,lang:"svg",headerAction:x,isStreaming:n});let v=null!==g&&c!==g,b=e=>(0,r.jsx)("img",{src:g??void 0,alt:s("i18n.svgImage"),className:[e,p===g?"is-unsized":""].filter(Boolean).join(" "),onLoad:e=>{let{naturalWidth:t,naturalHeight:n}=e.currentTarget;t&&n||h(g)},onError:()=>u(g)});return(0,r.jsx)(su,{lang:"svg",actions:(0,r.jsxs)(r.Fragment,{children:[v&&m&&(0,r.jsx)(sc,{onClick:()=>so(m,"image.svg")}),x]}),children:void 0===m?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading"}):v?(0,r.jsxs)(r.Fragment,{children:[!a&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openSvgViewer"),"aria-label":s("i18n.openSvgViewer"),onClick:()=>d(!0),children:b("svg-block-image")}),a&&(0,r.jsx)(sp,{title:s("i18n.svgImage"),label:s("i18n.svgViewer"),onClose:()=>d(!1),children:b("svg-zoom-image")})]}):(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidSvg")})})}let sb=(0,i.createContext)(!1);function sy(e){let{src:t,alt:n,cwd:s,...l}=e,o=(0,i.useContext)(sb);delete l.node;let a="string"==typeof t?t:void 0,d=a?rA(a,s):null,c=d?`/api/files/${tI(d)}?type=read`:a,u=d??a?.split(/[?#]/,1)[0]??"",p=n?.trim()?n:void 0;if(r2(u))return(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:c,"aria-label":p});if(r4(u))return(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:c,"aria-label":p});let h=(0,r.jsx)("img",{src:c,alt:n??"",loading:"lazy",...l});return!c||o?h:(0,r.jsx)(iF,{src:c,alt:n??"",className:"markdown-image",children:h})}function sw(e){let{source:t,children:n}=e,{t:s}=(0,e0.s)(),[l,o]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-math-display",children:[n,(0,r.jsx)("button",{type:"button",onClick:()=>{rG(t).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},className:"markdown-code-action markdown-math-copy",children:s(l?"i18n.copied":"i18n.copy")})]})}let sj=(0,i.memo)(function(e){let{markdown:t,remarkPlugins:n,urlTransform:i,rehypePlugins:s,components:l}=e;return(0,r.jsx)(rY.oz,{remarkPlugins:n,rehypePlugins:s,urlTransform:i,components:l,children:t})}),sk=(0,i.memo)(function(e){let{children:t,className:n,isStreaming:s,cwd:l,onOpenFile:o,onNavigateLink:a,keepLineBreaks:d}=e,c=(0,i.useMemo)(()=>ih(t),[t]),u=(0,i.useMemo)(()=>s?function(e){let t=e.split("\n");if(/^---[ \t]*\r?$/.test(t[0]))return[e];let n=[],r=[],i=null,s=!1,l=!1,o=!1;for(let e of t){let t=""===e.trim();!o||t||i||s||l||!(r.length>0)||/^[ \t]/.test(e)||iP.test(e)||(n.push(r.join("\n")+"\n"),r=[]),r.push(e);let a=e.match(iz);if(a){let e=a[1][0],t=a[1].length;i?e===i.marker&&t>=i.size&&(i=null):i={marker:e,size:t}}else if(!i){let t=e.replace(iO,"");iW.test(t)&&(l=!0),(t.match(/\$\$/g)?.length??0)%2==1&&(s=!s)}o=t}return n.push(r.join("\n")),n}(c):[c],[s,c]),p=(0,i.useMemo)(()=>({code(e){let{className:t,children:n,...i}=e,l=t?.replace("language-","").toLowerCase()??"",o=String(n);return t?.includes("language-")||o.includes("\n")?"mermaid"===l?(0,r.jsx)(sa,{code:o.replace(/\n$/,""),isStreaming:s,defaultPreview:!0}):"svg"===l?(0,r.jsx)(sv,{code:o.replace(/\n$/,""),isStreaming:s}):(0,r.jsx)(sm,{code:o.replace(/\n$/,""),lang:l,isStreaming:s}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:n,...i}=e;if(delete i.node,a&&t&&!id(t)){let e=()=>a(t);return(0,r.jsx)(sb.Provider,{value:!0,children:(0,r.jsx)("a",{...i,role:"link",tabIndex:0,onClick:e,onKeyDown:t=>{"Enter"===t.key&&e()},children:n})})}if(t?.startsWith("#"))return(0,r.jsx)(sb.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:ic,children:n})});let s=o?rA(t,l):null;return s&&o?(0,r.jsx)(sb.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,onClick:e=>{if(!rI(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),o(s,rz(t)??void 0))},children:n})}):(0,r.jsx)(sb.Provider,{value:!0,children:(0,r.jsx)("a",{href:t,...i,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,r.jsx)(sy,{cwd:l,...e}),ol(e){let{node:t,start:n,style:i,...s}=e,l=String(Math.abs((n??1)+Math.max(t?.children.filter(e=>"element"===e.type&&"li"===e.tagName).length??0,1)-1)).length;return(0,r.jsx)("ol",{start:n,style:{...i,"--ol-marker-digits":Math.max(l,2)},...s})},div(e){let{node:t,children:n,...i}=e,s=t?.properties?.dataMathSource;return"string"==typeof s?(0,r.jsx)(sw,{source:s,children:n}):(0,r.jsx)("div",{...i,children:n})},table(e){let{children:t}=e;return(0,r.jsx)("div",{className:"markdown-table-frame",children:(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:t})})})}}),[l,s,o,a]);return(0,r.jsx)("div",{className:["markdown-body",n].filter(Boolean).join(" "),children:u.map((e,t)=>(0,r.jsx)(sj,{markdown:e,remarkPlugins:d?i$:ik,urlTransform:o?ia:io,rehypePlugins:a?iA:iR,components:p},t))})});function sS(e){let{active:t,size:n=14}=e;return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z",stroke:t?"#d4a017":void 0,fill:t?"rgba(250, 204, 21, 0.18)":"none",style:{filter:t?"drop-shadow(0 0 2px rgba(250, 204, 21, 0.35))":"none"}}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]})}let sC=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,sN=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function s$(e){let t,n=[],r=null,i=0,s=0,l=0,o=0,a=null,d=[],c=[],u=()=>({lineNo:null,text:"",type:"empty"}),p=()=>{if(!r){d=[],c=[];return}let e=Math.max(d.length,c.length);for(let t=0;t<e;t++){let e=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"removed"}:u(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:u();r.rows.push({type:"line",left:e,right:n})}d=[],c=[]};for(let u of e.split(/\r?\n/)){if(!(l>0||o>0)){if(u.startsWith("--- ")){p(),t=sM(u.slice(4));continue}if(u.startsWith("+++ ")){p(),r={oldPath:t,newPath:sM(u.slice(4)),rows:[]},n.push(r),a=null;continue}}let e=u.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),p(),i=Number(e[1]),s=Number(e[3]),l=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]);let t=0===l?i+1:i,d=0===o?s+1:s;if(a){let e=t-a.old,n=d-a.new;(e>0||n>0)&&r.rows.push({type:"gap",count:e===n?e:null})}a={old:t+l,new:d+o},r.rows.push({type:"hunk",text:u});continue}if(!r)continue;if(u.startsWith("\\ ")){p(),r.rows.push({type:"hunk",text:u});continue}let h=u[0],f=u.slice(1);" "===h?(p(),r.rows.push({type:"line",left:{lineNo:i++,text:f,type:"context"},right:{lineNo:s++,text:f,type:"context"}}),l>0&&l--,o>0&&o--):"-"===h?(d.push({lineNo:i++,text:f}),l>0&&l--):"+"===h?(c.push({lineNo:s++,text:f}),o>0&&o--):""!==u&&(p(),r.rows.push({type:"hunk",text:u}))}p();let h=n.filter(e=>e.rows.some(e=>"line"===e.type));return h.length>0?h:null}function sE(e){let t=[];for(let n of e.rows)if("hunk"!==n.type){if("gap"===n.type){t.push(n);continue}if("context"===n.left.type&&"context"===n.right.type){t.push({type:"context",text:n.right.text,oldLineNo:n.left.lineNo,newLineNo:n.right.lineNo});continue}"empty"!==n.left.type&&t.push({type:"removed",text:n.left.text,oldLineNo:n.left.lineNo,newLineNo:null}),"empty"!==n.right.type&&t.push({type:"added",text:n.right.text,oldLineNo:null,newLineNo:n.right.lineNo})}return t}function sI(e,t){return 1===e?t("diff.unchangedLine"):t("diff.unchangedLines",{count:e})}function sM(e){return e.split(" ")[0].trim()}let sT=new Set,sR="pi-thinking-expanded",sA="pi-thinking-expanded-changed";function sL(){try{return"true"===window.localStorage.getItem(sR)}catch{return!1}}function sz(e){let{files:t,onOpenFile:n}=e,{t:i}=(0,e0.s)();return 0===t.length?null:(0,r.jsx)("div",{"aria-label":i("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:t.map(e=>{let{filePath:t}=e,s=tM(t);return(0,r.jsxs)("button",{type:"button",title:t,"aria-label":i("chat.openWrittenFile",{name:s}),onClick:()=>n?.(t),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[t$(s,12),(0,r.jsx)("span",{children:s})]},t)})})}let sP="codemode",sW=new Set(["running","ok","error","cancelled"]);function sO(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sF(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function sD(e){if(!sO(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!sO(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&sW.has(e.status)?e.status:"ok",n=sF(e.durationMs),r=sF(e.cost);return{id:"string"==typeof e.id?e.id:"",name:e.name,args:"string"==typeof e.args?e.args:"",status:t,...void 0!==n?{durationMs:n}:{},..."string"==typeof e.error&&e.error?{error:e.error}:{},...void 0!==r&&r>0?{cost:r}:{}}}(e);return t?[t]:[]}),n=sF(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let sB=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function sH(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let s_={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function sU(e){var t;let{call:n}=e,{t:i}=(0,e0.s)(),s=s_[n.status],l=void 0===(t=n.durationMs)?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`;return(0,r.jsxs)("li",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6,minWidth:0},children:[(0,r.jsx)("span",{role:"img","aria-label":i(`codemode.status.${n.status}`),title:i(`codemode.status.${n.status}`),style:{color:s.color,width:12,flexShrink:0,textAlign:"center"},children:s.icon}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontWeight:600,flexShrink:0},children:n.name}),n.args&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n.args}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,marginLeft:"auto",fontVariantNumeric:"tabular-nums"},children:l}),void 0!==n.cost&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:sH(n.cost)})]}),n.error&&(0,r.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function sq(e){let t,{calls:n,omitted:s,isError:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1);if(0===n.length&&0===s)return null;let c=a?0:Math.max(0,n.length-20),u=c>0?n.slice(c):n,p=(t=n.filter(e=>void 0!==e.cost)).length>1?t.reduce((e,t)=>e+(t.cost??0),0):null;return(0,r.jsxs)("div",{style:{borderTop:l?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",background:"var(--bg-subtle)",padding:"6px 10px",fontFamily:"var(--font-mono)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"inherit",fontSize:11},children:o("codemode.calls")}),s>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:o("codemode.omittedCalls",{count:s})}),c>0&&(0,r.jsx)("button",{type:"button",onClick:()=>d(!0),style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",color:"var(--accent)",cursor:"pointer",font:"inherit"},children:o("codemode.showEarlierCalls",{count:c})}),(0,r.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:u.map((e,t)=>(0,r.jsx)(sU,{call:e},e.id||`${c+t}`))}),null!==p&&(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:o("codemode.modelCost",{cost:sH(p)})})]})}var sK=n(9701);let sV=new Map,sZ="transcriptNotices";function sJ(e){if("object"!=typeof e||null===e)return[];let t=e[sZ];return Array.isArray(t)?t:[]}function sY(e){return e<1e3?e.toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${Math.round(e/1e3)}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${Math.round(e/1e6)}M`}let sG="#d97706";function sX(e,t){let n=t>=.01?`$${t.toFixed(2)}`:void 0;return n?e("transcriptNotice.costSuffix",{cost:n}):""}function sQ(e,t){switch(t.kind){case"cache_miss":{let n={tokens:sY(t.missedTokens),cost:sX(e,t.missedCost)};if(t.modelChanged)return e("transcriptNotice.cacheMissModelSwitch",n);if(void 0!==t.idleMinutes)return e("transcriptNotice.cacheMissIdle",{...n,minutes:t.idleMinutes});return e("transcriptNotice.cacheMiss",n)}case"cache_warm":var n;return e("transcriptNotice.cacheWarmed",{note:t.note?e("transcriptNotice.cacheWarmedNote",{note:t.note}):"",cost:(n=t.cost,`$${n.toFixed(6).replace(/(\.\d{3}\d*?)0+$/,"$1")}`)});case"summary_cost":return e("compaction"===t.source?"transcriptNotice.compactionCost":"transcriptNotice.branchSummaryCost",{tokens:sY(t.tokens),cost:sX(e,t.cost)});case"thinking_dropped":return e(1===t.count?"transcriptNotice.thinkingDroppedOne":"transcriptNotice.thinkingDropped",{count:t.count})}}let s0=(0,i.memo)(function(e){let{notices:t}=e,{t:n}=(0,e0.s)(),i=t.filter(e=>"summary_cost"!==e.kind||"compaction"!==e.source);return 0===i.length?null:(0,r.jsx)("div",{className:"transcript-notices",style:{display:"flex",flexDirection:"column",gap:2,margin:"-6px 0 12px"},children:i.map((e,t)=>{let i="cache_warm"!==e.kind;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:12,lineHeight:1.5,color:i?sG:"var(--text-dim)",overflowWrap:"anywhere"},children:[i&&(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:3},children:[(0,r.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsx)("span",{children:sQ(n,e)})]},t)})})}),s1=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function s2(e){let t=0,n=0;for(let r of e)s1.test(r)?t++:n++;return t+n/4}let s4=new Map;function s8(e){let{children:t,className:n,...s}=e,{t:l}=(0,e0.s)(),[o,a]=(0,i.useState)(!1);if(t.length<=1e5)return(0,r.jsx)(sk,{className:n,...s,children:t});if(!o){var d;return(0,r.jsxs)("button",{onClick:()=>a(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",l("i18n.largeMessageReveal",{size:(d=t.length)>=1e6?`${(d/1e6).toFixed(1)} MB`:d>=1e3?`${Math.round(d/1e3)} KB`:`${d} B`})]})}return(0,r.jsx)("div",{className:n,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:t})})}function s3(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}let s5=(0,i.memo)(function(e){let{message:t,isStreaming:n,toolResults:i,modelNames:s,cwd:l,onOpenFile:o,onOpenSubagent:a,entryId:d,searchBlock:c,onFork:u,forking:p,onEditContent:h,onCancelEdit:f,isEditing:m,showTimestamp:g,prevTimestamp:x,sessionId:v,writtenFiles:b,turnDurationMs:y,onCompact:w,isCompacting:j,compactError:k}=e;return"user"===t.role?(0,r.jsx)(s6,{message:t,cwd:l,onOpenFile:o,entryId:d,onFork:u,forking:p,onEditContent:h,onCancelEdit:f,isEditing:m}):"assistant"===t.role?(0,r.jsx)(s9,{message:t,isStreaming:n,toolResults:i,modelNames:s,cwd:l,onOpenFile:o,onOpenSubagent:a,showTimestamp:g,prevTimestamp:x,sessionId:v,entryId:d,searchBlock:c,writtenFiles:b,turnDurationMs:y,onCompact:w,isCompacting:j,compactError:k}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,r.jsx)(lb,{message:t}):(0,r.jsx)(lk,{message:t,cwd:l,onOpenFile:o}):"bashExecution"===t.role?(0,r.jsx)(lz,{message:t,sessionId:v}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSubagent===t.onOpenSubagent&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forking===t.forking&&e.onEditContent===t.onEditContent&&e.onCancelEdit===t.onCancelEdit&&e.isEditing===t.isEditing&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.writtenFiles===t.writtenFiles&&e.turnDurationMs===t.turnDurationMs&&e.sessionId===t.sessionId&&e.onCompact===t.onCompact&&e.isCompacting===t.isCompacting&&e.compactError===t.compactError);function s6(e){let{message:t,cwd:n,onOpenFile:s,entryId:l,onFork:o,forking:a,onEditContent:d,onCancelEdit:c,isEditing:u}=e,{t:p}=(0,e0.s)(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),b=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),y="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),w=t5(b),j=w?.search(/\s/)??-1,k=w?-1===j?w:w.slice(0,j):"",S=w&&-1!==j?w.slice(j+1):"",C=s3(t.timestamp),N=!!l&&!!o,$=w??b,E=w?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(t,w):t,I=y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(iF,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid rgba(59,130,246,0.15)"}})},t)})}),M=!!l&&!!d,T=!!u&&!!c;return(0,r.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:u?"color-mix(in srgb, var(--accent) 14%, var(--user-bg))":"var(--user-bg)",border:u?"1px solid color-mix(in srgb, var(--accent) 62%, var(--user-bg))":"1px solid rgba(59,130,246,0.2)",boxShadow:u?"0 0 0 2px color-mix(in srgb, var(--accent) 16%, transparent)":void 0,borderRadius:12,padding:"8px 12px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:w?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[I,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:p(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),S&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:S})]}),x&&(0,r.jsx)(sk,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:function(e){let t=e.match(t3);if(!t)return null;let n=t[4],r=void 0===n?9:11+n.length;return e.slice(e.indexOf("\n")+1,e.length-r)}(b)??b})]}):(0,r.jsxs)(r.Fragment,{children:[I,b&&(0,r.jsx)(s8,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:s,children:b})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{rG($).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),p(m?"i18n.copied":"i18n.copy")]})}),(N||M||T)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||a||T?1:0,pointerEvents:h||a||T?"auto":"none",transition:"opacity 0.12s"},children:[M&&!T&&(0,r.jsxs)("button",{onClick:()=>d(E,l),title:p("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),p("i18n.editFromHere")]}),T&&(0,r.jsxs)("button",{type:"button",onClick:c,title:p("i18n.cancel"),"aria-label":p("i18n.cancel"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:500,whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})}),p("i18n.cancel")]}),N&&(0,r.jsxs)("button",{onClick:()=>{o(l)},disabled:a,title:p(a?"i18n.creatingSession":"i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-dim)",cursor:a?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{a||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),p(a?"i18n.creating":"i18n.newSession")]})]}),C&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:C})]})]})}function s9(e){var t,n,s,l,o;let a,d,c,u,p,h,{message:f,isStreaming:m,toolResults:g,modelNames:x,cwd:v,onOpenFile:b,onOpenSubagent:y,showTimestamp:w,prevTimestamp:j,sessionId:k,entryId:S,searchBlock:C,writtenFiles:N,turnDurationMs:$,onCompact:E,isCompacting:I,compactError:M}=e,{t:T}=(0,e0.s)(),R=w?s3(f.timestamp):null,A=(0,i.useMemo)(()=>(f.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!rk(t,{isStreaming:m})}),[f.content,m]),L=(0,i.useMemo)(()=>A.map(e=>{let{block:t}=e;return t}),[A]),z=rC(f,{isStreaming:m}),P=rN(f,{isStreaming:m}),W=P&&!r$(f),[O,F]=(0,i.useState)(!1),[D,B]=(0,i.useState)(!1),H=(0,i.useRef)(null),_="number"!=typeof f.timestamp?null:`${f.provider??""}/${f.model??""}@${f.timestamp}`,U=(0,i.useRef)(_);U.current=_;let[q,K]=(0,i.useState)(null),V=(0,i.useRef)(A);V.current=A;let Z=(0,i.useRef)(new Map),J=(0,i.useMemo)(()=>{if(!m)return Z.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of A){let i="text"===n.type?n.text:"thinking"===n.type?n.thinking:"toolCall"===n.type?n.rawInput??JSON.stringify(n.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return s2(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=1/4,s--),i+s2(t.slice(s))}(Z.current.get(r),i);e.set(r,{text:i,tokens:s}),t+=s}return Z.current=e,t},[A,m]),Y=(0,i.useRef)(J);Y.current=J;let G=(0,i.useRef)(new Map),[X,Q]=(0,i.useState)(new Map),ee="assistant"===f.role?lr(f.durationMs):void 0,et=(0,i.useMemo)(()=>{let e=ee??(f.timestamp&&j?f.timestamp-j:void 0);if(void 0===e)return;let t=Math.round(e/1e3);return t>0?t:void 0},[ee,f.timestamp,j]),en=(0,i.useMemo)(()=>{let e=new Map;if(!g)return e;for(let[t,n]of g){let r=lr(n.durationMs)??(n.timestamp&&f.timestamp?n.timestamp-f.timestamp:void 0);void 0!==r&&r>=li&&e.set(t,r)}return e},[g,f.timestamp]),er=L.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ei=f.usage?(s=f.usage,a=[],s.input&&a.push({icon:"up",before:"↑",text:sY(s.input)}),s.output&&a.push({icon:"down",before:"↓",text:sY(s.output)}),s.cacheRead&&a.push({text:`R${sY(s.cacheRead)}`}),s.cacheWrite&&a.push({text:`W${sY(s.cacheWrite)}`}),s.cost?.total&&a.push({text:`$${s.cost.total.toFixed(4)}`}),a):[];if(void 0!==$){let e;ei.length>0&&ei.push({text:"\xb7"});let t=rZ($);ei.push((l=T("chat.turnDuration",{time:t}),o=t,(e=l.indexOf(o))<0?{text:l}:{icon:"clock",before:l.slice(0,e),text:o,after:l.slice(e+o.length)}))}return((0,i.useEffect)(()=>{if(!m){let e=new Date().getTime();Q(t=>{let n=new Map(t);for(let[t,r]of G.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),H.current=null,K(null);return}let e=setInterval(()=>{var e;let t,n=V.current,r=Date.now();n.forEach(e=>{let{originalIndex:t}=e;G.current.has(t)||G.current.set(t,r)}),Q(e=>{let t=!1,i=new Map(e);for(let e=0;e<n.length-1;e++){let s=n[e].originalIndex,l=n[e+1].originalIndex;if(!i.has(s)&&G.current.has(s)){let e=G.current.get(s),n=G.current.get(l)??r;i.set(s,Math.round((n-e)/1e3)),t=!0}}return t?i:e});let i=Y.current;if(0===i)return;H.current??=function(e,t,n){let r=null===e?void 0:sV.get(e);if(r)return r;let i={at:n,tokens:t};return null!==e&&(sV.set(e,i),sV.size>32&&sV.delete(sV.keys().next().value)),i}(U.current,i,r);let s=(e=H.current,(t=(r-e.at)/1e3)>.5?(i-e.tokens)/t:null);null!==s&&K(s)},300);return()=>clearInterval(e)},[m]),0!==L.length||m||z||P)?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":S,style:{marginBottom:16},onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6},children:[f.provider&&(0,r.jsx)("span",{children:(t=f.provider,n=f.model,d=t.toLowerCase(),c=n.toLowerCase(),u=Object.entries(x??{}).flatMap(e=>{let[t,n]=e,r=t.indexOf(":");return r>0&&t.slice(0,r).toLowerCase()===d?[{id:t.slice(r+1).toLowerCase(),name:n}]:[]}),u.find(e=>e.id===c)?.name??u.find(e=>c.endsWith(`/${e.id}`))?.name??Object.entries(x??{}).find(e=>{let[t]=e;return t.toLowerCase()===c})?.[1]??`${t}/${n}`)}),m&&(p=Math.round(J),(0,r.jsx)(r.Fragment,{children:p>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:T("i18n.estimatedTokens"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),p]}),null!==q&&(h=q>=50?"#53b3cb":q>=30?"#9bc53d":q>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:h,color:"#fff",fontSize:11,fontWeight:400},children:[q.toFixed(1)," t/s"]}))]})}))]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:A.map(e=>{let{block:t,originalIndex:n}=e;return(0,r.jsx)(s7,{block:t,searchTarget:t===C,toolResults:g,isStreaming:m,streamingDuration:X.get(n)??("thinking"===t.type?et:void 0),toolCallDurations:en,cwd:v,onOpenFile:b,onOpenSubagent:y,sessionId:k,entryId:S,blockIndex:n},n)})}),z&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(L.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",z]}),P&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:L.length>0||z?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[T(W?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),W&&E&&(0,r.jsx)("button",{type:"button",onClick:E,disabled:I,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:I?"default":"pointer",font:"inherit"},children:T(I?"chat.compacting":"chat.compactContext")}),W&&M&&(0,r.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:M})]}),N&&N.length>0&&(0,r.jsx)(sz,{files:N,onOpenFile:b}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[ei.length>0&&!m&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",columnGap:7,fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:ei.map((e,t)=>(0,r.jsxs)(i.Fragment,{children:[t>0&&" ",(0,r.jsx)(lL,{part:e})]},t))}),er&&!m&&(0,r.jsxs)("button",{onClick:()=>{rG(er).then(()=>{B(!0),setTimeout(()=>B(!1),1500)})},title:T("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:D?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!O,pointerEvents:O?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{D||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{D||(e.currentTarget.style.color="var(--text-dim)")},children:[D?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),T(D?"i18n.copied":"i18n.copy")]}),R&&!m&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:R})]})]}):null}function s7(e){let{block:t,searchTarget:n,toolResults:i,isStreaming:s,streamingDuration:l,toolCallDurations:o,cwd:a,onOpenFile:d,onOpenSubagent:c,sessionId:u,entryId:p,blockIndex:h}=e;if("text"===t.type)return(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":n||void 0,children:(0,r.jsx)(le,{block:t,isStreaming:s,cwd:a,onOpenFile:d})});if("thinking"===t.type)return(0,r.jsx)(ln,{block:t,duration:l,sessionId:u,entryId:p,blockIndex:h});if("toolCall"===t.type){let e=i?.get(t.toolCallId),n=o?.get(t.toolCallId);return(0,r.jsx)(ls,{block:t,result:e,duration:n,onOpenSubagent:c})}return null}function le(e){let{block:t,isStreaming:n,cwd:i,onOpenFile:s}=e;return(0,r.jsx)(s8,{isStreaming:n,cwd:i,onOpenFile:s,children:t.text})}function lt(e){let{text:t}=e,n=(0,i.useMemo)(()=>(function(e){let t=[],n=0;for(;e.length-n>8e3;){let r=n+8e3,i=r+8e3,s=e.slice(r,i+1),l=s.indexOf("\n");for(;l>=0&&/\n\r?$/.test(e.slice(r+l-2,r+l));)l=s.indexOf("\n",l+1);if(l>=0){let i=r+l;if(i===e.length-1)break;t.push({text:e.slice(n,i),lineBreak:!0}),n=i+1}else if(e.length>i){let r=e.charCodeAt(i-1),s=r>=55296&&r<=56319?i-1:i;t.push({text:e.slice(n,s),lineBreak:!1}),n=s}else break}return t.push({text:e.slice(n),lineBreak:!1}),t})(t),[t]);return 1===n.length?t:n.map((e,t)=>(0,r.jsx)("div",{children:e.text},t))}function ln(e){var t;let{block:n,duration:s,sessionId:l,entryId:o,blockIndex:a}=e,{t:d}=(0,e0.s)(),[c,u]=(0,i.useState)(sL),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),v=`${l}:${o}:${a}`,[b,y]=(0,i.useState)(v);b!==v&&(y(v),h(null),m(!1),x(null));let w=(0,i.useRef)(d);w.current=d;let j=(t=n.thinking,t.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>u(sL());return window.addEventListener(sA,e),()=>window.removeEventListener(sA,e)},[]),(0,i.useEffect)(()=>{if(!c||!n.deferred||null!==p)return;if(!l||!o)return void x(w.current("i18n.thinkingUnavailable"));let e=!1;return m(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=s4.get(r);if(i)return s4.delete(r),s4.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw s4.delete(r),e});if(s4.set(r,s),s4.size>100){let e=s4.keys().next().value;e&&s4.delete(e)}return s})(l,o,a).then(t=>{e||(h(t),m(!1))}).catch(t=>{e||(x(t instanceof Error?t.message:String(t)),m(!1))}),()=>{e=!0}},[c,n.deferred,p,l,o,a]),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,minWidth:0,border:"1px solid var(--border)",borderRadius:7,padding:"6px 10px",background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":c,"aria-label":`${d("i18n.thinking")}${j?`: ${j}`:""}`,title:d("i18n.thinking"),onClick:()=>u(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,width:c?14:"100%",flexShrink:+!c,minWidth:0,minHeight:"1.5em",padding:0,background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)(sS,{active:c}),!c&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j?(0,r.jsx)(rY.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:j}):"..."})]}),c&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:f?d("i18n.loadingThinking"):g??(0,r.jsx)(lt,{text:(n.deferred?p:n.thinking)??""})}),void 0!==s&&(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[s,"s"]})]})}function lr(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}let li=100;function ls(e){var t,n,s,l;let o,{block:a,result:d,duration:c,onOpenSubagent:u}=e,{t:p}=(0,e0.s)(),[h,f]=(0,i.useState)(()=>{var e;return void 0!==(e=a.toolCallId)&&sT.has(e)}),m=function(e){if(void 0!==e.rawInput||!rP(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>l$.has(e))?t:null}(a),g=m??(s=a).rawInput??JSON.stringify(s.input,null,2),x=void 0!==a.rawInput,v=rW(a.toolName),b=d&&!d.isError?function(e){let t=e.details;if(!lg(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(d):null,y=b?.text,w=(0,i.useMemo)(()=>(function(e){if(!e)return null;let t=s$(e);return t?.length===1&&lu(t[0])||null})(y),[y]),j=function(e,t){if(!rO(e.toolName))return null;let n=r_(rF(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(lg(r)){let e=rU(r.preview);if(e)return e}return null}(a,d),k=rO(a.toolName)?0===(o=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(rF((l=a).input,l.rawInput))).length?null:o.join(", ").slice(0,120):null,S=a.toolName!==sP||x?null:sO(t=a.input)&&"string"==typeof t.code?t.code:null,C=null===S?null:{code:S,...sD(d?.details)},N=null!==C&&void 0!==d&&0===d.content.length,$=h&&null===m&&null===C&&null===j?function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let t=Object.entries(e);if(0===t.length)return null;let n=[];for(let[e,r]of t){if(null!==r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)return null;let t=null===r?"null":String(r);n.push({key:e,value:""===t?"(empty)":t,multiline:t.includes("\n")})}return n}(x?(0,sK.o2)(a.rawInput):a.input):null,E=function(e,t){if(!e.startsWith("mcp__")||!("object"==typeof t&&null!==t&&!Array.isArray(t)))return null;let{server:n,tool:r}=t;return"string"==typeof n&&"string"==typeof r&&n&&r?{server:n,tool:r}:null}(a.toolName,d?.details),I=d?C?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&sB.test(t.text)?n:[...e]}(d.content):d.content:[],M=d?I.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,T=E&&null!==M?function(e){let t=e.trim();if(t.length>2e5||!/^[[{]/.test(t))return e;try{return JSON.stringify(JSON.parse(t),null,2)}catch{return e}}(M):M,R=lC(I),A=null!==T&&("(no output)"===T.trim()||""===T.trim()),L=(d?.isError??!1)||rO(a.toolName)&&rB(d?.details),z=(n=d?.details)&&"object"==typeof n&&"pi-web-subagent"===n.kind&&"string"==typeof n.sessionId?d.details:null,P=C?C.calls.length+C.omitted:0;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:L?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:L?"rgba(248,113,113,0.05)":"rgba(34,197,94,0.04)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{onClick:()=>{var e;let t=!h;e=a.toolCallId,e&&(t?sT.add(e):sT.delete(e)),f(t)},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[(0,r.jsx)("span",{title:E?a.toolName:void 0,style:{color:L?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:E?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{style:{fontWeight:500,opacity:.75},children:[E.server,"/"]}),E.tool]}):a.toolName}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:x?p("chat.generatingToolInput"):k??(C?function(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(e&&!e.startsWith("// @options:"))return e}return""}(C.code):function(e,t){let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);return 0===r.length?"":"command"in n?String(n.command).slice(0,120):"path"in n?String(n.path).slice(0,120):"file_path"in n?String(n.file_path).slice(0,120):t?t.slice(0,120):"pattern"in n?String(n.pattern).slice(0,120):"query"in n?String(n.query).slice(0,120):String(n[r[0]]).slice(0,120)}(a,w))}),P>0&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===P?p("codemode.callCountOne"):p("codemode.callCount",{count:P})}),void 0!==c&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:function(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),i=n%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m ${i}s`}(c)}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:h?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),z&&u&&(0,r.jsx)("button",{type:"button",onClick:()=>u(z.sessionId,z.description||z.profile),title:p("subagent.openTab"),"aria-label":p("subagent.openTab"),style:{width:32,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})]}),h&&(x||!v)&&!j&&($?(0,r.jsx)("div",{style:{padding:"6px 10px 8px",background:"var(--bg-subtle)",borderTop:L?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)"},children:(0,r.jsx)(lT,{fields:$})}):(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:L?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:C?C.code.replace(/\r/g,"").trimEnd():g})),h&&C&&(0,r.jsx)(sq,{calls:C.calls,omitted:C.omitted,isError:L}),R.length>0&&(0,r.jsx)(lx,{images:R,isError:L}),h&&j&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(la,{files:j})}),h&&d&&j&&L&&(0,r.jsx)(lv,{text:T??"",isEmpty:A,isError:L}),h&&d&&!j&&!N&&(b?(0,r.jsx)(ll,{diff:b}):(!A||0===R.length)&&(0,r.jsx)(lv,{text:T??"",isEmpty:A,isError:L}))]})}function ll(e){let{diff:t}=e;return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(lo,{text:t.text})})}function lo(e){let{text:t}=e,n=(0,i.useMemo)(()=>s$(t),[t]);return n?(0,r.jsx)(la,{files:n}):(0,r.jsx)(lm,{text:t})}function la(e){let{files:t}=e,n=te()?"stacked":"split";return(0,r.jsx)(ld,{files:t,layout:n})}function ld(e){let{files:t,layout:n}=e,{t:i}=(0,e0.s)(),s=t.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:t.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===t?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[s&&"split"===n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(lh,{title:e.oldPath||i("i18n.before"),side:"left"}),(0,r.jsx)(lh,{title:e.newPath||i("i18n.after"),side:"right"})]}),s&&"stacked"===n&&lu(e)&&(0,r.jsx)("div",{title:lu(e),style:{position:"sticky",top:0,zIndex:1,padding:"5px 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:lu(e)}),"split"===n&&(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:"gap"===e.type?(0,r.jsx)(lc,{gap:e},t):(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(lf,{cell:e.left,side:"left"}),(0,r.jsx)(lf,{cell:e.right,side:"right"})]},t))}),"stacked"===n&&sE(e).map((e,t)=>"gap"===e.type?(0,r.jsx)(lc,{gap:e},t):(0,r.jsx)(lp,{line:e},t))]},t))})}function lc(e){let{gap:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)("div",{style:{gridColumn:"1 / -1",padding:"0 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",userSelect:"none"},children:null===t.count?"⋯":`⋯ ${sI(t.count,n)}`})}function lu(e){return e.newPath&&"/dev/null"!==e.newPath?e.newPath:e.oldPath||e.newPath||""}function lp(e){let{line:t}=e;return(0,r.jsx)(lf,{side:"right",cell:{lineNo:"removed"===t.type?t.oldLineNo:t.newLineNo,text:t.text,type:t.type}})}function lh(e){let{title:t,side:n}=e;return(0,r.jsx)("div",{title:t,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===n?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})}function lf(e){let{cell:t,side:n}=e,i="added"===t.type?"rgba(34,197,94,0.12)":"removed"===t.type?"rgba(248,113,113,0.13)":"empty"===t.type?"var(--bg-subtle)":"transparent",s="added"===t.type?"+":"removed"===t.type?"-":" ",l="added"===t.type?"#22c55e":"removed"===t.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:i,borderRight:"left"===n?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:t.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:l,userSelect:"none",fontWeight:"context"===t.type||"empty"===t.type?400:700,flexShrink:0},children:s}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===t.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.text||"\xa0"})]})}function lm(e){let{text:t}=e,n=t.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:n.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function lg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function lx(e){let{images:t,isError:n}=e;return(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)",borderTop:`1px solid ${n?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:t.map((e,t)=>{let n=lN(e);return n?(0,r.jsx)(iF,{src:n,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:n,alt:"",loading:"lazy",style:{display:"block",maxWidth:"min(100%, 720px)",maxHeight:520,borderRadius:6,objectFit:"contain",border:"1px solid var(--border)"}})},`${n}-${t}`):null})})}function lv(e){let{text:t,isEmpty:n,isError:i}=e,{t:s}=(0,e0.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${i?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:i?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?s("i18n.noOutput"):t})})}function lb(e){let{message:t}=e,{t:n}=(0,e0.s)(),[s,l]=(0,i.useState)(!1),o=lS(t.content),a=s3(t.timestamp),d=t.details?.tokensBefore,c=sJ(t).find(e=>"summary_cost"===e.kind&&"compaction"===e.source);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":s,title:n(s?"i18n.collapse":"i18n.expand"),onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:0,border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:4,color:"var(--text-muted)",transform:s?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),"number"==typeof d&&Number.isFinite(d)&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactedFromTokens",{tokens:d.toLocaleString()})}),c&&(0,r.jsx)("span",{style:{display:"block",marginTop:2,color:sG,fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:sQ(n,c)})]})]}),s&&(0,r.jsx)(ly,{summary:o})]})]})})}function ly(e){let{summary:t}=e,{t:n}=(0,e0.s)(),s=(0,i.useMemo)(()=>{let e,n,r,i,s;return e=[],n=[],r=t.match(sN),i=r?.[1]??"",s=r?.index===void 0?t:t.slice(0,r.index),i.replace(sC,(t,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):n.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:n}},[t]);return(0,r.jsxs)("div",{style:{marginTop:10},children:[(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactionDescription")}),s.body?(0,r.jsx)(sk,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:n("i18n.noSummary")}),(0,r.jsx)(lw,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})}function lw(e){let{readFiles:t,modifiedFiles:n}=e,{t:i}=(0,e0.s)();if(0===t.length+n.length)return null;let s=[];return t.length>0&&s.push(`${t.length} read`),n.length>0&&s.push(`${n.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:i("i18n.fileContext",{details:s.join(", ")})}),n.length>0&&(0,r.jsx)(lj,{title:i("i18n.modifiedFiles"),files:n}),t.length>0&&(0,r.jsx)(lj,{title:i("i18n.readFiles"),files:t})]})}function lj(e){let{title:t,files:n}=e;return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:t}),(0,r.jsx)("ul",{className:"compaction-file-list",children:n.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function lk(e){let{message:t,cwd:n,onOpenFile:s}=e,{t:l}=(0,e0.s)(),[o,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=lS(t.content),f=lC(t.content),m=void 0!==t.details,g=m?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(t.details):"",x=t.customType||"extension",v=s3(t.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:o?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:(0,r.jsxs)("button",{type:"button",onClick:()=>a(e=>!e),"aria-expanded":o,title:l(o?"i18n.collapse":"i18n.expand"),style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1,padding:0,border:"none",background:"none",color:"inherit",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650,flexShrink:0},children:x}),!o&&h&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.slice(0,300).replace(/\s+/g," ").trim()}),v&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,flexShrink:0},children:v}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:o?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),o&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[f.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!h},children:f.map((e,t)=>{let n=lN(e);return n?(0,r.jsx)(iF,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),h?(0,r.jsx)(sk,{className:"markdown-custom-message",cwd:n,onOpenFile:s,children:h}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[h||g?(0,r.jsx)("button",{onClick:()=>{rG(h||g).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:u?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(u?"i18n.copied":"i18n.copy")}):null,m&&(0,r.jsx)("button",{onClick:()=>c(e=>!e),style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(d?"i18n.hideDetails":"i18n.showDetails")})]}),m&&d&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:g})]})]})})}function lS(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function lC(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function lN(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}let l$=new Set(["path","file_path","content"]),lE={padding:"4px 12px 4px 0",color:"var(--text-dim)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",whiteSpace:"nowrap",verticalAlign:"top"},lI={padding:"4px 0",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},lM={margin:0,padding:"8px 10px",maxHeight:260,overflow:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",font:"inherit",lineHeight:1.5,whiteSpace:"pre-wrap"};function lT(e){let{fields:t}=e;return(0,r.jsx)("table",{style:{borderCollapse:"collapse"},children:(0,r.jsx)("tbody",{children:t.map(e=>(0,r.jsxs)("tr",{children:[(0,r.jsx)("td",{style:lE,children:e.key}),(0,r.jsx)("td",{style:lI,children:e.multiline?(0,r.jsx)("pre",{style:lM,children:e.value}):e.value})]},e.key))})})}let lR={up:"M6 10.5V1.5M2.5 5 6 1.5 9.5 5",down:"M6 1.5v9M2.5 7 6 10.5 9.5 7",clock:"M6 1.25a4.75 4.75 0 1 0 0 9.5 4.75 4.75 0 1 0 0-9.5M6 3.5V6l1.75 1"},lA={fontSize:0};function lL(e){let{part:t}=e;return t.icon?(0,r.jsxs)("span",{children:[t.before&&(0,r.jsx)("span",{style:lA,children:t.before}),(0,r.jsx)("svg",{width:"clock"===t.icon?10:9,height:"clock"===t.icon?10:9,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,style:{display:"inline",verticalAlign:"clock"===t.icon?"-0.1em":"-0.05em",marginRight:"clock"===t.icon?3:1},children:(0,r.jsx)("path",{d:lR[t.icon]})}),t.text,t.after&&(0,r.jsx)("span",{style:lA,children:t.after})]}):(0,r.jsx)("span",{children:t.text})}function lz(e){let{message:t,sessionId:n}=e,{t:s}=(0,e0.s)(),[l,o]=(0,i.useState)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),p=!t.output&&void 0===t.exitCode&&!t.cancelled,h=t.cancelled||void 0!==t.exitCode&&0!==t.exitCode,f=n&&t.fullOutputPath?`/api/agent/${encodeURIComponent(n)}/bash-output?path=${encodeURIComponent(t.fullOutputPath)}`:null,m=t.truncated&&f&&null===l,g=l??t.output;async function x(){if(f){d(!0),u(null);try{let e=await fetch(f),t=await e.json();t.success?o(t.data?.output??""):u(t.error??"failed")}catch(e){u(String(e))}finally{d(!1)}}}let v=t.excludeFromContext?"bash (local)":"bash",b={type:"toolCall",toolCallId:`bash-${t.timestamp??""}`,toolName:v,input:{command:t.command}},y=p?void 0:{role:"toolResult",toolCallId:b.toolCallId,toolName:v,content:g?[{type:"text",text:g}]:[],isError:h,timestamp:t.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(ls,{block:b,result:y}),t.truncated&&f&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[m&&(0,r.jsx)("button",{onClick:x,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s(a?"chat.loadingFullOutput":"chat.viewFullOutput")}),(0,r.jsx)("a",{href:`${f}&download=1`,style:{marginLeft:10*!!m,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:s("chat.downloadFullOutput")}),c&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",c,")"]})]})]})}function lP(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let lW=new Map;function lO(e){return`parked-new:${e}`}function lF(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function lD(e){return!e.value&&0===e.images.length}function lB(e){let t=lW.get(e);return t?lF(t):null}function lH(e,t){lD(t)?lW.delete(e):lW.set(e,lF(t))}function l_(e){lW.delete(e)}function lU(e,t){return e.trim()?t.trim()?`${e}
9
9
 
10
10
  ${t}`:e:t}function lq(e,t,n,r){let i=[...t??[],...r].filter(lP).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:lU(e,n),images:i}}function lK(e,t,n){let r=lB(e)??{value:"",images:[]},i=lq(t,n,r.value,r.images);return lH(e,i),i}function lV(e,t,n){if(e===t)return n?lF(n):lB(t);let r=lB(e),i=n&&!lD(n)?lF(n):r??(n?lF(n):null),s=lB(t);if(l_(e),!i)return s;let l=s?lq(s.value,s.images,i.value,i.images):i;return lH(t,l),lF(l)}let lZ=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,lJ=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,lY=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,lG=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,lX=/^[ \t]{0,3}(`{3,}|~{3,})/;function lQ(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function l0(e){return"/mcp"===e.trim()}let l1="pi-enter-send-mode",l2="enter",l4=null,l8=new Set;function l3(){return null===l4&&(l4=function(){try{let e=window.localStorage.getItem(l1);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return l2}}()),l4}function l5(e){return l8.add(e),()=>{l8.delete(e)}}function l6(e){l4=e;try{window.localStorage.setItem(l1,e)}catch{}l8.forEach(e=>e())}function l9(){return(0,i.useSyncExternalStore)(l5,l3,()=>l2)}let l7="pi-chat-content-width",oe="pi-chat-content-font-size",ot={width:820,fontSize:14},on=null,or=new Set;function oi(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function os(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function ol(e){try{return window.localStorage.getItem(e)}catch{return null}}function oo(e){let{width:t,fontSize:n}=e;"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${t}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${n}px`))}function oa(){return on||oo(on={width:oi(ol(l7)),fontSize:os(ol(oe))}),on}function od(e){return or.add(e),()=>{or.delete(e)}}function oc(e,t){let n="width"===e?oi(t):os(t);oo(on={...oa(),[e]:n});try{window.localStorage.setItem("width"===e?l7:oe,String(n))}catch{}or.forEach(e=>e())}let ou=e=>oc("width",e),op=e=>oc("fontSize",e);function oh(){return{...(0,i.useSyncExternalStore)(od,oa,()=>ot),setWidth:ou,setFontSize:op}}let of=[{value:100,label:"settings.fontWeightThin"},{value:200,label:"settings.fontWeightExtraLight"},{value:300,label:"settings.fontWeightLight"},{value:400,label:"settings.fontWeightRegular"},{value:500,label:"settings.fontWeightMedium"},{value:600,label:"settings.fontWeightSemiBold"}],om={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},og={ui:"",mono:"",uiWeight:400,monoWeight:400};function ox(e){let t="string"==typeof e?Number(e):e;return of.find(e=>e.value===t)?.value??400}function ov(e){return"string"==typeof e&&e.length<=500?e:""}let ob=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),oy=["ui","mono"],ow=Object.keys(om),oj=null,ok=new Set;function oS(){let e={...og};for(let t of oy)try{e[t]=ov(window.localStorage.getItem(om[t]));let n=`${t}Weight`;e[n]=ox(window.localStorage.getItem(om[n]))}catch{}return e}function oC(e){for(let t of oy){let n=`--font-${t}`,r=function(e,t){let n=ov(t).split(",").flatMap(e=>{let t=e.trim().replace(/\s+/g," "),n=t.length>=2&&('"'===t[0]||"'"===t[0])&&t.endsWith(t[0]);return(n&&(t=t.slice(1,-1).trim()),t)?[!n&&ob.has(t.toLowerCase())?t.toLowerCase():JSON.stringify(t)]:[]}).join(", ");return n?`${n}, var(--font-${e}-default)`:""}(t,e[t]);r?document.documentElement.style.setProperty(n,r):document.documentElement.style.removeProperty(n);let i=e[`${t}Weight`];400===i?document.documentElement.style.removeProperty(`${n}-weight`):document.documentElement.style.setProperty(`${n}-weight`,String(i))}}function oN(){return oj||oC(oj=oS()),oj}function o$(){ok.forEach(e=>e())}function oE(e){if(null!==e.key&&!Object.values(om).includes(e.key))return;let t=oS(),n=oN();ow.every(e=>t[e]===n[e])||(oj=t,oC(t),o$())}function oI(e){return 0===ok.size&&window.addEventListener("storage",oE),ok.add(e),oN(),()=>{ok.delete(e),0===ok.size&&window.removeEventListener("storage",oE)}}function oM(e){let t=oN(),n=ow.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(oj=e,oC(e),n))try{e[t]===og[t]?window.localStorage.removeItem(om[t]):window.localStorage.setItem(om[t],String(e[t]))}catch{}o$()}}function oT(e,t){oM({...oN(),[e]:ov(t)})}function oR(e,t){oM({...oN(),[`${e}Weight`]:ox(t)})}function oA(e){oM({...oN(),[e]:"",[`${e}Weight`]:400})}function oL(){return{...(0,i.useSyncExternalStore)(oI,oN,()=>og),setFontPreference:oT,setFontWeight:oR,resetFontPreference:oA}}function oz(e){let{filled:t,size:n}=e;return(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:t?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:(0,r.jsx)("polygon",{points:"12 2.5 14.9 8.6 21.5 9.4 16.6 13.9 17.9 20.5 12 17.2 6.1 20.5 7.4 13.9 2.5 9.4 9.1 8.6"})})}function oP(e){let{active:t,onSelect:n,star:s,gutter:l=!!s,children:o}=e,a=te(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),f=h&&(d||u||a);return(0,r.jsxs)("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>p(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||p(!1)},style:{position:"relative",background:t?"var(--bg-selected)":d?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:l?"7px 36px 7px 12px":"7px 12px",border:"none",background:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),o]}),s?.isDefault&&(0,r.jsx)("span",{role:"img","aria-label":s.defaultLabel,title:s.defaultLabel,style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,color:"var(--text-dim)"},children:(0,r.jsx)(oz,{filled:!0,size:10})}),s&&h&&(0,r.jsx)("button",{type:"button",title:s.saveLabel,"aria-label":s.saveLabel,tabIndex:f?0:-1,onClick:e=>{e.stopPropagation(),s.onSave()},style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",opacity:+!!f,pointerEvents:f?"auto":"none",transition:"opacity 0.1s, background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsx)(oz,{filled:!1,size:12})})]})}function oW(e){let t,n,s,l,o,a,d,c,u,p,h,{options:f,value:m,onChange:g,onReselect:x,onClear:v,emptyLabel:b,selectedLabel:y,disabled:w=!1,busy:j=!1,isAutoSelection:k=!1,ariaLabel:S,variant:C="toolbar",placement:N="up",defaultValue:$,onSetDefault:E}=e,{t:I}=(0,e0.s)(),M=te(),T=(0,i.useRef)(null),R=(0,i.useRef)(null),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(""),F=w||j,D=(t=W.trim().toLocaleLowerCase())?f.filter(e=>`${e.name} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(t)):f,B=f.length>8,H=[];for(let e of D){let t=H.find(t=>t.provider===e.provider);t?t.options.push(e):H.push({provider:e.provider,options:[e]})}let _=y??(m?f.find(e=>e.modelId===m.modelId&&e.provider===m.provider)?.name??m.modelId:b??(f.length>0?"Select model":"No models"));(0,i.useEffect)(()=>{let e=e=>{T.current&&!T.current.contains(e.target)&&R.current&&!R.current.contains(e.target)&&(L(!1),O(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!A)return;let e=()=>{let e=T.current?.querySelector("button")?.getBoundingClientRect();e?.height&&P({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},t=window.visualViewport,n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-keyboard-open"]}),window.addEventListener("resize",e),t?.addEventListener("resize",e),t?.addEventListener("scroll",e),()=>{n.disconnect(),window.removeEventListener("resize",e),t?.removeEventListener("resize",e),t?.removeEventListener("scroll",e)}},[A]),(0,i.useEffect)(()=>{F&&(L(!1),O(""))},[F]);let U="field"===C?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:5,background:F?"var(--bg-panel)":"var(--bg)",color:F?"var(--text-dim)":"var(--text)",cursor:F?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:M?"flex-start":void 0,gap:6,width:M?"100%":void 0,maxWidth:M?"100%":220,height:32,padding:M?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:A?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:F?"not-allowed":"pointer",fontSize:12,opacity:F?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:T,className:`model-selector is-${C}${F?" is-disabled":""}`,style:{position:"relative",width:"field"===C||M?"100%":void 0,minWidth:0,flex:"toolbar"===C&&M?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&A&&(e.preventDefault(),e.stopPropagation(),O(""),L(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":S,"aria-haspopup":"listbox","aria-expanded":A,"aria-busy":j||void 0,disabled:F,title:j?"Switching model":F?_:f.length>0||v?"Change model":"No available models",style:U,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();P({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),L(e=>(e&&O(""),!e))},onMouseEnter:e=>{F||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(F){e.currentTarget.style.background="field"===C?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===C?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=A?"var(--bg-hover)":"field"===C?"var(--bg)":"none",e.currentTarget.style.color="field"===C?"var(--text)":"var(--text-muted)"},children:[j?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_}),"field"===C&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),A&&z&&(n=window.visualViewport?.offsetTop??0,s=window.visualViewport?.height??window.innerHeight,l=window.visualViewport?.width??window.innerWidth,a=(o=Math.min(z.top-6,n+s-8))-n-8,d=n+s-z.bottom-6-8,u=Math.max(120,Math.min((c="up"===N||a>d)?a:d,.6*s)),p=c?{top:o,transform:"translateY(-100%)"}:{top:z.bottom+6},h=M?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:z.left,width:"max-content",minWidth:z.width,maxWidth:Math.max(z.width,l-z.left-8)},(0,r.jsxs)("div",{ref:R,role:"listbox","aria-label":S,style:{position:"fixed",...p,...h,zIndex:500,display:"flex",flexDirection:"column",maxHeight:u,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:c?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[B&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:W,onChange:e=>O(e.target.value),placeholder:I("chat.filterModels"),"aria-label":I("chat.filterModels"),autoFocus:!M,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!M,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[v&&!W.trim()&&(0,r.jsx)(oP,{active:!m,gutter:!!E,onSelect:()=>{L(!1),O(""),v()},children:(0,r.jsx)(oO,{label:b??"Default"})}),0===H.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:W.trim()?I("chat.noMatchingModels"):"No available models"}):H.map((e,t)=>(0,r.jsxs)("div",{children:[H.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",borderTop:t>0||v?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:"uppercase"},children:e.provider}),e.options.map(e=>(0,r.jsx)(oP,{active:e.modelId===m?.modelId&&e.provider===m?.provider,onSelect:()=>{let t;return t=e.modelId===m?.modelId&&e.provider===m?.provider,void(L(!1),O(""),!t||k?g(e.provider,e.modelId):x?.(e.provider,e.modelId))},star:E?{isDefault:e.modelId===$?.modelId&&e.provider===$?.provider,saveLabel:I("chat.saveDefaultModel"),defaultLabel:I("chat.defaultModel"),onSave:()=>{L(!1),O(""),E?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(oO,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function oO(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let oF=["configured","chat-only","read-only","default","full"],oD={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},oB=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function oH(e,t,n){return t<=0?0:((e+n)%t+t)%t}function o_(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function oU(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,l=e.selectionEnd;if(e.focus(),s===l&&t<=s&&n>=l){let i=e.value.length-(n-t)+r.length;for(let n=s-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-l;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else o_(e,t,e.selectionStart+(n-l),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||o_(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function oq(e){e.style.height="auto",e.style.height=`${e.value?Math.min(e.scrollHeight,200):e.clientHeight}px`,e.style.overflowY=e.value&&e.scrollHeight>e.clientHeight?"auto":"hidden"}function oK(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,l=s?.parentElement,o="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&o?.observe(s),l&&o?.observe(l);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{o?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let oV=["auto","off","minimal","low","medium","high","xhigh","max"],oZ={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"};function oJ(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let oY=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"}];function oG(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return oY.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let oX=["builtin","extension","prompt","skill"],oQ={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},o0={builtin:0,extension:1,prompt:2,skill:3};function o1(e,t){return"builtin"===e.source?t(e.description):e.description??""}function o2(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function o4(e){return{data:e.data,mimeType:e.mimeType}}function o8(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function o3(e){return(e??[]).filter(lP).slice(0,10).map(o8)}function o5(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function o6(e){let{kind:t,text:n}=e;return(0,r.jsxs)("div",{title:n,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:`1px solid ${"steer"===t?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===t?"var(--accent)":"var(--text-dim)"},children:t}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]})}function o9(e){let{tone:t,title:n,body:i,onClose:s}=e,{t:l}=(0,e0.s)(),o="error"===t?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${o},0.3)`,borderRadius:6,background:`rgba(${o},0.07)`,color:`rgb(${o})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:n}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:i})]}),s&&(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":l("sidebar.dismiss"),style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function o7(e){let{cwd:t}=e,{t:n}=(0,e0.s)();return t?(0,r.jsx)(o9,{tone:"error",title:n("chat.cwdMissingTitle"),body:n("chat.cwdMissingBody",{cwd:t})}):null}function ae(e){let{error:t}=e,{t:n}=(0,e0.s)();return t?(0,r.jsx)(o9,{tone:"error",title:n("chat.modelError"),body:t}):null}function at(e){let{warnings:t}=e,{t:n}=(0,e0.s)();return t&&0!==t.length?(0,r.jsx)(o9,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let an=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,l,o,a,d,c,{onSend:u,onAbort:p,onSteer:h,onFollowUp:f,isStreaming:m,model:g,isAutoModelSelection:x,modelNames:v,modelList:b,modelError:y,missingCwd:w,modelScopeWarnings:j,onModelChange:k,modelSwitching:S,defaultModel:C,onSetDefaultModel:N,onCompact:$,onAbortCompaction:E,isCompacting:I,compactError:M,onDismissCompactError:T,compactResult:R,toolPreset:A,onToolPresetChange:L,thinkingLevel:z,isAutoThinkingSelection:P=!1,onThinkingLevelChange:W,availableThinkingLevels:O,thinkingLevelMap:F,savedDefaultThinkingLevel:D,onSetDefaultThinkingLevel:B,retryInfo:H,queuedMessages:_,inputHistory:U=[],onRecallQueue:q,slashCommands:K,slashCommandsLoading:V,onLoadSlashCommands:Z,onBuiltinCommand:J,soundEnabled:Y,onSoundToggle:G,onAudioUnlock:X,onPromptWithStreamingBehavior:Q,draftKey:ee,cwd:et,onAttachFiles:en,compact:er=!1}=e,{t:ei}=(0,e0.s)(),{fontSize:es}=oh(),{ui:el,uiWeight:eo}=oL(),ea=te(),ed=l9(),[ec,eu]=(0,i.useState)(()=>ee?lB(ee)?.value??"":""),[ep,eh]=(0,i.useState)(!1),[ef,em]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),[ev,eb]=(0,i.useState)(()=>ee?o3(lB(ee)?.images):[]),ey=ec.trimStart(),ew=0===ev.length&&ey.startsWith("!"),ej=ew&&ey.startsWith("!!"),[ek,eS]=(0,i.useState)(!1),[eC,eN]=(0,i.useState)(0),[e$,eE]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(null),[eT,eR]=(0,i.useState)(!1),[eA,eL]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(0),[eW,eO]=(0,i.useState)(!1),[eF,eD]=(0,i.useState)(!1),[eB,eH]=(0,i.useState)(0),[e_,eU]=(0,i.useState)(!1),eq=(0,i.useRef)(!1),[eK,eV]=(0,i.useState)(null),[eZ,eJ]=(0,i.useState)(!1),[eY,eG]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(null),e1=et&&eX?.cwd===et?eX.values:{},e2=(0,i.useRef)(null),e4=(0,i.useRef)(null),e8=(0,i.useRef)(null),e3=(0,i.useRef)(null),e5=(0,i.useRef)(null),e6=(0,i.useRef)(null),e9=(0,i.useRef)(!1),e7=(0,i.useRef)(0),tt=(0,i.useRef)(!1),tn=(0,i.useRef)(null),tr=(0,i.useRef)([]),ti=(0,i.useRef)(null),ts=(0,i.useRef)([]),tl=(0,i.useRef)([]),to=(0,i.useRef)(null),ta=(0,i.useRef)(null),td=(0,i.useRef)(ee),tc=(0,i.useRef)(ec),tu=(0,i.useRef)(ev),tp=(0,i.useRef)(0);tc.current=ec,tu.current=ev,(0,i.useImperativeHandle)(t,()=>({insertIfEmpty(e){let t=e2.current;(t?t.value:ec).trim()||(tc.current=e,eu(e),eM(null),requestAnimationFrame(()=>{t&&(t.focus(),oq(t))}))},replaceMessage(e){var t,n,r;let i=e2.current;if(t=i?i.value:ec,n=tu.current.length,r=tp.current,t.trim()||0!==n||0!==r)return;let s="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),l=o3("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return lP(r)?[r]:[]}));tc.current=s,tu.current=l,eu(s),eM(null),eD(!1),eb(e=>(e.forEach(o5),l)),requestAnimationFrame(()=>{i&&(i.focus(),oq(i))})},prependText(e){if(!e.trim())return;let t=e2.current,n=[e,t?t.value:ec].filter(e=>e.trim()).join("\n\n");tc.current=n,eu(n),eM(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),oq(t))})},rekeyDraft(e,t){if(e===t)return;if(td.current!==e)return void lV(e,t);let n={value:tc.current,images:tu.current.map(o4)},r=lV(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(td.current=t,i)return;let s=o3(r.images);tc.current=r.value,tu.current=s,eu(r.value),eb(e=>(e.forEach(o5),s)),eM(null),eD(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=td.current,i=n??r,s=i===r,l=!s&&i?lB(i):null,o=lq(e,t,s?tc.current:l?.value??"",s?tu.current.map(o4):l?.images??[]);if(i&&lH(i,o),!s)return;let a=t?.length?[...o3(t).slice(0,Math.max(0,10-tu.current.length)),...tu.current].slice(0,10):tu.current;tc.current=o.value,tu.current=a,eu(t=>{let n=lU(e,t);return tc.current=n,n}),eM(null),eD(!1),t?.length&&eb(e=>{let n=Math.max(0,10-e.length),r=o3(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tu.current=i,i}),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),oq(e))})},focus(){let e=e2.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=e2.current;if(!t)return void eu(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);oU(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eM(null)},addImages(e){th(e)}}));let th=(0,i.useCallback)(async e=>{if(er)return;let t=Math.max(0,10-tu.current.length-tp.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tp.current+=n.length;try{let e=await Promise.all(n.map(async e=>{var t;return{...await (t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})),previewUrl:URL.createObjectURL(e)}}));eb(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(o5);let r=[...t,...n];return tu.current=r,r})}finally{tp.current-=n.length}}},[er]),tf=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",en?en(t):th(t)},[en,th]),tm=(0,i.useCallback)(e=>{eb(t=>{let n=[...t],[r]=n.splice(e,1);return r&&o5(r),tu.current=n,n})},[]),tg=(0,i.useCallback)(()=>{tu.current=[],eb(e=>(e.forEach(o5),[]))},[]),tx=(0,i.useCallback)(()=>{tc.current="",eu(""),eM(null),eD(!1),ee&&l_(ee),td.current&&td.current!==ee&&l_(td.current),tg(),e2.current&&(e2.current.style.height="auto")},[tg,ee]);(0,i.useEffect)(()=>{ee&&td.current===ee&&lH(ee,{value:ec,images:ev.map(o4)})},[ev,ee,ec]),(0,i.useEffect)(()=>{let e=td.current;if(e===ee)return;e&&lH(e,{value:tc.current,images:tu.current.map(o4)});let t=ee?lB(ee):null;td.current=ee;let n=t?.value??"",r=o3(t?.images);tc.current=n,tu.current=r,eu(n),eM(null),eD(!1),eb(e=>(e.forEach(o5),r))},[ee]);let tv=(0,i.useCallback)(()=>{let e=e2.current;e&&(e.style.height="auto",e.value?oq(e):e.style.overflowY="hidden")},[]);(0,i.useLayoutEffect)(tv,[ec,es,el,eo,tv]),(0,i.useEffect)(()=>{let e=e2.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tv())});return n.observe(e),()=>n.disconnect()},[tv]),(0,i.useEffect)(()=>{let e=e2.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),l=-1===s?e.length:s,o=e.slice(i,l),a=function(e){if(lG.test(e))return null;let t=lZ.exec(e);if(t)return{indent:t[1],marker:t[2],number:null,delimiter:"",spacing:t[3],task:void 0!==t[4],length:t[0].length};let n=lJ.exec(e)??lY.exec(e);return n?{indent:n[1],marker:"",number:n[2],delimiter:n[3],spacing:n[4],task:void 0!==n[5],length:n[0].length}:null}(o);return!a||t-i<a.length||function(e){let t=null;for(let n of e.split("\n")){let e=lX.exec(n)?.[1];e&&(null===t?t=e:e[0]===t[0]&&e.length>=t.length&&n.trim()===e&&(t=null))}return null!==t}(e.slice(0,i))?null:""===o.slice(a.length).trim()?{start:i,end:l,text:""}:{start:t,end:t,text:`
11
- ${r=null===a.number?a.marker:`${String(Number(a.number)+1).padStart(a.number.length,"0")}${a.delimiter}`,`${a.indent}${r}${a.spacing}${a.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tu.current.forEach(o5)},[]);let tb=(0,i.useCallback)(async e=>{if(ev.length||!e.startsWith("/")||!J)return!1;if(eq.current)return!0;eq.current=!0,eU(!0);try{var t,n;let r=await J(e);if(!r.handled)return!1;return r.error||(t=tc.current,n=tu.current.length,0!==n||t.trim()!==e)||tx(),!0}finally{eq.current=!1,eU(!1)}},[ev.length,tx,J]),ty=(0,i.useCallback)(async()=>{var e;let t=ec.trim();(t||ev.length)&&(X?.(),(!m||oG(e=t)||l0(e))&&await tb(t)||m||(tx(),u(t,ev.length?ev:void 0)))},[ec,ev,m,tb,u,tx,X]),tj=!er&&ec.startsWith("/")&&!/\s/.test(ec.slice(1))?ec.slice(1).toLowerCase():null,tk=(()=>{var e;let t,n;return null===tj?[]:(e=[...m?oY.filter(e=>e.availableWhileStreaming):oY,...K??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tj||t===tj?0:n.startsWith(tj)||t.startsWith(tj)?1:t.includes(tj)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return o1(t,ei).toLowerCase().includes(tj)})).sort((e,t)=>e.rank-t.rank||o0[e.command.source]-o0[t.command.source]||oB.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:tC,groups:tN}=(n=0,{commands:(s=oX.map(e=>{let t=tk.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!o2(e,e1)),...t.filter(e=>o2(e,e1))]:t;return{source:e,items:r.map(e=>({command:e,index:n++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:s}),tE=1===tk.length?ei(tj?"chat.match":"chat.command"):ei(tj?"chat.matches":"chat.commands",{count:tk.length}),tI=!!ec.trim()||ev.length>0,tM=er||ea&&m,tT=ev.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(g,b)&&!eW;(0,i.useEffect)(()=>{0===ev.length&&eO(!1)},[ev.length]);let tR=(0,i.useCallback)((e,t)=>{if(!et)return void eM(null);let n=t??e.length;eM(tL(e.slice(0,n)))},[et]),tA=eI?.query??null,tW=i.useMemo(()=>null!==tA&&eK&&eK.cwd===et?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:tP(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:tP(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||tz(e.entry.path)-tz(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eK.entries,tA):[],[tA,eK,et]),tO=!!(tA&&eK?.truncated&&eK.cwd===et);(0,i.useEffect)(()=>{if(!tO||!et||!tA)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(et)}&q=${encodeURIComponent(tA)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>eG({cwd:et,query:tA,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tO,tA,et]);let tF=tO&&null!==eY&&eY.cwd===et&&eY.query===tA,tD=tF?eY.matches:tW,tB=null===eI?null:`${eI.start}:${+!!eI.quoted}:${eI.query}`;(0,i.useEffect)(()=>{if(null===tB){eR(!1),eP(0);return}eR(!0),eP(0)},[tB]);let tH=null!==eI;(0,i.useEffect)(()=>{if(!tH||!et)return;let e=to.current;e&&e.cwd===et&&Date.now()-e.fetchedAt<1e4||ta.current===et||(ta.current=et,eJ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(et)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eV({cwd:et,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>tz(e.path)-tz(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),to.current={cwd:et,fetchedAt:Date.now()}}).catch(()=>{to.current=null}).finally(()=>{ta.current=null,eJ(!1)}))},[tH,et]);let t_=(0,i.useCallback)(e=>{if(!eI)return;let t=e2.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eI.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eI.quoted),s=eI.start+i.cursorOffset;oU(t,eI.start,r,i.text,i.cursorOffset),eM(tL(t.value.slice(0,s)))},[eI]);(0,i.useEffect)(()=>{ez>=tD.length&&eP(Math.max(0,tD.length-1))},[tD.length,ez]),(0,i.useEffect)(()=>{ts.current.length=tD.length},[tD.length]),(0,i.useEffect)(()=>{eT&&ts.current[ez]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ez,eT]),(0,i.useEffect)(()=>{eB>=U.length&&eH(Math.max(0,U.length-1))},[U.length,eB]),(0,i.useEffect)(()=>{tl.current.length=U.length},[U.length]),(0,i.useEffect)(()=>{eF&&tl.current[eB]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eB,eF]);let tU=(0,i.useCallback)(e=>{eu(e),eD(!1),eH(0),eM(null),requestAnimationFrame(()=>{let t=e2.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),oq(t))})},[]),tq=(0,i.useCallback)(e=>{let t=`/${e.name} `;eu(t),eS(!1),eN(0),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),oq(e))})},[]),tK=(0,i.useCallback)(e=>{let t=ec.trim();if(!t&&!ev.length)return;X?.();let n=ev.length?ev:void 0,r=()=>{if(t.startsWith("/")&&Q){tx(),Q(t,"steer"===e?"steer":"followUp",n);return}tx(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!ev.length&&J&&oG(t)?tb(t):!ev.length&&J&&l0(t)?tb(t).then(e=>{e||r()},()=>r()):r()},[ec,ev,J,Q,h,f,tx,X,tb]),tV=(0,i.useCallback)(e=>{let t=tC.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eC-1);if("right"===e)return Math.min(t,eC+1);let n=tr.current[eC];if(!n)return"down"===e?Math.min(t,eC+1):Math.max(0,eC-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,l=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eC)continue;let t=tr.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-s;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<o&&(l=n,o=d)}return l>=0?l:"down"===e?Math.min(t,eC+1):Math.max(0,eC-1)},[tC.length,eC]),tZ=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ea||"ctrlEnter"===ed?n&&(e.ctrlKey||e.metaKey):n,i=ea?r:n,s=Date.now()-e7.current<100,l=e9.current||t.isComposing||229===t.keyCode;if(i&&(l||s)){s&&e.preventDefault();return}if(eF&&!l){if("ArrowDown"===e.key){e.preventDefault(),eH(e=>Math.min(Math.max(0,U.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eH(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eD(!1);return}if(("Tab"===e.key||i)&&U[eB]){e.preventDefault(),tU(U[eB]);return}}if(ek&&null!==tj){if("ArrowDown"===e.key){e.preventDefault(),eN(tV("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eN(tV("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eN(tV("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eN(tV("left"));return}if("Escape"===e.key){e.preventDefault(),eS(!1);return}let t=tC[eC];if("Tab"===e.key&&t){e.preventDefault(),tq(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return lQ(t)&&l0(e)}(ec,t,m)?(eS(!1),ty()):tq(t);return}}if(eT&&null!==eI&&!l){if("ArrowDown"===e.key){e.preventDefault(),eP(e=>oH(e,tD.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eP(e=>oH(e,tD.length,-1));return}if("Escape"===e.key){e.preventDefault(),eR(!1);return}if(("Tab"===e.key||i)&&tD[ez]){e.preventDefault(),t_(tD[ez]);return}}if("ArrowUp"===e.key&&!l&&!m&&U.length>0&&0===ec.trim().length){e.preventDefault(),eS(!1),eR(!1),eH(U.length-1),eD(!0);return}if("Escape"===e.key&&!l&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?tK(e.altKey&&f||!h?"followup":"steer"):ty())},[ea,ed,m,h,f,p,ek,tj,tC,eC,tq,tK,ty,tV,eT,eI,tD,ez,t_,eF,U,eB,tU,ec]),tJ=(0,i.useCallback)(()=>{let e=e2.current;e&&oq(e)},[]),tY=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!er&&t.length){e.preventDefault(),th(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:l,occurrence:o}of t){if(!s||!l)continue;let t=0;for(let n=0;n<=o&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let a=s.replace(/([\\[\]])/g,"\\$1"),d=l.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let l=e.currentTarget,o=l.selectionStart,a=l.value.slice(0,o)+s+l.value.slice(l.selectionEnd);e.preventDefault(),tc.current=a,eu(a),eD(!1),tR(a,o+s.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(o+s.length,o+s.length)})},[er,th,tR]);(0,i.useEffect)(()=>{if(null===tj){eS(!1),eN(0),tt.current=!1;return}eS(!0),eN(0),!tt.current&&Z&&(tt.current=!0,Promise.resolve(Z()).catch(()=>{tt.current=!1}))},[tj,Z]),(0,i.useEffect)(()=>{if(!ek||!et)return;let e=!1;return eQ({cwd:et,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(et)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;eQ({cwd:et,values:n})}).catch(()=>{e||eQ({cwd:et,values:{}})}),()=>{e=!0}},[ek,et]),(0,i.useEffect)(()=>{eC>=tC.length&&eN(Math.max(0,tC.length-1))},[tC.length,eC]),(0,i.useEffect)(()=>{tr.current.length=tC.length},[tC.length]),(0,i.useEffect)(()=>{ek&&tr.current[eC]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eC,ek]),(0,i.useLayoutEffect)(()=>{if(!ek||null===tj)return void eE(null);let e=tn.current;if(e)return oK(e,e=>{eE(t=>t===e?t:e)})},[ek,tj]),(0,i.useLayoutEffect)(()=>{if(!eT||null===eI)return void eL(null);let e=ti.current;if(e)return oK(e,e=>{eL(t=>t===e?t:e)})},[eT,eI]);let tG=b&&b.length>0?b.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(v??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),tX=R?Math.max(0,R.tokensBefore-R.estimatedTokensAfter):0,tQ=R?`${R.reason&&"manual"!==R.reason?`${R.reason[0].toUpperCase()}${R.reason.slice(1)} `:ei("chat.compacted")} ${oJ(R.tokensBefore)} -> ${oJ(R.estimatedTokensAfter)} tokens (${ei("chat.tokensSaved",{saved:oJ(tX)})})`:null,t0=z&&"auto"!==z?z:null,t1="auto"!==(l=t0??"auto")&&F?F[l]??l:l,t2=Object.entries(oD).find(e=>{let[,t]=e;return t===(A??"configured")})?.[0]??"configured",t4="chat-only"===t2?ei("chat.chatOnly"):t2;(0,i.useEffect)(()=>{let e=e=>{e4.current&&!e4.current.contains(e.target)&&eh(!1),e8.current&&!e8.current.contains(e.target)&&em(!1),e3.current&&!e3.current.contains(e.target)&&ex(!1),!e5.current||e5.current.contains(e.target)||e2.current?.contains(e.target)||eD(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eh(!1)},[m]);let t8=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t8.current=performance.now()}},[m]);let t3=e=>{var t,n;return t=e.detail,n=performance.now()-t8.current,t>0&&n<600};return(0,i.useEffect)(()=>{ea||ex(!1)},[ea]),(0,r.jsxs)("fieldset",{disabled:e_,"aria-busy":e_,className:er?void 0:"chat-input-shell",style:{...er?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:er?0:"0 16px 8px",paddingRight:er?0:ea?16:52,opacity:e_?.5:1,transition:"opacity 0.15s"},children:[!er&&(0,r.jsx)("input",{ref:e6,type:"file",accept:en?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tf}),(0,r.jsxs)("div",{style:{...er?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(o7,{cwd:w}),(0,r.jsx)(ae,{error:y}),(0,r.jsx)(at,{warnings:j}),tT&&(o=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(o9,{tone:"warning",title:ei("chat.imageNotSupportedTitle"),body:ei("chat.imageNotSupportedBody",{model:o?.name||g?.modelId||""}),onClose:()=>eO(!0)})),(_?.steering.length??0)+(_?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ei("chat.queued",{count:(_?.steering.length??0)+(_?.followUp.length??0)})}),q&&(0,r.jsxs)("button",{onClick:q,title:ei("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),ei("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[_?.steering.map((e,t)=>(0,r.jsx)(o6,{kind:"steer",text:e},`steer-${t}`)),_?.followUp.map((e,t)=>(0,r.jsx)(o6,{kind:"follow-up",text:e},`followup-${t}`))]})]}),H&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),ei("chat.retrying",{attempt:H.attempt,max:H.maxAttempts}),H.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",H.errorMessage]})]}),tQ&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),tQ]}),M&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:T?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:T?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:M}),T&&(0,r.jsx)(tw,{onClick:T,title:ei("chat.dismissCompactError")})]}),ev.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ev.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(iF,{src:e.previewUrl,children:(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tm(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eF&&U.length>0&&(0,r.jsxs)("div",{ref:e5,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:ei("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:U.map((e,t)=>{let n=t===eB;return(0,r.jsxs)("button",{ref:e=>{tl.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tU(e)},onMouseEnter:()=>eH(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),ek&&null!==tj&&(0,r.jsxs)("div",{ref:tn,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e$?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${e$}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:V?ei("chat.loadingCommands"):ei("chat.slashCommands",{label:tE})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:V||0!==tk.length?tN.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:ei(oQ[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===eC,s=o2(t,e1);return(0,r.jsxs)("button",{ref:e=>{tr.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tq(t)},onMouseEnter:()=>eN(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ei("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:o1(t,ei)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ei("chat.noCommands")})})]}),eT&&null!==eI&&(a=eZ&&(!eK||eK.cwd!==et),d=1===tD.length?ei("chat.match"):ei("chat.matches",{count:tD.length}),c=eK?.truncated&&!tF?eI.query?ei("chat.searchingAll"):ei("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:ti,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eA?"min(48vh, 400px)":`min(48vh, 400px, ${eA}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?ei("chat.loadingFiles"):ei("chat.files",{label:d,hint:c})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tD.length?tD.map((e,t)=>{let n=t===ez,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{ts.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eP(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(tS,{size:14}):t$(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tO&&!tF?ei("chat.searching"):ei("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:tM?"column":"row",gap:8,alignItems:tM?"stretch":"center",background:"var(--bg)",border:er?"none":`1px solid ${ew?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!er,padding:er?0:ea?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:er?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:e2,className:"chat-input-textarea","aria-label":er?ei("chat.quoteQuestion"):void 0,value:ec,onChange:e=>{tc.current=e.target.value,eu(e.target.value),eD(!1),tR(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tR(t.value,t.selectionStart)},onKeyDown:tZ,onCompositionStart:()=>{e9.current=!0},onCompositionEnd:e=>{e9.current=!1,e7.current=Date.now();let t=e.currentTarget;tR(t.value,t.selectionStart)},onInput:tJ,onPaste:tY,placeholder:I?ei("chat.compactingPlaceholder"):m&&(h||f)?ei("chat.steerPlaceholder"):m?ei("chat.agentPlaceholder"):ei("chat.messagePlaceholder"),rows:1,style:{flex:tM?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:er?96:24,maxHeight:200,overflow:"auto"}}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[h&&(0,r.jsxs)("button",{onClick:()=>tK("steer"),disabled:!tI,title:ei("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tI?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tI?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tI?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),ei("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>tK("followup"),disabled:!tI,title:`${ei("chat.followUpHint")} (${ea?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":ea?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tI?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tI?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tI?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),ei("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:ty,disabled:!ec.trim()&&!ev.length,title:ei("chat.send"),"aria-label":ei("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ea?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ec.trim()||ev.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ec.trim()||ev.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ec.trim()||ev.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ec.trim()||ev.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!ea&&ei("chat.send")]})]})]}),ew&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ej?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ei("chat.shell")," \xb7 ",ej?ei("chat.outputLocal"):ei("chat.outputModel")]}),!er&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ea?4:8,display:ea?"grid":"flex",gridTemplateColumns:ea?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ea?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>e6.current?.click(),title:ei("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ev.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ev.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ev.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(tG.length>0||g||y)&&k&&(0,r.jsx)(oW,{options:tG,value:g,onChange:k,onReselect:k,disabled:m,busy:S,isAutoSelection:x,defaultValue:C,onSetDefault:N})]}),!ea&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e3,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ea?0:"auto"},children:[ea&&(0,r.jsx)("button",{type:"button",title:eg?void 0:ei("chat.moreControls"),"aria-label":ei("chat.moreControls"),"aria-expanded":eg,"aria-hidden":eg||void 0,tabIndex:eg?-1:void 0,onClick:()=>{ex(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:32,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eg?"default":"pointer",fontSize:12,fontWeight:500,visibility:eg?"hidden":"visible",pointerEvents:eg?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eg||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eg||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:ei("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ea?eg?"flex":"none":"flex",alignItems:"center",gap:ea?1:2,...ea?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[W&&(0,r.jsxs)("div",{ref:e8,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>em(e=>!e),title:m?ei("chat.currentReasoning",{level:t1}):ei("chat.changeReasoning",{level:t1}),"aria-label":ei("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:ef?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=ef?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ea?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:oV.filter(e=>!O||"auto"===e||O.includes(e)).map(e=>{let t="auto"===e?P:!P&&t0===e,n=ei(oZ[e]),i="auto"!==e&&F?F[e]:void 0,s=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)(oP,{active:t,onSelect:()=>{if(em(!1),"auto"===e){P||W("auto");return}(!t||P)&&W(e)},gutter:!!B,star:B&&"auto"!==e?{isDefault:D===e,saveLabel:ei("chat.saveDefaultThinking"),defaultLabel:ei("chat.defaultThinking"),onSave:()=>{em(!1),B(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,l&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&L&&(0,r.jsxs)("div",{ref:e4,style:{position:ea?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t3(e)||eh(e=>!e)},disabled:m,title:ei("chat.changeToolPreset")+`: ${t4}`,"aria-label":ei("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:ep?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ep?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("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"})}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t4})]}),ep&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ea?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:oF.map(e=>{let t,n=oD[e],i=(A??"configured")===n;return t="configured"===e?ei("chat.configuredTools"):"chat-only"===e?ei("chat.chatOnly"):"read-only"===e?ei("chat.readOnlyTools",{count:4}):"default"===e?ei("chat.builtInTools",{count:4}):ei("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eh(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||I)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:I?E:e=>{t3(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:I?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:I?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=I?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=I?"#ef4444":"var(--text-muted)"},title:I?ei("chat.stopCompaction"):ei("chat.compactContext"),"aria-label":I?ei("chat.stopCompaction"):ei("chat.compactContext"),children:I?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:ei("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),ei("chat.stop")]}),void 0!==G&&(0,r.jsx)("button",{onClick:G,title:Y?ei("chat.disableSound"):ei("chat.enableSound"),"aria-label":Y?ei("chat.disableSound"):ei("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:Y?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:Y?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=Y?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=Y?"1":"0.55"},children:Y?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ea&&eg&&(0,r.jsx)("button",{type:"button",title:ei("chat.collapseControls"),"aria-label":ei("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eh(!1),em(!1),ex(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})})),ar="pi-web:minimap-preview-locked";function ai(){try{return window.localStorage}catch{return null}}function as(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ai();if(!e)return!1;try{return"true"===e.getItem(ar)}catch{return!1}}var al=n(88576),ao=n.n(al);function aa(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:ao().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!s,onClick:e=>{e.stopPropagation(),null!==i&&s?.(i)},children:n})}let ad=[...iE??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],ac=[[r8.A,{throwOnError:!1,strict:!1}]];function au(e){let t=e?.properties,n=t?.dataPreviewHeadingIndex??t?.["data-preview-heading-index"];return"number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):null}let ap=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,l=(0,i.useMemo)(()=>ih(t),[t]);return t?(0,r.jsx)("div",{className:ao().outline,children:(0,r.jsx)(rY.oz,{remarkPlugins:ad,rehypePlugins:ac,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(aa,{level:1,headingIndex:au(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(aa,{level:2,headingIndex:au(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(aa,{level:3,headingIndex:au(i),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,r.jsx)("button",{type:"button",className:ao().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:l})}):null}),ah=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:l,onRevealHistory:o,turnsBefore:a}=e,{t:d}=(0,e0.s)(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(600),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(as),[j,k]=(0,i.useState)(null),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),N=(0,i.useRef)([]),$=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),E=(0,i.useRef)(null),I=(0,i.useRef)(new Map),M=(0,i.useRef)(null),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(t);A.current=t;let L=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(p,g),[p,g]),{nodes:z,gap:P}=L;$.current=L;let W=(0,i.useCallback)(e=>{T.current={index:e,until:Date.now()+1600},m(e)},[]),O=(0,i.useCallback)((e,t)=>{let n=T.current;if(n&&Date.now()<n.until)return void m(n.index);T.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void m(null);let i=e.scrollTop+.3*e.clientHeight;m(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),F=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=N.current;u(t>20),O(e,n)},[s,O]),D=(0,i.useRef)(null),B=(0,i.useCallback)(()=>{D.current||(D.current=setTimeout(()=>{D.current=null;let e=s.current,t=C.current;if(!e||!t)return;let r=l.current,i=e.getBoundingClientRect(),o=[],a=0,d=null,c=n();for(let t of c?[...A.current,c]:A.current){let n=rj(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[a];if(a++,n){d=null;let n=s?.getBoundingClientRect();d={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null,toolCount:0},o.push(d);continue}if(!d)continue;d.toolCount+="assistant"===t.role&&Array.isArray(t.content)?t.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let l=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=rE(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);l&&d.assistantPreviews.push({markdown:l,element:s})}let p=o.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));x(t.clientHeight),N.current=p,h(p),u(e.scrollHeight-e.clientHeight>20),O(e,p);let f=R.current,m=f?p[f.nodeIndex]:null;if(f&&m){let t=void 0===f.assistantIndex?null:m.targetTurn.assistantPreviews[f.assistantIndex],n=m.targetTurn.scrollTop;if("assistant"===f.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===f.target){let r=void 0===f.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(f.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;R.current=null,W(m.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,W,l,s,O]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",F,{passive:!0}),()=>e.removeEventListener("scroll",F)},[s,F]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{B(),F()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),D.current&&(clearTimeout(D.current),D.current=null)}},[B,s,F]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{B(),F()},50);return()=>clearTimeout(e)},[t.length,B,F]);let H=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(W(e.index),null===e.targetTurn.scrollTop){R.current={nodeIndex:e.index,target:"user"},o();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[W,o,s]),_=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){R.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},o();return}let i=n.getBoundingClientRect(),l=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;W(e.index),n.scrollTo({top:Math.max(0,l),behavior:"smooth"})},[W,o,s]),U=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=$.current,i=C.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),l=t[0].topRatio*i,o=n>0?Math.round((s-l)/n):0,a=Math.max(0,Math.min(t.length-1,o)),d=t[a];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),q=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){R.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},o();return}let l=i.querySelectorAll("h1, h2, h3").item(n);if(!l)return;let a=r.getBoundingClientRect(),d=l.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;W(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[W,o,s]),K=(0,i.useCallback)(()=>{M.current&&(clearTimeout(M.current),M.current=null)},[]),V=(0,i.useCallback)(()=>{y||(K(),b(!0))},[K,y]),Z=(0,i.useCallback)(()=>{let e=!y;w(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ai();if(t)try{t.setItem(ar,String(e))}catch{}}(e),e&&(K(),b(!1),k(null))},[K,y]),J=(0,i.useCallback)(()=>{K(),M.current=setTimeout(()=>{M.current=null,b(!1),k(null)},250)},[K]);(0,i.useEffect)(()=>()=>K(),[K]);let Y=(0,i.useCallback)(e=>{if(!c)return;S.current=!0,V();let t=e.currentTarget.getBoundingClientRect();k(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=U(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&H(r,n)};n(e.clientY,"smooth");let r=e=>{S.current&&n(e.clientY,"auto")},i=()=>{S.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[U,H,V,c]),G=null===j?null:U(j),X=G?.index??null;if((0,i.useEffect)(()=>{if(!v||null===X)return;let e=E.current,t=I.current.get(X);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[p,v,X]),!c)return null;let Q=Math.max(1,(z.length>0?z[z.length-1].topRatio*g:12)-12);return(0,r.jsxs)("div",{ref:C,onMouseDown:Y,onMouseEnter:V,onMouseLeave:J,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();k((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[a>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:Q,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),z.map(e=>{let t=v&&G?.index===e.index,n=f===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,P),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)("button",{type:"button",className:ao().lock,"data-minimap-lock":y?"on":"off","aria-pressed":y,title:d(y?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":d("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Z()},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),y?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})}),v&&p.length>0&&(0,r.jsxs)("div",{ref:E,className:ao().preview,"data-minimap-preview-box":"",onMouseEnter:V,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[a>0&&(0,r.jsx)("button",{type:"button",className:ao().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:d("chatMinimap.earlierTurns",{count:a})}),p.map(e=>{var t;let n=X===e.index;return(0,r.jsxs)("div",{ref:t=>{t?I.current.set(e.index,t):I.current.delete(e.index)},className:ao().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:ao().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(a+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:ao().toolBadge,role:"img",title:d("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":d("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:ao().content,children:[(0,r.jsx)("button",{type:"button",className:ao().user,"data-minimap-preview-user":e.index,onClick:()=>{H(e,"smooth")},children:(0,r.jsx)("span",{className:ao().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:ao().assistant,children:[(0,r.jsx)("button",{type:"button",className:ao().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>_(e,n),"aria-label":d("chatMinimap.locateAssistant"),title:d("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(ap,{markdown:t.markdown,onAnswerClick:()=>_(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]})});var af=n(42790);function am(e){let{text:t}=e,n=(0,i.useMemo)(()=>new af.v().ansi_to_html(t).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="'),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function ag(e){let t,n,s,{widgets:l,children:o}=e,{t:a}=(0,e0.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>l.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(l.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[l]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===l.length)return null;let g=l.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=l.indexOf(g),n=`${d}-trigger-${t}`,s=`${d}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(am,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:l.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=f.has(e.key),l=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=a("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${o}: ${e.key}, ${l}`,title:`${e.key} - ${o} - ${i?a("i18n.collapse"):a("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${o}: ${e.key}, ${l}`,title:`${e.key} - ${o}`,children:p},e.key)})}),o]})]})}let ax="command:";function av(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,l=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(ax))return null;let t=e.slice(ax.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=rf(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else rf(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===l.length&&0===n.length)return null;let o=l.some(e=>"command"===e.kind),a=l.map(e=>"text"===e.kind?rf(e.text):e.label).join(" "),d=l.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:l.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(am,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${l.length>0?" has-status":""}${o?" has-commands":""}`,children:n.length>0?(0,r.jsx)(ag,{widgets:n,children:d}):d})}function ab(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function ay(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function aw(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function aj(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function ak(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ak(e)||"toolCall"!==e.type)return null;let n={type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=ak(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ak(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}function aC(e){if(!e||"object"!=typeof e)return null;let{reason:t,cwd:n}=e;return"cwd-missing"===t&&"string"==typeof n&&n?n:null}class aN extends Error{constructor(e,t,n,r,i){super(e),this.status=t,this.code=n,this.accepted=r,this.missingCwd=i,this.name="AgentCommandError"}}function a$(e){return e instanceof aN&&"prompt_rejected"===e.code&&!1===e.accepted}function aE(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function aI(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new aN(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,aC(r)??void 0);return r.data}function aM(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let aT=new WeakMap;function aR(e){let t,n=aT.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return aT.set(e,t),t}function aA(e){let t=aM().get(e);return t?Date.now()-t.savedAt>6e5?(aM().delete(e),null):(aM().delete(e),aM().set(e,t),t):null}function aL(e){if(!e.sessionId||!e.revision)return!1;let t=aM();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(aR(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=aM();for(;e.size>8;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}let t=0;for(let n of e.values())t+=aR(n);for(;t>0x2000000&&e.size>0;){let n=e.keys().next().value;if(void 0===n)break;let r=e.get(n);e.delete(n),r&&(t-=aR(r))}}(),aM().has(n.sessionId))}function az(e){aM().delete(e)}var aP=n(14755);let aW="pi-tool-preset";function aO(){try{return window.localStorage}catch{return null}}function aF(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0)}function aD(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,aF(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),aF(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function aB(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function aH(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(aB).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let a_=(e,t)=>`live:${e??""}:${t}`;class aU extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class aq{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new aU("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof aU?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new aU("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new aU("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new aU("closed")));try{t=this.options.createSource(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw this.lastError={reason:"error",message:e,at:Date.now()},new aU("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(d,new aU("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a=Date.now(),d={sessionId:e,source:t,attempt:o,watchdog:null,openedAt:a,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=e=>{let t;if(this.current===d){d.lastSeenAt=Date.now();try{t=JSON.parse(e.data)}catch{return}if("heartbeat"===t.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===t.type){d.connectedAt??=d.lastSeenAt,o.ready=!0,o.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??a)>e&&this.fail(d,new aU("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(d,new aU("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(t)}},t.onerror=()=>{this.fail(d,new aU("closed"),"error")},d}fail(e,t,n){this.current===e&&(this.lastError={reason:n,message:"startup_error"===n?t.message:null,at:Date.now()},this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){null!==e.watchdog&&clearInterval(e.watchdog),e.watchdog=null,e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.retries+=1,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t,dueAt:Date.now()+this.options.reconnectDelayMs}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function aK(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function aV(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let aZ=()=>"hidden"===document.visibilityState,aJ=()=>!1;function aY(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function aG(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}function aX(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aQ(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let a0={isStreaming:!1,streamingMessage:null};function a1(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function a2(){let e=a0,t=new Set;return{getState:()=>e,dispatch(n){let r=function(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=aS(t.message,{includeStreamingRawInput:!0});return"assistant"===n.role?{isStreaming:!0,streamingMessage:n}:e}case"delta":var n=t.event;switch(n.type){case"text_start":return a1(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return a1(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return a1(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return a1(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return a1(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return a1(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return a1(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return a1(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id||e.toolCallId,toolName:n.toolName||e.toolName,rawInput:(e.rawInput??"")+n.delta}:null);case"toolcall_end":return a1(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return a0;default:return e}}(e,n);if(r!==e)for(let n of(e=r,t))n()},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}function a4(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function a8(e,t){return e.reduce((e,n)=>"user"===n.role&&aH(n)===t?e+1:e,0)}function a3(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function a5(e){return e&&"auto"!==e?e:null}let a6=new Map,a9=[2e3,5e3,1e4];function a7(e){return new Promise(t=>setTimeout(t,e))}function de(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function dt(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:de(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:de(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=de(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function dn(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function dr(e,t){let[n,r]=(0,i.useState)(()=>t(e.getState()));return(0,i.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let di=e=>e.isStreaming,ds=e=>!!e.streamingMessage?.content.length,dl=e=>e.streamingMessage,da=null,dd=null;function dc(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>dd);if((0,i.useEffect)(()=>{if(dd)return;let e=!1;return(da??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(dd=e,e)).catch(()=>(da=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let l=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:l,"aria-label":l,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function du(e){let t,{messageCount:n,toolCallCount:s,durationMs:l,cacheMisses:o,defaultExpanded:a=!1,reveal:d=!1,children:c,t:u}=e,[p,h]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{d&&h(!0)},[d]);let f=[`${n} ${u(1===n?"chat.message":"chat.messages")}`];s>0&&f.push(`${s} ${u(1===s?"chat.toolCall":"chat.toolCalls")}`),void 0!==l&&f.push(u("chat.turnDuration",{time:rZ(l)}));let m=o&&!(p||d)?(t={count:o.count,tokens:sY(o.missedTokens),cost:sX(u,o.missedCost)},u(1===o.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":p||d,"aria-label":[u("chat.processDetails"),...f,...m?[m]:[]].join(" \xb7 "),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:u(p?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:p?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:sG},children:` \xb7 ${m}`})]})]}),(p||d)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}function dp(e){var t;let s,{session:o,searchTarget:a,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onToolEnd:b,onAttentionNeeded:y,onSessionCreated:w,onSessionForked:j,modelsRefreshKey:k,chatInputRef:S,onBranchDataChange:C,onSystemPromptChange:N,onSystemToolsChange:$,onSystemInfoLoaderChange:E,onDebugSnapshotReaderChange:I,onSessionStatsChange:M,onSessionStatsPanelOpen:T,onOpenSettings:R,onContextUsageChange:A,onOpenFile:L,onFilesUploaded:z,onOpenSubagent:P,onAskInNewChat:W,quoteSelectionEnabled:O=!1,initialPrompt:F,onInitialPromptConsumed:D,soundEnabled:B=!0,onSoundToggle:H,playDoneSound:_=()=>{},unlockAudio:U,holdAudio:q}=e,{t:K}=(0,e0.s)(),V=te(),Z=o?.relation?.kind!=="subagent",J=(0,i.useRef)(_);J.current=_;let Y=(0,i.useRef)(B);Y.current=B;let G=(0,i.useRef)(!1),X=(0,i.useCallback)(e=>{Z&&Y.current&&!e.aborted&&!e.subagentsActive&&J.current(),v?.(e)},[Z,v]),Q=(0,i.useRef)(a?null:c??null),[ee,et]=(0,i.useState)(()=>{let e=Q.current;return e&&!e.atBottom?e:null}),[en,er]=(0,i.useState)(!1),{loading:ei,error:es,messages:el,activeToolResults:eo,entryIds:ea,messageKeys:ed,historyCursor:ec,hasEarlierMessages:eu,earlierTurnCount:ep,streamingStore:eh,agentRunning:ef,bashRunning:em,pendingBash:eg,modelNames:ex,modelList:ev,modelError:eb,missingCwd:ey,modelScopeWarnings:ew,modelThinkingLevels:ej,modelThinkingLevelMaps:ek,toolPreset:eS,thinkingLevel:eC,retryInfo:eN,contextUsage:e$,forkingEntryId:eE,isCompacting:eI,compactError:eR,compactResult:eA,displayModel:eL,modelSwitching:eP,sessionStats:eW,slashCommands:eO,slashCommandsLoading:eF,queuedMessages:eD,notices:eB,extensionDialog:eH,waitingExtensionDialogCount:e_,extensionCustomUi:eU,waitingExtensionCustomUiCount:eq,extensionStatuses:eK,extensionWidgets:eV,respondToExtensionUi:eZ,sendExtensionCustomInput:eJ,setNoticePaused:eY,addNotice:eG,isAutoModelSelection:eX,isAutoThinkingSelection:eQ,defaultModel:e1,savedDefaultThinkingLevel:e2,agentPhase:e4,isNew:e8,editEntryId:e3,showScrollToBottom:e5,sessionIdRef:e6,scrollContainerRef:e9,lastUserMsgRef:e7,promptAnchorActive:tt,handleSend:tn,handleAbort:tr,handleFork:ts,handleEditContent:tl,cancelEdit:to,handleModelChange:ta,handleCompact:td,handleSteer:tu,handleFollowUp:tp,handlePromptWithStreamingBehavior:th,handleAbortCompaction:tf,dismissCompactError:tm,handleRecallQueue:tg,handleBuiltinSlashCommand:tx,handleToolPresetChange:tv,handleThinkingLevelChange:tb,handleSetDefaultModel:ty,handleSetDefaultThinkingLevel:tw,loadSlashCommands:tj,scrollUserMsgToTop:tk,loadContext:tS,activeLeafId:tC,scrollToBottom:tN,scrollToMessage:t$}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:s,onAgentEnd:l,onToolEnd:o,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:p,onSystemPromptChange:h,onSystemToolsChange:f,onSystemInfoLoaderChange:m,onSessionStatsPanelOpen:g,onOpenSettings:x,onDebugSnapshotReaderChange:v}=e,b=null===t&&null!==r,y=b?e.initialNewSessionChoices??null:null,[w,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(!b),[C,N]=(0,i.useState)(null),[$,E]=(0,i.useState)(null),[I,M]=(0,i.useState)([]),[T,R]=(0,i.useState)(new Map),[A,L]=(0,i.useState)([]),[z,P]=(0,i.useState)(()=>new Map),[W,O]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(0),[_]=(0,i.useState)(a2),U=_.dispatch,[q,K]=(0,i.useState)(!1),[V,Z]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(null),[G,X]=(0,i.useState)({}),[Q,ee]=(0,i.useState)([]),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(null),[es,el]=(0,i.useState)(null),[eo,ea]=(0,i.useState)([]),[ed,ec]=(0,i.useState)({}),[eu,ep]=(0,i.useState)({}),[eh,ef]=(0,i.useState)(()=>y?.model??null),[em,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(aP.Q8),[eb,ey]=(0,i.useState)(()=>y?.thinkingLevel??null),[ew,ej]=(0,i.useState)(null),[ek,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[e$,eE]=(0,i.useState)(null),[eI,eR]=(0,i.useState)(null),[eA,eL]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(null),eO=(0,i.useRef)(0),eF=(0,i.useRef)(0),[eD,eB]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(null),[eU,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(null),[eZ,eJ]=(0,i.useState)(null),[eY,eG]=(0,i.useState)(!1),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(!0),[e2,e4]=(0,i.useState)(null),[e8,e3]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)([]),[ti,ts]=(0,i.useState)(!1),[tl,to]=(0,i.useReducer)(dt,{visible:[],pending:[]}),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)([]),[tp,th]=(0,i.useState)([]),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)([]),[tv,tb]=(0,i.useState)({steering:[],followUp:[]}),ty=(0,i.useRef)(null),tw=(0,i.useRef)(null),tj=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tS=(0,i.useRef)(!1),[tC,tN]=(0,i.useState)(0),t$=(0,i.useRef)(null),tE=(0,i.useRef)(()=>{}),tI=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tM=(0,i.useRef)({count:0,lastAt:null}),tT=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tR=(0,i.useRef)(null),tA=(0,i.useRef)(null),tL=(0,i.useRef)(!1),tz=(0,i.useRef)(0),tP=(0,i.useRef)(t?.id??null),tW=(0,i.useRef)(t?.id??null),tO=(0,i.useRef)(!1),tF=(0,i.useRef)(!1),tD=(0,i.useRef)(!1),tB=(0,i.useRef)(!1),tH=(0,i.useRef)(-1),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(0),tq=(0,i.useRef)(null),tK=(0,i.useRef)(!!e.deferInitialScroll),tV=(0,i.useRef)(null),tZ=(0,i.useRef)(!1),tJ=(0,i.useRef)(!0),tY=(0,i.useRef)(0),tG=(0,i.useRef)(null),tX=(0,i.useRef)(void 0),tQ=(0,i.useRef)(void 0),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)([]),t4=(0,i.useRef)(null),t8=(0,i.useRef)(0),t3=(0,i.useRef)(!1),t5=(0,i.useRef)(y?.model??null),t6=(0,i.useRef)(y?.thinkingLevel??null),t9=(0,i.useRef)({}),t7=(0,i.useRef)(null),ne=(0,i.useRef)(0),nt=(0,i.useRef)(null),nn=(0,i.useRef)(null),nr=(0,i.useRef)(null),ni=(0,i.useRef)(0),ns=(0,i.useRef)(null),nl=(0,i.useCallback)(()=>{nn.current=ne.current,nr.current?.runId===ne.current&&(nr.current=null)},[]),no=(0,i.useRef)(!1),na=(0,i.useRef)(new Map),nd=(0,i.useRef)(!0),nc=(0,i.useRef)(new Map),nu=(0,i.useRef)(null),np=(0,i.useRef)([]),nh=(0,i.useRef)([]),nf=(0,i.useRef)(null),nm=(0,i.useRef)(null),ng=(0,i.useRef)(!1),nx=(0,i.useRef)(0);tW.current=t?.id??null,nu.current=w,np.current=I,nh.current=A,nf.current=$,nm.current=W,ng.current=F,nx.current=B,tL.current=eX,tz.current=tc.length+tp.length;let nv=(0,i.useCallback)(e=>nd.current&&tP.current===e&&(tF.current||tk.current||tW.current===e&&!tS.current),[]);ty.current||(ty.current=new aq({createSource:e=>ez("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(eT())}`),e),onEvent:e=>tq.current?.(e),shouldMaintain:nv,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nb=e.setToolPreset??ev,ny=t?.id;(0,i.useLayoutEffect)(()=>{(ny||b&&!tP.current)&&nb(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:aO();if(!e)return aP.Q8;try{let t=e.getItem(aW);return(0,aP.sn)(t)?t:aP.Q8}catch{return aP.Q8}}())},[ny,b,nb]);let nw=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{b&&nw?.({model:eh,thinkingLevel:eb})},[b,eh,eb,nw]);let nj=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=t0.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),tY.current=t.scrollTop)},[]),nk=eU??eK??w?.context.model??eZ??null,nS=b?eh??em:nk??(w?.context.messages.length===0?em:null),nC=a5(w?.context.thinkingLevel&&"off"!==w.context.thinkingLevel?w.context.thinkingLevel:null),nN=b?eb??ew:eC??e$??nC??(w?.context.messages.length===0?ew:null),n$=t?.id??s??void 0,nE=(0,i.useCallback)(e=>{eV(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eE(a5(e.thinkingLevel))},[]),nI=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=na.current.get(t);if(!e)break;t=e}return t},[]),nM=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),l=nI(r);if(!nd.current&&!t3.current&&r===s)return;let o=e.chatInputRef?.current;o?o.restoreSubmission(t,i,l):l&&lK(l,t,i)},[s,e.chatInputRef,nI]),[nT,nR]=(0,i.useState)(()=>{let e=t?.id;return e&&!lB(e)&&a6.delete(e),e&&a6.get(e)||null}),nA=(0,i.useCallback)(e=>{t?.id&&(e?a6.set(t.id,e):a6.delete(t.id),nR(e))},[t?.id]),nL=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),nA(r))},[e.chatInputRef,t?.id,nA]),nz=(0,i.useCallback)(()=>nA(null),[nA]),nP=(0,i.useMemo)(()=>{let e=w?.totalActiveMs,n=eP&&eP.sessionId===w?.sessionId?eP.value:void 0,r=void 0===e&&void 0===n?void 0:Math.max(e??0,n??0);if(ta)return{...ta,totalActiveMs:r,...eA?{contextUsage:eA}:{}};let i=w?.stats,s=function(e,t,n){let r=aD(n);if(!e)return r;let i=aD(t),s=(e,t)=>Math.max(0,e-t),l={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return l.total=l.input+l.output+l.cacheRead+l.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:l,cost:e.cost+s(r.cost,i.cost)}}(i,w?.context.messages??[],I);return 0!==s.tokens.total||0!==I.length||i?{sessionFile:w?.filePath||void 0,sessionId:tP.current??t?.id??"",sessionName:t?.name,...s,totalActiveMs:r,...eA?{contextUsage:eA}:{}}:null},[I,ta,eA,eP,w?.sessionId,w?.context.messages,w?.filePath,w?.totalActiveMs,w?.stats,t?.id,t?.name]),nW=(0,i.useCallback)((e,t,n,r)=>{nd.current&&tP.current===t&&ne.current===n&&!(r<=eF.current)&&(eF.current=r,e?.contextUsage!==void 0&&eL(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eW({sessionId:t,value:e.totalActiveMs}))},[]),nO=(0,i.useCallback)(async e=>{let t=ne.current,n=++eO.current;try{let r=await fetch(aE(e));if(!r.ok)return;let i=await r.json();nW(i.state,e,t,n)}catch{}},[nW]),nF=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:nc.current.get(i);if(s)return await s;let l=(async()=>{let i=!1,s=++ni.current;try{t&&S(!0);let l=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&l.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${l}`);if(404===o.status)return t&&(j(null),E(null),M([]),L([]),O(null),D(!1),H(0),N(null)),az(e),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let a=await o.json();if(tP.current!==e)return null;(ns.current?.seq??0)<s&&(ns.current={sid:e,seq:s,messages:a.context.messages,entryIds:a.context.entryIds??[]});let d=aA(e),c=!!(a.snapshotRevision&&d?.revision===a.snapshotRevision&&d.entryIds.length>=(a.context.entryIds??[]).length),u=c?np.current:a.context.messages;if(j(c?{...a,context:{...a.context,messages:np.current,entryIds:nh.current,oldestEntryId:nm.current,hasMore:ng.current,turnsBefore:nx.current}}:a),E(a.leafId),c)aL({sessionId:e,revision:a.snapshotRevision,messages:np.current,entryIds:nh.current,leafId:a.leafId,oldestEntryId:nm.current,hasMore:ng.current,turnsBefore:nx.current,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:nh.current});else{let e={messages:np.current,entryIds:nh.current},t={messages:u,entryIds:a.context.entryIds??[]};P(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],l=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===l&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var o,a;let d=t.entryIds[l+n];if(void 0===d||(o=e.messages[i+n],a=t.messages[l+n],o.role!==a.role||("user"===o.role?aH(o)!==aH(a):"custom"===o.role?o.customType!==a.customType:o.timestamp!==a.timestamp)))break;r.set(d,a_(s,n))}return r})({...e,aliases:n},t)),M(t.messages),L(t.entryIds),O(a.context.oldestEntryId),D(a.context.hasMore),H(a.context.turnsBefore??0)}if(tO.current=void 0!==a.toolNames,nb(void 0!==a.toolNames?(0,aP.YO)(a.toolNames):aP.Q8),eq(e=>no.current?e:null),eN(null),N(null),"summary"===a.treeFormat&&a.snapshotRevision&&aL({sessionId:e,revision:a.snapshotRevision,messages:u,entryIds:a.context.entryIds??[],leafId:a.leafId,oldestEntryId:a.context.oldestEntryId,hasMore:a.context.hasMore,turnsBefore:a.context.turnsBefore??0,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:a.context.entryIds??[]}),a.wrapperRebuilt&&(ty.current?.close("rebuilt"),ty.current?.maintain(e)),!n&&a.context.thinkingLevel&&"off"!==a.context.thinkingLevel&&eE(a5(a.context.thinkingLevel)),i=!0,t&&S(!1),!n)return null;try{let t=ne.current,n=++eO.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tP.current!==e)return null;let s=i.state;return nE(s),s?(nW(s,e,t,n),void 0!==s.systemPrompt&&eB(s.systemPrompt??null),void 0!==s.extensionStatuses&&tm(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tx(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tb(a3(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&e1(s.autoCompactionEnabled??!0)):i.running||tb({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return N(String(e)),"error"}finally{t&&!i&&S(!1)}})();return r?.force||nc.current.set(i,l),l.finally(()=>{nc.current.get(i)===l&&nc.current.delete(i)}),await l},[nW,nb,nE]),nD=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,l=await fetch(s,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let o=await l.json();if(tP.current!==e||r?.signal?.aborted||!nd.current)return;return O(o.context.oldestEntryId),D(o.context.hasMore),H(o.context.turnsBefore??0),j(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...o.context.messages,...t.context.messages],entryIds:[...o.context.entryIds,...t.context.entryIds],oldestEntryId:o.context.oldestEntryId,hasMore:o.context.hasMore,turnsBefore:o.context.turnsBefore}:o.context;return{...t,context:r}}),n?(M(e=>[...o.context.messages,...e]),L(e=>[...o.context.entryIds,...e])):(M(o.context.messages),L(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),nB=(0,i.useCallback)(async e=>{try{let t=await aI(e,{type:"get_tools"});if(!t||!nd.current||tP.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nb(tO.current?r(t):aP.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,nb]),nH=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",i=tP.current;if(b&&r&&i&&!t3.current&&(t3.current=!0,s)){if(s!==i){na.current.set(s,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(s,i):lV(s,i)}d?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},s)}},[b,r,s,d,e.chatInputRef]),n_=(0,i.useCallback)(async()=>{if(tP.current||!b||!r)return tP.current;if(t1.current)return t1.current;let e=(async()=>{let e=t5.current,t=t6.current;e&&eJ(e);let n=(0,aP.xG)(ex);tO.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok){let e=await i.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${i.status}`,n=aC(e);throw n?new aN(t,i.status,void 0,void 0,n):Error(t)}let s=await i.json(),l=s.sessionId;return tP.current=l,s.model&&t5.current===e&&(eJ(s.model),e||eg(s.model)),s.thinkingLevel&&t6.current===t&&(eE(a5(s.thinkingLevel)),t||ej(a5(s.thinkingLevel))),l})();t1.current=e;try{return await e}finally{t1.current=null}},[b,r,ex]),nU=(0,i.useCallback)(async()=>{let e=tP.current??await n_();if(!e)return;let[t]=await Promise.all([aI(e,{type:"get_state"}),nB(e)]);nd.current&&tP.current===e&&(nE(t),eB(t.systemPrompt??""))},[n_,nB,nE]),nq=(0,i.useCallback)(e=>{t2.current=e,tr(e)},[]),nK=(0,i.useCallback)(()=>{t8.current+=1,t4.current=null,nq([])},[nq]),nV=(0,i.useCallback)(()=>{let e=++t8.current,t=(async()=>{let t=tP.current??await n_();if(!t)return t8.current===e&&nq([]),[];ts(!0);try{let n=await aI(t,{type:"get_commands"}),r=n?.commands??[];return t8.current===e&&nq(r),r}catch(t){return console.error("Failed to load slash commands:",t),t8.current===e&&nq([]),null}finally{t8.current!==e&&t4.current||ts(!1)}})();t4.current=t;let n=()=>{t4.current===t&&(t4.current=null)};return t.then(n,n),t},[n_,nq]),nZ=(0,i.useCallback)(async()=>await nV()??[],[nV]),nJ=(0,i.useCallback)(async()=>{let e=t4.current,t=t2.current;return!e&&t.length>0?t:await (e??nV()).catch(()=>null)??(t.length>0?t:null)},[nV]),nY=(0,i.useCallback)(()=>{tj.current+=1,tk.current=!1,tA.current=null,tw.current&&(clearTimeout(tw.current),tw.current=null)},[]),nG=(0,i.useCallback)(e=>{ty.current?.close(e)},[]),nX=(0,i.useCallback)(e=>ty.current.ensureConnected(e),[]),nQ=(0,i.useCallback)(e=>{ty.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return nd.current=!0,tS.current=!1,nQ(e),()=>{tP.current===e&&ty.current?.close("deselected")}},[nQ,t?.id]);let n0=(0,i.useCallback)(e=>{let t=t$.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,l=Date.now();tI.current.inFlightSince=l,tI.current.requests+=1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store",signal:n.signal});return t=r.status,s=r.ok?await r.json():null}catch(e){return n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),t$.current===i&&(t$.current=null);try{let e=tI.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-l),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),t$.current=i,i.promise},[]),n1=!q&&!V&&!eX&&0===tc.length&&0===tp.length;(0,i.useEffect)(()=>{let e=t?.id;if(!e||!n1)return;let n=!1,r=null,i=()=>!n&&"hidden"===document.visibilityState&&!tS.current&&tP.current===e&&tW.current===e&&!tF.current&&!t_.current,s=async()=>{if(r=null,tR.current=null,!i())return;let t=await n0(e);if(i()){if(!("unanswered"===t||t&&!aK(t)))return void l();tS.current=!0,tM.current={count:tM.current.count+1,lastAt:Date.now()},nG("released")}},l=()=>{null===r&&(r=setTimeout(()=>void s(),3e4),tR.current=Date.now()+3e4)},o=()=>{"hidden"===document.visibilityState?l():r&&(clearTimeout(r),r=null,tR.current=null)};return"hidden"===document.visibilityState&&l(),document.addEventListener("visibilitychange",o),()=>{n=!0,r&&clearTimeout(r),tR.current=null,document.removeEventListener("visibilitychange",o)}},[nG,n1,tC,n0,t?.id]);let n2=(0,i.useCallback)(async(e,t)=>{let n=tP.current;if(tu(t=>aj(t,e.id)),n)try{await aI(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),n4=(0,i.useCallback)(async(e,t)=>{let n=tP.current;if(n)try{await aI(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),n8=(0,i.useCallback)(e=>{let t=e.message.trim();t&&to({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),n3=(0,i.useRef)(e.t);n3.current=e.t;let n5=(0,i.useCallback)((e,t)=>n3.current(e,t),[]),n6=(0,i.useCallback)(()=>{n8({type:"warning",message:n5("chat.sendUnconfirmed")})},[n8,n5]),n9=(0,i.useCallback)(e=>{nd.current&&M(t=>a4(t,e.bubble));let t=aA(e.sid);t?.messages.includes(e.bubble)&&aL({...t,messages:a4(t.messages,e.bubble)})},[]),n7=(0,i.useCallback)((e,t,n)=>{let r=nr.current;if(!r||r.runId!==t||r.sid!==e)return;nr.current=null;let i=ns.current,s=i?.sid===e&&i.seq>n?i:null,l=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&l>=0&&a8(s.messages.slice(l),r.key)>r.sameTextAfterSend||(nM(r.message,r.images,r.draftKey),s&&n9(r),n8(s&&!r.command&&l===s.entryIds.length?{type:"error",message:n5("chat.sendNotReceived")}:{type:"warning",message:n5("chat.sendUnconfirmed")}))},[n8,n9,nM,n5]),re=(0,i.useCallback)(()=>{let e=nr.current;if(nr.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});lK(e.parkedDraftKey,e.message,t)}else nM(e.message,e.images,e.draftKey);n9(e)}},[n9,nM]),rt=(0,i.useRef)(re);rt.current=re;let rn=(0,i.useCallback)(t=>{switch(ay(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":tu(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":n8({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tm(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tx(e=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"aboveEditor";if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},s=e.findIndex(e=>e.key===t);return -1===s?[...e,i]:e.map((e,t)=>t===s?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":th(e=>{let n;return t.closed?aj(e,t.id):-1===(n=e.findIndex(e=>e.id===t.id))?[...e,t]:e[n]===t?e:e.map((e,r)=>r===n?t:e)})}},[n8,a,e.chatInputRef]),rr=(0,i.useCallback)(()=>{let e=tF.current;return tF.current=!1,K(!1),e6(null),eR(null),R(new Map),U({type:"end"}),e},[U]),ri=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return tH.current!==e&&(tH.current=e,l?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[l]),rs=(0,i.useCallback)(e=>{if(tW.current===e)return void nY();nY(),tk.current=!0;let t=tj.current,n=async()=>{if(t===tj.current&&tP.current===e&&tk.current)try{let r=await fetch(aE(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tj.current||tP.current!==e||!tk.current)return;let s=i.state;if(nE(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tk.current=!1,tw.current=null,tA.current=null,tD.current=!!s?.isStreaming,tB.current=!!s?.isPromptRunning,tF.current=!0,K(!0),e6(e=>ab(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){eQ(!0),tw.current=setTimeout(()=>void n(),600),tA.current=Date.now()+600;return}tk.current=!1,tw.current=null,tA.current=null,nG("grace_end")}catch{if(t!==tj.current||tP.current!==e||!tk.current)return;tw.current=setTimeout(()=>void n(),600),tA.current=Date.now()+600}};tw.current=setTimeout(()=>void n(),3e4),tA.current=Date.now()+3e4},[nY,nG,nE]),rl=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tP.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ne.current;if(ne.current!==t)return;let n=ni.current;try{e&&await nF(e)}finally{if(ne.current!==t)return;e&&n7(e,t,n);let r=tB.current,i=tD.current;tB.current=!1,tD.current=!1,nt.current=null;let s=rr();r?ri(t):i&&s&&l?.({aborted:!1}),e&&rs(e)}},[nF,ri,l,rs,rr,n7]),ro=(0,i.useCallback)(async(e,t)=>{await a7(800);let n=Date.now();for(;tF.current&&Date.now()-n<2e4;){if(void 0!==t&&ne.current!==t)return;try{let n=await fetch(aE(e));if(n.ok){let r=await n.json(),i=r.state;if(nE(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rl(e,t)}}catch{}await a7(600)}},[rl,nE]),ra=(0,i.useCallback)(async e=>{let t=tU.current+1;for(tU.current=t;t_.current&&tU.current===t&&tP.current===e;){await a7(1e3);try{let n=await fetch(aE(e));if(!n.ok)continue;let r=await n.json();if(nE(r.state),r.state?.isBashRunning)continue;if(await nF(e),tU.current!==t||tP.current!==e)return;t_.current=!1,Z(!1),Y(null);return}catch{}}},[nF,nE]),rd=(0,i.useCallback)(async e=>{if(!tF.current||tP.current!==e)return;let t=ne.current,n=++eO.current;try{let r=await fetch(aE(e));if(!r.ok)return;let i=await r.json();if(tP.current!==e||ne.current!==t)return;let s=i.state;if(nW(s,e,t,n),nE(s),eQ(s?.isCompacting??!1),e1(s?.autoCompactionEnabled??!0),tb(a3(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tD.current=!!s.isStreaming,tB.current=!!s.isPromptRunning;return}if(!tF.current)return;s&&(void 0!==s.extensionStatuses&&tm(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tx(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nd.current&&tP.current===e&&t.state?.systemPrompt!==void 0&&eB(t.state.systemPrompt??null)}).catch(()=>{})),await rl(e,t)}catch{}},[nW,rl,nE]);(0,i.useEffect)(()=>{if(!q)return;let e=()=>{let e=tP.current;e&&rd(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[q,rd]),(0,i.useEffect)(()=>{tF.current=q},[q]),tq.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(U({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);tu(e=>aw(e,t)),th(e=>aw(e,t))}!0===e.isStreaming&&(nY(),tD.current=!0,tF.current=!0,K(!0),e6({kind:"waiting_model"})),tP.current&&nO(tP.current);break;case"agent_start":nl(),nY(),tD.current=!0,tF.current=!0,K(!0),e6({kind:"waiting_model"}),eR(null),U({type:"start"});break;case"agent_end":if(!tF.current)break;if(e6(null),eR(null),U({type:"end"}),tP.current){let e=tP.current,t=ne.current,n=++eO.current;nF(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nd.current&&tP.current===e&&ne.current===t&&(nE(r.state),nW(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eB(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tm(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tx(r.state.extensionWidgets??[]),tb(a3(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=tD.current;if(tD.current=!1,!t||tB.current)break;let n=tP.current,r=rr();eQ(!1),n&&(nF(n),rs(n)),r&&l?.({aborted:!0===e.aborted,...!0===e.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{nl();let t=ne.current,n=tB.current;tB.current=!1,nt.current=null;let r=ri(t,!0===e.aborted,!0===e.subagentsActive);if(!n&&!r)break;let i=tP.current;i&&nF(i),!tD.current&&(rr(),i&&rs(i))}break;case"prompt_error":n8({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":n8({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tF.current||aG(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(U({type:"snapshot",message:t}),t.content.length>0&&e6(null)):t&&e6(null)}else{let t=e.assistantMessageEvent;t&&(U({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&e6(null))}!tZ.current&&tJ.current&&null===tG.current&&(tG.current=requestAnimationFrame(()=>{tG.current=null,tJ.current&&nj("auto")}));break;case"message_end":{if(!tF.current||aG(e))break;let t=e.message;if(t&&"user"===t.role){let e=aS(t),n=aH(e),r=nt.current;nt.current=null,r&&nl(),M(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&aH(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let n=Array.isArray(e.transcriptNotices)?e.transcriptNotices:void 0;if(M(e=>{var r;return[...e,(r=aS(t),n&&0!==n.length?{...r,[sZ]:[...n]}:r)]}),"assistant"===t.role){let e=tP.current;e&&nO(e)}}U({type:"end"}),e6({kind:"waiting_model"});break}case"tool_execution_start":{if(aY(e))break;let t=e.toolCallId,n=e.toolName;e6(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(aY(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===sP)&&Array.isArray(i)&&R(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===sP?function(e){if(!sO(e))return null;let{calls:t}=sD(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args.length>120?`${n.args.slice(0,117)}...`:n.args;return r?`${n.name} ${r}`:n.name}(e.partialResult):function(e){if(!aX(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>aX(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);e6(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),l={id:t,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),l]}});break}case"tool_execution_end":{if(aY(e))break;let t=e.toolCallId;o?.(e.toolName),R(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),e6(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":nl(),tb({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eR({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eR(null);break;case"auto_compaction_start":case"compaction_start":eQ(!0),e4(null),e3(null);break;case"auto_compaction_end":case"compaction_end":eQ(!1),e.errorMessage?(e4(e.errorMessage),e3(null)):!e.aborted&&(e3(dn(e.result,e.reason??"auto")),tP.current&&nF(tP.current));break;case"extension_ui_request":rn(e);break;case"extension_ui_closed":tu(t=>aj(t,e.id))}},[n8,nW,nY,U,rn,nF,nl,ri,l,o,nO,rs,nj,rr,nE]);let rc=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tF.current||t_.current)return void nM(e,n,n$);if(nT&&(nA(null),!await tQ.current?.(nT))){nA(nT),nM(e,n,n$);return}let s=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await tX.current?.(r,t):void nM(e,n,n$)}let l=ne.current+1;nY(),tB.current=!0;let o=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:o?.length?[...e.trim()?[{type:"text",text:e}]:[],...o]:e,timestamp:Date.now()},d=aH(a),c=nh.current,u=c.at(-1)??null,p=a8(np.current.slice(c.length),d);M(e=>[...e,a]),nt.current=d,ne.current=l,tF.current=!0,K(!0),e6(s?{kind:"running_command"}:{kind:"waiting_model"}),U({type:"start"}),tZ.current=!0,e7(!0);let h=()=>{M(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nt.current=null},f=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),m=null,g=!1;try{if(b&&r){let t=tP.current??await t1.current,n=t??await n_();if(!n)throw Error("Unable to create a session for the prompt");m=n,eh&&(eJ(eh),t&&await aI(n,{type:"set_model",provider:eh.provider,modelId:eh.modelId})),nd.current&&await nX(n).catch(e=>{if(nd.current)throw e}),g=!0;let r=await aI(n,{type:"prompt",message:e,...f?.length?{images:f}:{}});r?.queued&&h(),nH(1,e)}else if(t){m=t.id,await nX(t.id),g=!0;let n=await aI(t.id,{type:"prompt",message:e,...f?.length?{images:f}:{}});n?.queued&&h()}else throw Error("No active session for the prompt");el(null),s&&m&&ro(m,l)}catch(t){if(console.error("Failed to send message:",t),!(!g||a$(t))&&m){nn.current!==l&&(nr.current={runId:l,sid:m,message:e,images:n,draftKey:n$,parkedDraftKey:b&&r?lO(r):null,lastEntryIdAtSend:u,sameTextAfterSend:p,bubble:a,key:d,command:s},nd.current||re()),ro(m,l);return}if(tB.current=!1,M(e=>a4(e,a)),t instanceof aN&&t.missingCwd?el(t.missingCwd):n8({type:"error",message:t instanceof Error?t.message:String(t)}),nM(e,n,n$),nt.current=null,m)return void rd(m);tF.current=!1,nG("send_failed"),K(!1),e6(null),U({type:"end"})}},[b,r,eh,t,n_,nX,nH,ro,n8,re,nY,nG,n$,U,rd,nM,nT,nA]);tX.current=(0,i.useCallback)(async(e,n)=>{if(tF.current||t_.current)return;let r=`${n?"!!":"!"}${e}`;t_.current=!0,Y({command:e,excludeFromContext:n}),Z(!0);try{let i=tP.current??t?.id??await n_();if(!i)throw Error("Unable to create a session for the shell command");await aI(i,{type:"bash",command:e,excludeFromContext:n}),await nF(i),nH(1,r)}catch(e){console.error("Failed to execute shell command:",e),n8({type:"error",message:e instanceof Error?e.message:String(e)}),nM(r,void 0,n$)}finally{t_.current=!1,Y(null),Z(!1)}},[n8,n$,n_,nF,nH,nM,t]);let ru=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nM(n,t.images,n$):n&&e.chatInputRef?.current?.prependText(n)},[n$,e.chatInputRef,nM]),rp=(0,i.useCallback)(async()=>{let e=tP.current;if(e){if(t_.current){try{await aI(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{ru(await aI(e,{type:"abort"}))}catch(e){console.error("Failed to abort:",e)}}},[ru]),rh=(0,i.useCallback)(async e=>{if(t_.current)return;let t=tP.current;if(t){e_(e);try{let{cancelled:n,newSessionId:r}=await aI(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e),n8({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e_(null)}}},[n8,c]),rf=(0,i.useCallback)(async e=>{if(t_.current)return!1;let t=tP.current;if(!t)return!1;try{let n=await aI(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tP.current!==t)return!1;return await nF(t),tP.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nF]);tQ.current=rf;let rm=(0,i.useCallback)(async e=>{if(t_.current||tF.current||eX)return;E(e);let t=tP.current;t&&(await nD(t,e),e&&aI(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[eX,nD]),rg=(0,i.useCallback)(async(e,t)=>{if(b){let n={provider:e,modelId:t};t5.current=n,ef(n),eJ(n),null===t6.current&&ej(a5(t9.current[`${e}/${t}`])??t7.current);let r=tP.current??await t1.current;if(!r)return;try{await aI(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tP.current;if(n&&!no.current){no.current=!0,eq({provider:e,modelId:t}),eG(!0);try{let r=await aI(n,{type:"set_model",provider:e,modelId:t});eV({provider:r.provider,modelId:r.id}),no.current=!1,await nF(n)}catch(e){console.error("Failed to set model:",e),no.current=!1,eq(eU),n8({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nF(n,!1,!0)}finally{no.current=!1,eG(!1)}}},[n8,eU,b,nF,ef]),rx=(0,i.useCallback)(async e=>{let t=tP.current;if(!t||eX)return!0;eQ(!0),e4(null),e3(null);try{let n=await aI(t,{type:"compact",...e?{customInstructions:e}:{}});return e3(dn(n,"manual")),await nF(t,!0)&&nH(),!0}catch(e){return e4(e instanceof Error?e.message:String(e)),e3(null),!1}finally{eQ(!1)}},[eX,nF,nH]),rv=(0,i.useCallback)(()=>e4(null),[]),rb=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",s=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models",l=null;try{let t=await fetch(s,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error),l=aC(n)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(ei(l),en(l?null:t instanceof Error?t.message:String(t))),t}ei(null),X(n.models),en(n.modelError??null),ea(n.modelScopeWarnings??[]),ec(n.thinkingLevels??{}),ep(n.thinkingLevelMaps??{});let o=n.modelList??[];ee(o);let a=n.defaultModel?o.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(eg(a?{provider:a.provider,modelId:a.id}:null),t9.current=n.thinkingLevelPins??{},t7.current=a5(n.defaultThinkingLevel),eS(a5(n.savedDefaultThinkingLevel)),b&&!tP.current){let e=t5.current,t=e&&(0===o.length||o.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(t5.current=null,ef(null));let r=t?e:a&&{provider:a.provider,modelId:a.id},i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===t6.current&&ej(a5(i)??t7.current)}},[b,r,t?.cwd]),ry=(0,i.useCallback)(async e=>{let n=r??t?.cwd,i=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{cwd:n}:{},...e})});if(i.ok)return;let s="";try{let e=await i.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(s=e.error)}catch{}throw Error(s||`HTTP ${i.status}`)},[r,t?.cwd]),rw=(0,i.useCallback)(()=>{rb().catch(()=>{})},[rb]),rj=(0,i.useCallback)(async(e,t)=>{try{await ry({provider:e,modelId:t})}catch(e){n8({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}n8({type:"success",message:`Default model: ${e}/${t}`}),eg({provider:e,modelId:t}),(nS?.provider!==e||nS?.modelId!==t)&&await rg(e,t),rw()},[n8,nS,rg,rw,ry]),rk=(0,i.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),l=tP.current??await n_(),o=e=>(e.handled&&(e.error?n8({type:"error",message:e.error}):e.action||n8({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!l||eX)return o({handled:!0,error:"No active session to compact"});return rx(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),o({handled:!0,action:"compact"});case"auto-compact":{if(!l)return o({handled:!0,error:"No active session"});let e=await aI(l,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await aI(l,{type:"set_auto_compaction",enabled:t}),e1(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!l)return o({handled:!0,error:"No active session to reload"});return await aI(l,{type:"reload"}),await Promise.all([nF(l,!1,!0),nB(l),nZ(),rb()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!l)return o({handled:!0,error:"No active session to name"});if(!s)return o({handled:!0,error:"Usage: /name <name>"});return await aI(l,{type:"set_session_name",name:s}),await nF(l)&&nH(),o({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!l)return o({handled:!0,error:"No active session"});let e=await aI(l,{type:"get_session_stats"});return e&&td(e),g?.(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!x)return{handled:!1};let e=await nJ();if(!e||!(e.some(lQ)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return x("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!l)return o({handled:!0,error:"No active session"});let e=await aI(l,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!l)return o({handled:!0,error:"No active session to clone"});if(tF.current||t_.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=await aI(l,{type:"clone",leafId:$});if(e?.cancelled||!e?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=o({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return o({handled:!0,error:e instanceof Error?e.message:String(e)})}},[$,n8,n_,rx,eX,rb,nF,nZ,nB,nH,x,c,g,e.chatInputRef,nJ]),rS=(0,i.useCallback)(async(e,t,n)=>{let r=tP.current;if(nT)return void nM(e,n,n$);if(!r){nM(e,n,n$),n8({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await aI(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nM(e,n,n$),t instanceof aN&&t.missingCwd)return void el(t.missingCwd);a$(t)?n8({type:"error",message:t.message}):n6()}},[n8,n6,n$,nT,nM]),rC=(0,i.useCallback)(async(e,t)=>{await rS(e,"steer",t)},[rS]),rN=(0,i.useCallback)(async(e,t,n)=>{await rS(e,t,n)},[rS]),r$=(0,i.useCallback)(async(e,t)=>{await rS(e,"followUp",t)},[rS]),rE=(0,i.useCallback)(async()=>{let e=tP.current;if(e)try{await aI(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rI=(0,i.useCallback)(async()=>{let e=tP.current;if(e)try{let t=await aI(e,{type:"clear_queue"});tb({steering:[],followUp:[]}),ru(t)}catch(e){console.error("Failed to recall queued messages:",e),n8({type:"error",message:"Failed to recall queued messages"})}},[n8,ru]),rM=(0,i.useCallback)(async e=>{if("auto"===e){t6.current=null,ey(null),eN(null);return}b?(t6.current=e,ey(e)):eN(e);let t=tP.current??await t1.current;if(t)try{await aI(t,{type:"set_thinking_level",level:e}),nd.current&&tP.current===t&&(eE(e),eN(null))}catch(e){console.error("Failed to set thinking level:",e),eN(null)}},[b]),rT=(0,i.useCallback)(async e=>{try{await ry({thinkingLevel:e})}catch(e){n8({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}n8({type:"success",message:`Default reasoning level: ${e}`}),eS(e),nN!==e&&await rM(e),rw()},[n8,nN,rM,rw,ry]),rR=(0,i.useCallback)(async e=>{let t=(0,aP.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:aO();if(t)try{t.setItem(aW,e)}catch{}}(e),nb(e);let n=tP.current??await t1.current;if(!n){tO.current=void 0!==t;return}try{let e=await aI(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tO.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(nY(),nG("set_tools"),tu([]),th([]),tP.current=r,e?.recreated&&tW.current===r&&nQ(r)),nK(),tm([]),tx([]);let[i]=await Promise.all([aI(r,{type:"get_state"}),nB(r)]);nd.current&&tP.current===r&&(eB(i.systemPrompt??""),nE(i))}catch(e){console.error("Failed to set tools:",e)}},[nY,nK,nG,nB,nQ,nb,nE]),rA=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=t0.current;n&&(null!==tG.current&&(cancelAnimationFrame(tG.current),tG.current=null),tK.current=!0,tZ.current=!1,tJ.current=!1,e7(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tY.current=n.scrollTop)},[]),rL=(0,i.useCallback)(()=>{let e=t0.current,t=tV.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==tG.current&&(cancelAnimationFrame(tG.current),tG.current=null),tJ.current=!0,tY.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),rz=(0,i.useCallback)(()=>{let e=t0.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tF.current,s=tJ.current,l=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!aQ(n,r,i)||!(n<t)&&(!!(!e&&n>t&&aQ(n,r,i,s))||e)}(s,tY.current,t,n,r,i?96:8);tJ.current=l,tY.current=t;let o=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!aQ(e,t,n,r)}(t,n,r);tt(e=>e===o?e:o),!s&&l&&i?nj("auto"):l||null===tG.current||(cancelAnimationFrame(tG.current),tG.current=null)}},[nj]),rP=(0,i.useCallback)((e,t)=>{t?.running&&(nB(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tD.current=!!t.state.isStreaming,tB.current=!!t.state.isPromptRunning,tF.current=!0,K(!0),e6(e=>ab(e,t.state?.isStreaming===!0)),U({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&ro(e)),t.state?.isBashRunning&&(t_.current=!0,Z(!0),ra(e))),t?.state&&(void 0!==t.state.isCompacting&&eQ(t.state.isCompacting),void 0!==t.state.systemPrompt&&eB(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tm(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tx(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tb(a3(t.state.queuedMessages)))},[U,nB,ra,ro]);tE.current=(e,t)=>{!tS.current||(tS.current=!1,tT.current={count:tT.current.count+1,lastAt:Date.now(),lastReason:t},tN(e=>e+1),nd.current&&tP.current===e&&tW.current===e&&(nQ(e),nF(e,!1,!0).then(t=>{nd.current&&tP.current===e&&rP(e,t)})))},(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=tI.current,i=async()=>{let t=await n0(e);!n&&"hidden"===document.visibilityState&&aK(t)&&tE.current(e,"activity")};i();let s=setInterval(()=>void i(),3e4);r.renewStartedAt=Date.now();let l=()=>{"visible"===document.visibilityState&&(tE.current(e,"visible"),i())};return document.addEventListener("visibilitychange",l),()=>{n=!0,clearInterval(s),r.renewStartedAt=null,document.removeEventListener("visibilitychange",l)}},[n0,t?.id]),(0,i.useEffect)(()=>{if(nd.current=!0,eF.current=eO.current,t){tP.current=t.id;let e=aA(t.id);e&&(j({sessionId:t.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),E(e.leafId),M(e.messages),L(e.entryIds),O(e.oldestEntryId),D(e.hasMore),H(e.turnsBefore),N(null),S(!1)),nF(t.id,!e,!0,{force:!0}).then(e=>{rP(t.id,e)})}return()=>{nd.current=!1;let e=b?s:null;e&&queueMicrotask(()=>{nd.current||t3.current||l_(e)});let t=tP.current,n=nu.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=aA(t),r=nh.current;!e||function(e,t){if(0===t.length)return!0;let n=new Set([...e.entryIds,...e.loadedEntryIds]);return t.every(e=>n.has(e))}(e,r)?aL({sessionId:t,revision:n.snapshotRevision,messages:np.current,entryIds:nh.current,leafId:nf.current,oldestEntryId:nm.current,hasMore:ng.current,turnsBefore:nx.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nh.current}):az(t)}rt.current(),null!==tG.current&&(cancelAnimationFrame(tG.current),tG.current=null),tU.current+=1,nY(),nG()}},[]),(0,i.useEffect)(()=>{h?.(eD)},[eD,h]),(0,i.useEffect)(()=>(m?.(nU),()=>m?.(null)),[nU,m]);let rW=(0,i.useCallback)(()=>{let e,t=null;try{t=ty.current?.snapshot?.()??null}catch{t=null}let n=tP.current,r=tI.current,i=tT.current;return{pageId:"string"==typeof(e=globalThis[eM])?e:null,sessionId:n,selectedSessionId:tW.current,mounted:nd.current,wantsStream:null!==n&&nv(n),connection:t,released:{active:tS.current,...tM.current},reattached:{...i},hiddenReleaseDueAt:tR.current,hiddenGraceMs:3e4,graceDueAt:tA.current,run:{agentRunning:tF.current,bashRunning:t_.current,compacting:tL.current,dialogs:tz.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nv]);(0,i.useEffect)(()=>(v?.(rW),()=>v?.(null)),[rW,v]);let rO=q||V||eX;(0,i.useEffect)(()=>{p&&p(w?.tree??[],$,rm,rO)},[w?.tree,$,rm,rO,p]),(0,i.useEffect)(()=>{let e=t0.current;if(e)return tY.current=e.scrollTop,e.addEventListener("scroll",rz,{passive:!0}),()=>{e.removeEventListener("scroll",rz)}},[I.length,k,rz]),(0,i.useEffect)(()=>{q||e7(!1)},[q]),(0,i.useLayoutEffect)(()=>{I.length>0&&(tZ.current?(tZ.current=!1,tK.current=!0,rL()):tK.current?!tF.current&&tJ.current&&nj("auto"):(tK.current=!0,nj("instant")))},[I.length,q,nj,rL]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rb(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=a9.length||(await a7(a9[t]),e.signal.aborted))return}})(),()=>e.abort()},[rb,u]),(0,i.useEffect)(()=>{if(!e8)return;let e=setTimeout(()=>e3(null),6e3);return()=>clearTimeout(e)},[e8]);let[rF,rD]=(0,i.useState)(null),rB=(0,i.useRef)(5e3),rH=(0,i.useRef)(null),r_=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tl.visible.length){r_.current=null;return}let e=tl.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{to({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tl.visible[0];if(!t||(r_.current!==t.id&&(r_.current=t.id,rB.current=5e3),tl.visible.some(e=>e.id===rF)))return;rH.current=Date.now();let n=setTimeout(()=>{to({type:"mark_oldest_exiting"})},rB.current);return()=>{clearTimeout(n),null!==rH.current&&(rB.current=Math.max(0,rB.current-(Date.now()-rH.current)),rH.current=null)}},[tl.visible,rF]),(0,i.useEffect)(()=>{td(null)},[I.length,eA?.tokens,eA?.percent,eA?.contextWindow]);let rU=nN??"auto",rq=tc[0]??null,rK=Math.max(0,tc.length-1),rV=tp[0]??null,rZ=Math.max(0,tp.length-1),rJ=(0,i.useMemo)(()=>(function(e,t,n){let r=e[e.length-1],i=[];for(let s=0;s<t;s++){let t=e[s];i.push(void 0===t?a_(r,s-e.length):n.get(t)??t)}return i})(A,I.length,z),[A,I.length,z]);return{data:w,loading:k,error:C,activeLeafId:$,messages:I,activeToolResults:T,entryIds:A,messageKeys:rJ,historyCursor:W,hasEarlierMessages:F,earlierTurnCount:B,streamingStore:_,agentRunning:q,modelNames:G,modelList:Q,modelError:et,missingCwd:es??er,modelScopeWarnings:eo,modelThinkingLevels:ed,modelThinkingLevelMaps:eu,newSessionModel:eh,toolPreset:ex,thinkingLevel:rU,retryInfo:eI,contextUsage:eA,systemPrompt:eD,forkingEntryId:eH,isCompacting:eX,compactError:e2,compactResult:e8,currentModel:nk,displayModel:nS,modelSwitching:eY,sessionStats:nP,autoCompactionEnabled:e0,slashCommands:tn,slashCommandsLoading:ti,queuedMessages:tv,notices:tl.visible,extensionDialog:rq,waitingExtensionDialogCount:rK,extensionCustomUi:rV,waitingExtensionCustomUiCount:rZ,extensionStatuses:tf,extensionWidgets:tg,respondToExtensionUi:n2,sendExtensionCustomInput:n4,isAutoModelSelection:b&&null===eh,isAutoThinkingSelection:b&&null===eb,defaultModel:em,savedDefaultThinkingLevel:ek,agentPhase:e5,isNew:b,editEntryId:nT,promptAnchorActive:e9,showScrollToBottom:te,sessionIdRef:tP,scrollContainerRef:t0,lastUserMsgRef:tV,pendingScrollToUserRef:tZ,initialScrollDoneRef:tK,handleSend:rc,handleAbort:rp,handleFork:rh,handleNavigate:rf,handleModelChange:rg,handleCompact:rx,handleSteer:rC,handleFollowUp:r$,handlePromptWithStreamingBehavior:rN,handleAbortCompaction:rE,dismissCompactError:rv,handleRecallQueue:rI,handleBuiltinSlashCommand:rk,handleEditContent:nL,cancelEdit:nT?nz:void 0,addNotice:n8,setNoticePaused:rD,handleToolPresetChange:rR,handleThinkingLevelChange:rM,handleSetDefaultModel:rj,handleSetDefaultThinkingLevel:rT,loadTools:nB,loadSlashCommands:nZ,setActiveLeafId:E,setData:j,setMessages:M,loadContext:nD,scrollToBottom:nj,scrollUserMsgToTop:rL,scrollToMessage:rA,dispatch:U,setAgentRunning:K,setForkingEntryId:e_,bashRunning:V,pendingBash:J,handleAgentEventRef:tq}}({session:o,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:X,onToolEnd:b,onAttentionNeeded:y,onSessionCreated:w,onSessionForked:j,modelsRefreshKey:k,chatInputRef:S,onBranchDataChange:C,onSystemPromptChange:N,onSystemToolsChange:$,onSystemInfoLoaderChange:E,onSessionStatsPanelOpen:T,onOpenSettings:R,onDebugSnapshotReaderChange:I,t:K,deferInitialScroll:!!ee}),tE=dr(eh,di),tI=dr(eh,ds),tM=(0,i.useCallback)(()=>eh.getState().streamingMessage,[eh]),tT=ef||em;(0,i.useEffect)(()=>{if(ef&&q)return q()},[ef,q]);let[tR,tA]=(0,i.useState)(null),[tL,tz]=(0,i.useState)(!1),[tP,tB]=(0,i.useState)(!1),[tH,t_]=(0,i.useState)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(()=>{tA(null),tz(!1),t_(null)},[]);(0,i.useEffect)(()=>{O||tK()},[O,tK]);let tV=(0,i.useCallback)(()=>{if(!O||tL)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t1.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tA(null);let r=e.toString().trim();if(!r)return void tA(null);let i=t.getBoundingClientRect(),s=[t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement,t.startContainer.nodeType===Node.ELEMENT_NODE?t.startContainer:t.startContainer.parentElement,t.endContainer.nodeType===Node.ELEMENT_NODE?t.endContainer:t.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);tA({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:s})},[O,tL]);(0,i.useEffect)(()=>{tL&&tR&&tq.current?.insertIfEmpty(rJ(tR.text,K("chat.quoteIntro"),K("chat.quoteQuestion")))},[tL,tR,K]),(0,i.useLayoutEffect)(()=>{let e=tU.current;if(!e||!tR)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(tR.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tR.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[tR,tL,tH]),(0,i.useEffect)(()=>{if(!tR)return;let e=e=>{tL||tU.current?.contains(e.target)||tK()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tP||tK())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tR,tL,tP,tK]);let tZ=(0,i.useCallback)(()=>{tR&&(S?.current?.insertText(rJ(tR.text,K("chat.quoteIntro"),K("chat.quoteQuestion"))),tK())},[S,tR,tK,K]),tJ=(0,i.useCallback)(async e=>{let t=e6.current??o?.id;if(!tP&&e.trim()&&tR?.sourceEntryId&&t&&W){tB(!0),t_(null),U?.();try{await W(e,t,tR.sourceEntryId),tK()}catch(t){tq.current?.restoreSubmission(e),t_(t instanceof Error?t.message:String(t))}finally{tB(!1)}}},[W,tR,tP,o?.id,e6,tK,U]),tY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ei||es||!F||tY.current||(tY.current=!0,D?.(),tn(F))},[F,ei,es,tn,D]),(0,i.useEffect)(()=>{let e=!!eH&&!G.current;G.current=!!eH,Z&&e&&J.current()},[Z,eH]),(0,i.useEffect)(()=>{l=tT?tr:null},[tT,tr]);let[tG,tX]=(0,i.useState)(50),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t4=(0,i.useRef)(!1),t8=(0,i.useRef)(!1),t3=(0,i.useRef)(ee);t3.current=ee;let[t5,t6]=(0,i.useState)(null),t9=el[ea.indexOf(t5?.entryId??"")],t7=t9?.role==="assistant"?t5?.blockIndex===void 0?t9.content.find(e=>"text"===e.type):t9.content[t5.blockIndex]:void 0,ne=(0,i.useRef)({entryIds:ea,historyCursor:ec,hasEarlierMessages:eu});ne.current={entryIds:ea,historyCursor:ec,hasEarlierMessages:eu};let nt=(0,i.useRef)(null),nn=(0,i.useCallback)(async(e,t,n)=>{nt.current=t;let r=await tS(e,tC,t,n);return r||nt.current!==t||(nt.current=null),r},[tC,tS]);(0,i.useEffect)(()=>{ec!==nt.current&&(nt.current=null)},[ec]),(0,i.useLayoutEffect)(()=>{let e=o?.id,t=e9.current,n=t1.current;if(e&&u&&t&&n)return()=>{if(t3.current)return;if(aQ(t.scrollTop,t.clientHeight,t.scrollHeight))return void u(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&u(e,{atBottom:!1,...i,oldestEntryId:ne.current.historyCursor})}},[ei,u,e9,o?.id]),(0,i.useEffect)(()=>{a&&et(null)},[a]),(0,i.useEffect)(()=>{let e=o?.id;if(!ee||!e||ei||a||t8.current)return;t8.current=!0;let t=new AbortController;return(async()=>{let n=ne.current;if(n.entryIds.includes(ee.anchorEntryId)){tX(e=>Math.max(e,2*n.entryIds.length)),er(!0);return}t4.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nn(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tN("instant"),et(null);return}if(tX(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ee.anchorEntryId))return void er(!0);if(n.oldestEntryId===ee.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tN("instant"),et(null))}finally{t4.current=!1}})(),()=>{t.abort(),et(null)}},[tC,nn,ei,ee,tN,a,o?.id]),(0,i.useLayoutEffect)(()=>{let e=t1.current;if(!ee||!e||a)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ee.anchorEntryId);if(t instanceof HTMLElement){t$(t,ee.anchorOffset),et(null);return}en&&(tN("instant"),et(null))},[ea,ee,en,tN,t$,a,tG]),(0,i.useEffect)(()=>{if(!a||ei)return;let e=new AbortController;return(async()=>{let t=ne.current,n=t.entryIds.includes(a.entryId);if(!n&&!tT&&t.hasEarlierMessages&&t.historyCursor&&!t4.current){t4.current=!0;let r=e9.current;r&&(t2.current=r.scrollHeight-r.scrollTop);let i=await nn(a.sessionId,t.historyCursor,{tail:200,signal:e.signal});t4.current=!1,n=!!i?.entryIds.includes(a.entryId)}e.signal.aborted||(n?(t2.current=null,tX(e=>Math.max(e,(ne.current.entryIds.length+200)*2)),t6(a)):d?.(a))})(),()=>e.abort()},[a,ei,tT,nn,d,e9]),(0,i.useLayoutEffect)(()=>{if(!t5||t5!==a)return;let e=`[data-entry-id="${CSS.escape(t5.entryId)}"]`,t=e9.current?.querySelector(t9?.role==="user"?e:`${e} [data-search-target]`);t&&(t$(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),t6(null),d?.(t5)},[t5,a,t9,e9,t$,d]),(0,i.useEffect)(()=>{let e=e9.current;if(!tQ||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t4.current)return;if(!eu){t2.current=e.scrollHeight-e.scrollTop,tX(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!ec||ec===nt.current)return;let n=o?.id??e6.current;n&&(t4.current=!0,t2.current=e.scrollHeight-e.scrollTop,nn(n,ec).finally(()=>{t4.current=!1}))},{root:e,threshold:0});return t.observe(tQ),()=>t.disconnect()},[tQ,tG,ec,eu,o,nn,e6,e9]),(0,i.useEffect)(()=>{tX(e=>Math.max(e,el.length))},[el.length]),(0,i.useEffect)(()=>{if(null==t2.current)return;let e=e9.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t2.current),t2.current=null}},[tG,e9]);let nr=eW?[eW.sessionId,eW.sessionFile??"",eW.sessionName??"",eW.userMessages,eW.assistantMessages,eW.toolCalls,eW.toolResults,eW.totalMessages,eW.tokens.input,eW.tokens.output,eW.tokens.cacheRead,eW.tokens.cacheWrite,eW.tokens.total,eW.cost??0,eW.totalActiveMs??0].join("|"):null,ni=(0,i.useRef)(eW);ni.current=eW,(0,i.useEffect)(()=>{M?.(ni.current)},[nr,M]),(0,i.useEffect)(()=>()=>{M?.(null)},[M]);let ns=e$?`${e$.percent??"null"}|${e$.contextWindow}|${e$.tokens??"null"}`:null,nl=(0,i.useRef)(e$);nl.current=e$,(0,i.useEffect)(()=>{A?.(nl.current)},[ns,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let no=(0,i.useCallback)(async e=>{let t=o?.cwd??h;if(!t)return void eG({type:"warning",message:K("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await tO(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let l=s.uploaded??[],o=s.skipped??[],a=(n=[...l,...o],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>tW(e.name,!1)).join(""));for(let e of(a&&S?.current?.insertText(a),l.length>0&&(eG({type:"success",message:K("chat.dropUploaded",{count:l.length})}),z?.()),o.length>0&&eG({type:"warning",message:K("chat.dropAlreadyExists",{names:o.join(", ")})}),s.errors??[]))eG({type:"error",message:K("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){eG({type:"error",message:K("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[eG,S,h,z,o?.cwd,K]),na=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&S?.current?.addImages(t),r.length>0&&eG({type:"warning",message:K("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&no(n)},[eG,S,K,no]),nd=(0,i.useCallback)(e=>{na(e.map(e=>({kind:"file",file:e})))},[na]),{isDragOver:nc,handleDragEnter:nu,handleDragOver:np,handleDragLeave:nh,handleDrop:nf}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{tF(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),l=(0,i.useCallback)(e=>{tF(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:l,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(tD(t.dataTransfer))},[e])}}(na),nm=el.filter(e=>rj(e)||"assistant"===e.role),ng=(0,i.useMemo)(()=>{let e=new Map(eo);for(let t of el)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eo,el]),nx=(0,i.useMemo)(()=>new WeakMap,[]),nv=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=el.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(el[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[el]),nb=(t=nm.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),ny=(0,i.useCallback)(()=>{tX(e=>Math.max(e,2*el.length))},[el.length]),nw=e8&&0===el.length&&!tE&&!tT;ti(e9,!!o?.id||!nw);let nj=o?.cwd??h??void 0,nk=(0,i.useRef)(null),nS=(0,i.useRef)(0),nC=(0,i.useRef)(null),nN=(0,i.useRef)(!1),n$=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nk.current;if(!ef||!tt){n$.current=null,nS.current=0,nN.current=!1,e&&(e.style.height="");return}let t=e9.current,n=t1.current,r=e7.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let l;if(i||e9.current!==t||t1.current!==n||e7.current!==r||nk.current!==e)return;let o=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-o+t.scrollTop-16),d=e.getBoundingClientRect().top-o+t.scrollTop,c=(s=t.clientHeight,0===(l=Math.max(0,a))?0:Math.max(0,Math.ceil(l+s-Math.max(0,d)))),u=!nN.current;u&&(nN.current=!0),c!==nS.current&&(nS.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tk())};n$.current=s,s();let l="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nC.current||(nC.current=requestAnimationFrame(()=>{nC.current=null,s()}))});return l?.observe(t),l?.observe(n),l?.observe(r),()=>{i=!0,n$.current===s&&(n$.current=null),l?.disconnect(),null!==nC.current&&(cancelAnimationFrame(nC.current),nC.current=null)}},[ef,e7,el.length,tt,e9,tk]);let nE=(0,i.useCallback)(()=>{n$.current?.()},[]);(0,i.useLayoutEffect)(nE,[tE,tI,nE]);let nI=eL?ej[`${eL.provider}:${eL.modelId}`]??null:null,nM=eL?ek[`${eL.provider}:${eL.modelId}`]??null:null,nT=(0,r.jsx)(an,{ref:S,onSend:tn,onAbort:tr,onSteer:ef?tu:void 0,onFollowUp:ef?tp:void 0,onPromptWithStreamingBehavior:ef?th:void 0,isStreaming:tT,model:eL,isAutoModelSelection:eX,modelNames:ex,modelList:ev,modelError:eb,missingCwd:ey,modelScopeWarnings:ew,onModelChange:ta,modelSwitching:eP,defaultModel:e1,onSetDefaultModel:ty,onCompact:o||e8?td:void 0,onAbortCompaction:tf,isCompacting:eI,compactError:eR,onDismissCompactError:tm,compactResult:eA,toolPreset:eS,onToolPresetChange:o||e8?tv:void 0,thinkingLevel:eC,isAutoThinkingSelection:eQ,onThinkingLevelChange:o||e8?tb:void 0,availableThinkingLevels:nI,thinkingLevelMap:nM,savedDefaultThinkingLevel:e2,onSetDefaultThinkingLevel:o||e8?tw:void 0,retryInfo:eN,queuedMessages:eD,inputHistory:nv,onRecallQueue:tg,slashCommands:eO,slashCommandsLoading:eF,onLoadSlashCommands:tj,onBuiltinCommand:tx,soundEnabled:B,onSoundToggle:H,onAudioUnlock:U,draftKey:o?.id??f??void 0,cwd:o?.cwd??h,onAttachFiles:nd});return ei?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:K("chat.loadingSession")}):es?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:es}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nu,onDragOver:np,onDragLeave:nh,onDrop:nf,children:[nc&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!V,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(df,{notices:eB,floating:!0,onPauseChange:eY})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eH&&(0,r.jsx)(dx,{request:eH,waitingCount:e_,onRespond:eZ},eH.id),eU&&(0,r.jsx)(dv,{request:eU,waitingCount:eq,onInput:eJ},eU.id),!nw&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:e9,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ee?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t1,onPointerUp:tV,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,s=-1;for(let e=el.length-1;e>=0;e--)if("user"===el[e].role){s=e;break}let l=-1;for(let e=el.length-1;e>=0;e--)if(rj(el[e])){l=e;break}let a=new Map,d=0;el.forEach((e,t)=>{(rj(e)||"assistant"===e.role)&&a.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??el[e];if(rw(n))return null;let l=!1===t.withNotices?[]:sJ(el[e]),d=rj(n)||"assistant"===n.role,c=a.get(e),u=t.keyPrefix??"message",p=ed[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<el.length;t++){let e=el[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tE&&e===el.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let f=(0,r.jsx)(s5,{message:n,toolResults:ng,modelNames:ex,cwd:nj,onOpenFile:L,onOpenSubagent:P,entryId:ea[e],searchBlock:ea[e]===t5?.entryId?t7:void 0,onFork:em||e8?void 0:ts,forking:eE===ea[e],onEditContent:tT?void 0:tl,onCancelEdit:to,isEditing:e3===ea[e],showTimestamp:h,prevTimestamp:e>0?el[e-1].timestamp:void 0,sessionId:o?.id??e6.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?td:void 0,isCompacting:t.recoverTruncation?eI:void 0,compactError:t.recoverTruncation?eR:void 0},`${u}-view-${p}`),m=l.length>0?(0,r.jsx)(s0,{notices:l},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":ea[e],ref:!1===t.attachRef?void 0:t=>{nb.current[c]=t,e===s&&(e7.current=t)},children:[f,m]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[f,m]},`${u}-${p}`)},u=[];for(let e=0;e<el.length;){let t,n=rj(el[e]);if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,o=e+1;for(;o<el.length&&!rj(el[o]);)o+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&rE(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(el,i,o);if(-1===d||(tT||tE)&&o===el.length&&i===l){for(let e=s;e<o;e++)u.push(c(e));e=o;continue}n&&u.push(c(i));let p=n&&ea[i]?function(e,t,n){let r,i,s,l=rV(e[t]?.timestamp);if(void 0===l)return;let o=!1,a=0;for(let l=t+1;l<n;l++){let t=e[l];if("assistant"===t.role){var d;void 0!==i&&void 0!==s&&(a+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=rV(e.timestamp),n=rV(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);o=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(d=t).role&&("stop"===d.stopReason||"length"===d.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=rV(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=rV(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(o&&void 0!==r)return Math.max(0,r-l-a)}(el,i,o):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=rE(t),i=r.length>0||rC(t)||rN(t)?rK(t,r):null,s=t.content.indexOf(r[0]),l={answer:i,process:rK(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i})};return e.set(t,l),l}(nx,el[d]),f=h.answer,m=[],g=0,x=0,v=!1;for(let e=i+1;e<=d;e++){let n=el[e];if("custom"===n.role){if(rw(n))continue;v||=!!(t5&&t5.entryId===ea[e]),g+=1,m.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!f,l=rS(i);if(0===l.length){let t=s?sJ(n):[];t.length>0&&m.push((0,r.jsx)(s0,{notices:t},`process-notices-${ed[e]}`));continue}t??=a.get(e),x+=l.filter(e=>"toolCall"===e.type).length,g+=1,v||=!!(t5&&ea[e]===t5.entryId&&(!t7||l.includes(t7))),m.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===g)u.push(...m);else if(m.length>0){let e=(f?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),n=function(e){let t;for(let n of e)for(let e of sJ(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(el.slice(i+1,f?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nb.current[t]=e},children:(0,r.jsx)(du,{messageCount:g,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:v,t:K,children:m},e?"answered":"unanswered")},`process-group-${ed[s]}`))}if(f){let e=[];for(let t=i+1;t<=d;t++){let n=el[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(h,function(e,t,n){let r=new Set,i=[];for(let l of e){var s;if("toolCall"!==l.type||!(rP(s=l.toolName)||rW(s))&&!rO(l.toolName))continue;let e=t?.get(l.toolCallId);if(e&&!e.isError)for(let t of rO(l.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of rF(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!rD(e)||!rD(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(rB(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=rq(rU(n.preview));if(e.length>0)return e}return rq(r_(rF(e)))}(l.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(l.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),l=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(s),a=s.startsWith("//");if(o||a)n=s;else if(s.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!l)return null;n=`${l}/${s}`}return rR(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,ng,nj));u.push(c(d,{messageOverride:f,writtenFiles:t,turnDurationMs:0===m.length?p:void 0,recoverTruncation:o===el.length&&!tE&&!r$(f)}))}for(let e=d+1;e<o;e++)u.push(c(e));e=o}let{startIndex:p}=(t=Math.min(Math.max(tG,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||eu;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t0,className:"py-3 text-center text-xs text-text-muted",children:K("chat.loadEarlier")}),u.slice(p)]})})(),tE&&tI&&(0,r.jsx)(dh,{store:eh,onCommit:nE,toolResults:ng,modelNames:ex,cwd:nj,onOpenFile:L,onOpenSubagent:P}),(ef||eI)&&!tI&&(e4||eI)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n)return r>0?t("chat.compactingQueued",{count:r}):t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(e4,K,eI,(eD?.steering.length??0)+(eD?.followUp.length??0))})}),em&&!eg&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:K("chat.runningCommand")})}),eg&&(0,r.jsx)(s5,{message:{role:"bashExecution",command:eg.command,output:"",excludeFromContext:eg.excludeFromContext},sessionId:o?.id??e6.current??void 0,onOpenSubagent:P}),(0,r.jsx)("div",{ref:nk,"aria-hidden":"true"})]})})}),V||ee?null:(0,r.jsx)(ah,{messages:el,getStreamingMessage:tM,scrollContainer:e9,messageRefs:nb,onRevealHistory:ny,turnsBefore:ep})]})]}),O&&tR&&(0,tc.createPortal)((0,r.jsx)("div",{ref:tU,role:tL?"dialog":"toolbar","aria-label":K(tL?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tR.top,left:tR.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tL?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tL?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tL?(0,r.jsxs)("fieldset",{disabled:tP,"aria-busy":tP,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:K("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:K("i18n.close"),"aria-label":K("i18n.close"),disabled:tP,onClick:tK,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(an,{ref:tq,compact:!0,onSend:tJ,onAbort:tK,isStreaming:!1}),tH&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tH})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:K("chat.askInCurrent"),"aria-label":K("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tZ,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{fontSize:15},children:"@"}),(0,r.jsx)("span",{children:K("chat.askInCurrent")})]}),W&&tR.sourceEntryId&&!em&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:K("chat.askInNewChat"),"aria-label":K("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tz(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:K("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nw&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!V,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${e5&&!ee?" is-visible":""}`,title:K("chat.scrollToLatest"),"aria-label":K("chat.scrollToLatest"),onClick:()=>tN("smooth"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nw&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:V?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-brand",children:[(0,r.jsx)(rc.default,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","0.12.7"]}),(0,r.jsx)(dc,{label:e=>K("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.4.0"]})]})]})]}),m]})}),nT,(0,r.jsx)(av,{statuses:eK,widgets:eV,onCommand:tn,commandsDisabled:tT})]}),nw&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}let dh=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d}=e,c=dr(t,dl);return((0,i.useLayoutEffect)(n,[c,n]),c)?(0,r.jsx)(s5,{message:c,toolResults:s,isStreaming:!0,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d}):null});function df(e){let{notices:t,floating:n=!1,onPauseChange:i}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,s)=>{var l;let o,a,d,c="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>i?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||i?.(null)},onFocus:()=>i?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||i?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(s!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(l=e.message,o=[],a=(e,t)=>{if(!t)return;let n=o[o.length-1];n?.kind===e?n.text+=t:o.push({kind:e,text:t})},d=!1,l.split("\n").forEach((e,t)=>{let n=rv.test(e);t>0&&a(n&&d?"art":"text","\n"),a(n?"art":"text",e),d=n}),o).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function dm(e){let{count:t}=e,{t:n}=(0,e0.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function dg(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function dx(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:l}=(0,e0.s)(),[o,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),w=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(t),j=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;t.classList.add("extension-dialog-measuring");let i=Array.from(r,e=>e.scrollWidth-e.clientWidth);t.classList.remove("extension-dialog-measuring");let s=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,i);null!==s&&f(e=>null!==e&&e>=s?e:s)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let k=null!==j&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:l("chat.extensionExpiresIn",{seconds:j})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:o})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:l("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:t.title}),w&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:w}),(0,r.jsx)(dm,{count:n}),k,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:l("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":t.title,style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:l("chat.extensionRequest")}),(0,r.jsx)(dm,{count:n}),k]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:l(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":l(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(dg,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:l("chat.extensionCollapse"),"aria-label":l("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(sk,{children:t.message}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":e,ref:0===n?y:void 0,onClick:()=>s(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),s(t,{value:e}))},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(sk,{children:e})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:l("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:l("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:l("chat.submit")}):null]})]})})}function dv(e){let{request:t,waitingCount:n,onInput:s}=e,{t:l}=(0,e0.s)(),o=(0,i.useRef)(null),a=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(rh,""),i=rf(e).trimEnd();if(t.test(i))continue;let s=e,l=rx(s);("│"===l||"┃"===l)&&" "===rx(s=rg(s,0))&&(s=rg(s,0));let o=function(e){let t=rm(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=o>=0?rm(s)[o]?.char:void 0;("│"===a||"┃"===a)&&(s=rg(s,o)),n.push(function(e){let t=e;for(;;){let e=rm(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===rf(n[0]).trim();)n.shift();for(;n.length>0&&""===rf(n[n.length-1]).trim();)n.pop();return n.length?n:e}(t.lines),p=u.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||o.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:l("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:l("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(dm,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:l("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||o.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:o,"aria-label":l("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=ry[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":rb[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:l("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(dm,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:l("chat.extensionCollapse"),"aria-label":l("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:l("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(am,{text:u.join("\n")})})]})})}let db=null,dy="";function dw(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:l,onPick:o,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,e0.s)(),[h,f]=(0,i.useState)(()=>dy),m=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(l);return x.current=l,(0,i.useEffect)(()=>{if(dy)return;let e=!1;return(db??=fetch("/api/home").then(e=>e.json()).then(e=>dy=e.home??"").catch(()=>(db=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;eI(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(n8,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:o,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}function dj(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function dk(e,t){return null===e||null===t||e!==t}var dS=n(73620);let dC=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function dN(e){let t=function(e){let t=dC.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,dS.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}function d$(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let dE=[",",";"," ","|"];function dI(e){let t=/\.(csv|tsv)$/i.exec(e);return t?"tsv"===t[1].toLowerCase()?" ":",":null}function dM(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.complete??!0,i=n.maxRecords??1/0,s=[],l=[],o=e.length,a=t.charCodeAt(0),d=+(65279===e.charCodeAt(0)),c=1,u=[],p=1,h=()=>{(1!==u.length||""!==u[0])&&(s.push(u),l.push(p)),u=[]};for(;d<o&&s.length<i;){let t="",n=!1;if(34===e.charCodeAt(d)){n=!0;let r=d+=1;for(;d<o;){let i=e.indexOf('"',d);if(-1===i)break;if(34===e.charCodeAt(i+1)){t+=e.slice(r,i+1),r=d=i+2;continue}t+=e.slice(r,i),d=i+1,n=!1;break}n&&(t+=e.slice(r),d=o),c+=function(e){let t=0,n=e.indexOf("\n");for(;-1!==n;)t+=1,n=e.indexOf("\n",n+1);return t}(t)}let i=d;for(;i<o;){let t=e.charCodeAt(i);if(t===a||10===t)break;i+=1}let s=i<o?e.charCodeAt(i):-1,l=s!==a&&i>d&&13===e.charCodeAt(i-1)?i-1:i;t+=e.slice(d,l),u.push(t),d=i,s===a?(d+=1)===o&&(u.push(""),r&&h()):10===s?(d+=1,c+=1,h(),p=c):r&&h()}return{records:s,lines:l}}function dT(e){let t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t),r=0;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);t>=56320&&t<=57343||(r+=t>=11904?2:1)}return r}let dR={display:"flex",height:26,boxSizing:"border-box",borderBottom:"1px solid var(--border)"},dA={position:"sticky",left:0,zIndex:1,boxSizing:"border-box",width:56,flexShrink:0,padding:"0 10px",display:"flex",alignItems:"center",justifyContent:"flex-end",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontSize:11,fontVariantNumeric:"tabular-nums",userSelect:"none"},dL={boxSizing:"border-box",flexShrink:0,padding:"0 10px",lineHeight:"25px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderRight:"1px solid var(--border)"};function dz(e){let{content:t,filePath:n,complete:s,scrollRef:l}=e,o=(0,i.useMemo)(()=>(function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=dI(t)??",",i=","===r?function(e){let t=e.slice(0,65536),n=t.length===e.length,r=",",i=0;for(let e of dE){let{records:s}=dM(t,e,{complete:n,maxRecords:20}),l=s[0]?.length??0;if(l<2)continue;let o=1e3*s.filter(e=>e.length===l).length+Math.min(l,999);o>i&&(r=e,i=o)}return r}(e):r,{records:s,lines:l}=dM(e,i,{complete:n});if(0===s.length)return{columns:[],headerLine:0,rows:[],rowLines:[]};let o=0;for(let e of s)e.length>o&&(o=e.length);let a=s[0];return{columns:a.length===o?a:[...a,...Array.from({length:o-a.length},()=>"")],headerLine:l[0],rows:s.slice(1),rowLines:l.slice(1)}})(t,n,s),[s,t,n]),a=(0,i.useMemo)(()=>{var e,t;let n;return e=o.columns,n=Math.max(1,Math.ceil((t=o.rows).length/500)),e.map((e,r)=>{let i=dT(e);for(let e=0;e<t.length;e+=n){let n=t[e][r];if(n){let e=dT(n);e>i&&(i=e)}}return Math.min(Math.max(Math.ceil(7.4*i+22),64),420)})},[o]),d=(0,i.useMemo)(()=>a.reduce((e,t)=>e+t,56),[a]),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(0);if((0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=null,n=()=>{u(e.scrollTop),h(e.clientHeight)},r=()=>{null===t&&(t=requestAnimationFrame(()=>{t=null,n()}))};n(),e.addEventListener("scroll",r,{passive:!0});let i="u"<typeof ResizeObserver?null:new ResizeObserver(n);return i?.observe(e),()=>{e.removeEventListener("scroll",r),i?.disconnect(),null!==t&&cancelAnimationFrame(t)}},[l]),0===o.columns.length)return null;let{start:f,end:m}=function(e,t,n){if(e<=0)return{start:0,end:0};let r=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(n)&&n>0?n:800,s=Math.max(0,Math.floor(r/26)-20),l=Math.min(e,Math.ceil((r+i)/26)+20);return{start:Math.min(s,l),end:l}}(o.rows.length,c-26,p),g=[];for(let e=f;e<m;e+=1){let t=o.rows[e];g.push((0,r.jsxs)("div",{role:"row","aria-rowindex":e+2,style:{...dR,position:"absolute",top:26*e,left:0,width:d},children:[(0,r.jsx)("div",{role:"rowheader",style:dA,children:o.rowLines[e]}),a.map((e,n)=>{let i=t[n]??"";return(0,r.jsx)("div",{role:"cell",style:{...dL,width:e},title:i||void 0,children:i},n)})]},e))}return(0,r.jsxs)("div",{role:"table","aria-rowcount":o.rows.length+1,"aria-colcount":o.columns.length,style:{width:d,minWidth:"100%",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:12,color:"var(--text-muted)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{role:"row","aria-rowindex":1,style:{...dR,position:"sticky",top:0,zIndex:2,width:d,background:"var(--bg-panel)",color:"var(--text)",fontWeight:600},children:[(0,r.jsx)("div",{role:"rowheader",style:dA,children:o.headerLine}),o.columns.map((e,t)=>(0,r.jsx)("div",{role:"columnheader",style:{...dL,width:a[t]},title:e||void 0,children:e},t))]}),(0,r.jsx)("div",{style:{position:"relative",height:26*o.rows.length},children:g})]})}let dP=["tags","categories","keywords","tag","category"];function dW(e){var t;let{data:n}=e;if(!n)return null;let i=Object.entries(n);if(0===i.length)return null;let s="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,l=dP.find(e=>Array.isArray(n[e])),o=l?n[l].map(d$).filter(Boolean):[],a=i.filter(e=>{let[t]=e;return t!==l&&("title"!==t||!s)});return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),o.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:o.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),a.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:a.map(e=>{let[t,n]=e;return(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:t}),(0,r.jsx)("dd",{children:function(e){let t=d$(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(n)})]},t)})})]})}let dO={source:"Source",preview:"Preview",diff:"Diff"},dF={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},dD={...iH.xJ,'pre[class*="language-"]':{...iH.xJ['pre[class*="language-"]']}};delete dD['pre[class*="language-"]'].background;let dB={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"},dH={...dB,position:"sticky",left:0,zIndex:1};function d_(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function dU(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function dq(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=dU(n.startContainer),i=dU(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(l))return null;if(s<l){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(l=Number((i=e).dataset.lineNumber))}}}return s>l?null:{startLine:s,endLine:l}}function dK(e){let{rows:t,stylesheet:n,useInlineStyles:i,wrapLines:s}=e;return t.map((e,t)=>{let l=e.children??[],o=l[0]?.properties?.className,a=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,iD.Ay)({node:d,stylesheet:n,useInlineStyles:i,key:`source-line-number-${t}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:s?"anywhere":"normal",whiteSpace:s?"pre-wrap":"pre"},children:c.map((e,r)=>(0,iD.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function dV(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=tI(e),s=new URLSearchParams({type:t});for(let[e,i]of(n&&s.set("sessionId",n),"watch"===t&&s.set("holder",eT()),Object.entries(r)))void 0!==i&&s.set(e,String(i));return`/api/files/${i}?${s.toString()}`}function dZ(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,e0.s)();return(0,r.jsx)("a",{href:dV(t,"download",n),download:tM(t),title:i("i18n.downloadFile"),"aria-label":i("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function dJ(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function dY(e){let t,{patch:n}=e,{t:i}=(0,e0.s)(),s=(t=s$(n))?t.flatMap(sE):[],l=e=>"added"===e.type||"removed"===e.type;if(!s.some(l))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:i("i18n.noChanges")});let o=new Set(s.flatMap((e,t)=>l(e)?[t]:[])),a=new Set;for(let e of o)for(let t=Math.max(0,e-3);t<=Math.min(s.length-1,e+3);t++)a.add(t);let d=a.size<=1e3?dH:dB,c=e=>"gap"!==s[e].type&&a.has(e),u=[],p=0;for(;p<s.length;)if(c(p)){let e=[];for(;p<s.length&&c(p);){let t=s[p];"gap"!==t.type&&e.push(t),p++}u.push({hidden:!1,lines:e})}else{let e=0;for(;p<s.length&&!c(p);){let t=s[p],n="gap"===t.type?t.count:1;e=null===e||null===n?null:e+n,p++}u.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...dF},children:u.map((e,t)=>{if(e.hidden)return(0,r.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:null===e.count?"⋯":`⋯ ${sI(e.count,i)}`},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:d,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function dG(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=tM(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!l)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=dj(t);dk(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=dj(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,l]);let j=dV(t,"read",s,c?{v:c}:void 0),k=null!=p?dJ(p):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"image"}),f&&(0,r.jsxs)("span",{children:[f.w," \xd7 ",f.h]}),k&&(0,r.jsx)("span",{children:k}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:j,alt:t,onLoad:e=>{let t=e.currentTarget;m({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x(o("files.imageLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function dX(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function dQ(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=tM(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!l)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=dj(t);dk(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=dj(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,l]);let j=dV(t,"read",s,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"audio"}),null!=f&&(0,r.jsx)("span",{children:dX(f)}),null!=p&&(0,r.jsx)("span",{children:dJ(p)}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:j,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x(o("files.audioLoadFailed")),style:{width:"100%"}},j)]})})]})}function d0(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=tM(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!l)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=dj(t);dk(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=dj(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,l]);let j=dV(t,"read",s,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"video"}),null!=f&&(0,r.jsx)("span",{children:dX(f)}),null!=p&&(0,r.jsx)("span",{children:dJ(p)}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:j,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x(o("files.videoLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%"}},j)]})})]})}function d1(e){let{filePath:t,cwd:n,sourceSessionId:s,initialPage:l,watchEnabled:o=!0}=e,{t:a}=(0,e0.s)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(0),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),b=(0,i.useRef)(null),y=r1(t),w="pdf"===y,j=w&&l&&l>0?`#page=${l}`:"",k=w?`${dV(t,"read",s,u?{v:u}:void 0)}${j}`:dV(t,"preview",s,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),f(null),g(null),c(!1),b.current=null;let e=!0,n=++v.current;return fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{e&&n===v.current&&(t.error&&g(t.error),"number"==typeof t.size&&(f(t.size),!w&&t.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===v.current&&g(String(t))}),()=>{e=!1}},[t,w,s]),(0,i.useEffect)(()=>{if(c(!1),x.current&&(x.current.close(),x.current=null),!o)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);x.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++v.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==v.current)return;if(t.error)return void g(t.error);if("number"==typeof t.size&&(f(t.size),!w&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null);let r=dj(t);dk(b.current,r)&&(b.current=r,p(e=>e+1))}).catch(t=>{e&&n===v.current&&g(String(t))})}),n.addEventListener("change",e=>{v.current+=1,b.current=null;try{let t=JSON.parse(e.data);if(b.current=dj(t),"number"==typeof t.size&&(f(t.size),!w&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),p(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),x.current===n&&(x.current=null)}},[t,w,s,o]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===y?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:dJ(h)}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s}),(0,r.jsxs)("span",{title:a(d?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:d?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:d?"#4ade80":"var(--border)",display:"inline-block",boxShadow:d?"0 0 4px #4ade80":"none"}}),d?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:m?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:m}):(0,r.jsx)("iframe",{src:k,sandbox:w?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:tM(t)}),style:{width:"100%",height:"100%",border:"none",background:w?"var(--bg)":"#eef1f5"}},k)})]})}function d2(e){let t,{filePath:n,cwd:s,sourceSessionId:l,onOpenFile:o,onMentionLines:a,onAtMention:d,gitRefreshKey:c,initialDisplayMode:u,initialState:p,initialPage:h,onStateChange:f,watchEnabled:m=!0}=e,g=function(){let e=(0,i.useSyncExternalStore)(aV,aZ,aJ),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{if(!e)return void n(!1);let t=setTimeout(()=>n(!0),3e4);return()=>clearTimeout(t)},[3e4,e]),e&&t}(),x=m&&!g;return null!==(rX[r1(n)]??null)?(0,r.jsx)(dG,{filePath:n,cwd:s,sourceSessionId:l,watchEnabled:x}):r2(n)?(0,r.jsx)(dQ,{filePath:n,cwd:s,sourceSessionId:l,watchEnabled:x}):r4(n)?(0,r.jsx)(d0,{filePath:n,cwd:s,sourceSessionId:l,watchEnabled:x}):null!==("pdf"===(t=r1(n))||"docx"===t?t:null)?(0,r.jsx)(d1,{filePath:n,cwd:s,sourceSessionId:l,initialPage:h,watchEnabled:x}):(0,r.jsx)(d4,{filePath:n,cwd:s,sourceSessionId:l,onOpenFile:o,onMentionLines:a,onAtMention:d,gitRefreshKey:c,initialDisplayMode:u,initialState:p,onStateChange:f,watchEnabled:x})}function d4(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:l,onMentionLines:o,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=i5(),{t:m}=(0,e0.s)(),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(!1),[j,k]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!0),[N,$]=(0,i.useState)(!1),[E,I]=(0,i.useState)(null),M=u?.displayMode??c??"source",T=u?.wrapLines??!1,R=u?.scrollTop??0,A=u?.scrollLeft??0,[L,z]=(0,i.useState)(M),[P,W]=(0,i.useState)(T),[O,F]=(0,i.useState)(!1),D=(0,i.useRef)(null),B=(0,i.useRef)(0),H=(0,i.useRef)(null),_=(0,i.useRef)(0),U=(0,i.useRef)(null),q=(0,i.useRef)(!1),K=(0,i.useRef)(void 0===u&&void 0===c),V=(0,i.useRef)(!0),Z=(0,i.useRef)({displayMode:M,wrapLines:T,scrollTop:R,scrollLeft:A}),J=(0,i.useRef)(p),[Y,G]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null);J.current=p;let ee=(0,i.useCallback)(e=>{Z.current.displayMode=e,z(e)},[]),et=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Z.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Z.current={displayMode:M,wrapLines:T,scrollTop:R,scrollLeft:A},V.current=!0,q.current=!1,z(M),W(T),()=>{J.current?.({...Z.current})}),[t,s,M,T,R,A]);let en=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++B.current;return fetch(dV(e,"read",s,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==B.current?null:e.error?(I(e.error),null):(H.current=dj(e),I(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==B.current||I(String(e)),null))},[s]),er=(0,i.useCallback)(async e=>{let t=++_.current;if(w(!0),!n){b(null),w(!1),k(!0);return}try{let r=new URLSearchParams({cwd:n,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(t!==_.current)return;b(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{t===_.current&&b(null)}finally{t===_.current&&(w(!1),k(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),I(null),x(null),b(null),k(!1),F(!1),H.current=null,en(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,en,s]),(0,i.useEffect)(()=>{if(F(!1),D.current&&(D.current.close(),D.current=null),!h)return;let e=!0,n=()=>{en(t),er(t)},r=ez("file-watch",new EventSource(dV(t,"watch",s)),t);D.current=r,r.addEventListener("connected",()=>{(F(!0),null===H.current)?n():fetch(dV(t,"meta",s)).then(e=>e.json()).then(r=>{e&&(dk(H.current,dj(r))?n():er(t))}).catch(()=>{e&&n()})}),r.addEventListener("change",n);let i=()=>{F(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{e=!1,r.close(),D.current===r&&(D.current=null)}},[t,en,er,s,h]),(0,i.useEffect)(()=>{er(t)},[er,t,d]);let ei=g?.binary===!0,es=!ei&&null!==dI(t);(0,i.useEffect)(()=>{K.current&&g&&!g.binary&&(es||"markdown"===g.language&&!g.truncated||"html"===g.language&&(!g.truncated||g.size<=0xa00000))&&(K.current=!1,ee("preview"))},[g,es,ee]);let el="preview"===L&&g?.language==="html"&&g.truncated&&g.size<=0xa00000;(0,i.useEffect)(()=>{if(!el)return void Q(null);let e=new AbortController;return fetch(dV(t,"download",s),{signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);Q({text:await e.text()})}).catch(t=>{e.signal.aborted||Q({error:String(t)})}),()=>e.abort()},[el,g,t,s]);let eo=v?.supported===!0&&"string"==typeof v.patch,ea=eo&&"deleted"===v.status;(0,i.useEffect)(()=>{j&&!eo&&"diff"===L&&ee("source")},[L,j,eo,ee]),(0,i.useEffect)(()=>{"diff"===M&&eo&&!q.current&&(q.current=!0,ee("diff"))},[M,eo,ee]);let ed=(0,i.useMemo)(()=>g?.language==="markdown"?ih(g.content):"",[g]),ec=(0,i.useMemo)(()=>g?.language==="markdown"?dN(g.content):null,[g]),eu=g?.content??"",ep=(0,i.useMemo)(()=>eu.split("\n"),[eu]),eh=g?.language??"text",ef=se(!!g&&"text"!==eh),em=!ei&&"html"===eh,eg=!ei&&"markdown"===eh,ex=es||(em?!!g&&(!g.truncated||g.size<=0xa00000):eg&&!g?.truncated),ev=ea?"diff":L,eb=!!g?.truncated&&!(em&&"preview"===ev),ey=ep.length>1e3&&!("diff"===ev&&eo)&&!("preview"===ev&&ex),ew=(0,i.useMemo)(()=>(0,r.jsx)(iB.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"!==eh&&ef?eh:"plaintext",style:f?dD:iH.vs,showLineNumbers:!0,lineNumberStyle:{...dH},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...dF,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(dK,{...e,wrapLines:P}),wrapLongLines:P,children:eu}),[f,eh,ef,eu,P]),ej=(0,i.useMemo)(()=>ey?ep.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:dB,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:P?"anywhere":"normal",whiteSpace:P?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[ep,ey,P]);(0,i.useEffect)(()=>{let e=()=>{let e=U.current;G(t=>{let n=o&&"source"===L&&e?dq(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),o&&"source"===L)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,L,o]);let ek=(0,i.useCallback)(e=>{o&&e&&o(tR(t,n),e.startLine,e.endLine)},[n,t,o]);if((0,i.useEffect)(()=>{if(!o||"source"!==L)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=U.current,r=n?dq(n,window.getSelection()):null;r&&(e.preventDefault(),ek(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[L,ek,o]),(0,i.useEffect)(()=>{if(!V.current||S||E&&!ea||"diff"===M&&!j||"diff"===M&&eo&&"diff"!==L)return;let e=U.current;e&&(e.scrollTop=Z.current.scrollTop,e.scrollLeft=Z.current.scrollLeft,V.current=!1)},[g?.content,L,E,j,eo,ea,S,M]),S||"diff"===M&&y&&!g)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:m("i18n.loading")});if(E&&!ea)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:E});if(!g&&!ea)return null;let eS=tT(t),eC=ea?["diff"]:["source",...ex?["preview"]:[],...eo?["diff"]:[]],eN=ea?m("files.deleted"):ei?`${m("files.binary")} \xb7 ${dJ(g.size)}`:`${eh} \xb7 ${ep.length} lines \xb7 ${dJ(g.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eN,children:eN}),!ea&&(0,r.jsx)("span",{title:O?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":O?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[eC.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:eC.map(e=>{let t=ev===e;return(0,r.jsx)("button",{type:"button",onClick:()=>ee(e),title:"diff"===e?m("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:dO[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||o)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{Y&&o?ek(Y):a?.(tR(t,n),!1)},title:Y&&o?`${m("i18n.mentionSelectedLines")} (L${Y.startLine}${Y.startLine!==Y.endLine?`-L${Y.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!a&&!o,className:"file-viewer-icon-button",children:(0,r.jsx)(d_,{})}),"source"===ev&&!ei&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:et,title:P?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-label":P?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-pressed":P,className:"file-viewer-icon-button",style:{background:P?"var(--bg-selected)":"transparent",color:P?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!ea&&(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]})]}),eb&&g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,r.jsxs)("span",{children:[dJ(g.nextOffset)," / ",dJ(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{$(!0),en(t,g.nextOffset).finally(()=>$(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:U,className:"file-viewer-content",onScroll:e=>{Z.current.scrollTop=e.currentTarget.scrollTop,Z.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:eb?48:void 0},children:"diff"===ev&&eo?(0,r.jsx)(dY,{patch:v.patch}):em&&"preview"===ev&&g?.truncated&&!X?.text?(0,r.jsx)("div",{style:{padding:24,color:"var(--text-dim)",fontSize:12},children:X?.error??m("i18n.loading")}):em&&"preview"===ev?(0,r.jsx)("iframe",{srcDoc:g?.truncated?X?.text:eu,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):eg&&"preview"===ev?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ec?.data&&(0,r.jsx)(dW,{data:ec.data}),(0,r.jsx)(rY.oz,{remarkPlugins:iE,rehypePlugins:iL,urlTransform:l?ia:io,components:{code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?"mermaid"===s?(0,r.jsx)(sa,{code:l.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(sm,{code:l.replace(/\n$/,""),lang:s}):(0,r.jsx)("code",{className:t,...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:i,...s}=e;delete s.node;let o=l?rA(t,eS,n??eS):null;return o&&l?(0,r.jsx)("a",{href:t,...s,onClick:e=>{rI(e)&&(e.preventDefault(),l(o,rz(t)??void 0))},children:i}):id(t)?(0,r.jsx)("a",{href:t,...s,target:"_blank",rel:"noopener noreferrer",children:i}):(0,r.jsx)("a",{href:t,...s,onClick:ic,children:i})},img(e){let{src:t,alt:i,...l}=e;delete l.node;let o="string"==typeof t?rA(t,eS,n??eS):null,a=o?dV(o,"read",s):t;return(0,r.jsx)("img",{src:a,alt:i??"",loading:"lazy",...l})}},children:ed})]}):es&&"preview"===ev?(0,r.jsx)(dz,{content:eu,filePath:t,complete:!g?.truncated,scrollRef:U}):ei?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,padding:24,color:"var(--text-muted)",fontSize:13,textAlign:"center"},children:[(0,r.jsx)("span",{children:m("files.binaryNoPreview")}),(0,r.jsx)("a",{href:dV(t,"download",s),download:tM(t),className:"file-viewer-mode-button",style:{display:"inline-flex",alignItems:"center",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",textDecoration:"none"},children:m("files.download")})]}):ey?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...dF},children:ej}):ew})]})}function d8(e){let{tabs:t,activeTabId:n,onSelectTab:s,onCloseTab:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=c.current;if(!e)return;let t=t=>{t.ctrlKey||Math.abs(t.deltaY)<=Math.abs(t.deltaX)||e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[]),(0,i.useEffect)(()=>{let e=c.current,t=e?.querySelector('[role="tab"][aria-selected="true"]');if(!e||!t)return;let n=e.getBoundingClientRect(),{left:r,right:i}=t.getBoundingClientRect();r<n.left?e.scrollLeft-=n.left-r:i>n.right&&(e.scrollLeft+=i-n.right)},[n,t.length]),(0,r.jsx)("div",{ref:c,role:"tablist",className:"tabbar-scroll",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",overflowX:"auto",overflowY:"hidden",flexShrink:0,height:36},children:t.map(e=>{let i=e.id===n;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===e.kind?o("terminal.tabLabel",{name:e.label}):"agent"===e.kind?o("subagent.tabLabel",{name:e.label}):e.label,"aria-selected":i,tabIndex:i||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),s(e.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(n.key)){n.preventDefault();let r=t.findIndex(t=>t.id===e.id),i="Home"===n.key?0:"End"===n.key?t.length-1:(r+("ArrowRight"===n.key?1:-1)+t.length)%t.length;s(t[i].id),n.currentTarget.parentElement?.children[i]?.focus()}}},onClick:()=>s(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||l(e.id))},style:{display:"flex",alignItems:"center",gap:6,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"terminal"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"agent"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):t$(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath,children:e.label}),(0,r.jsx)("button",{disabled:e.closing,onClick:t=>{t.stopPropagation(),l(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:a===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:a===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:o("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${o("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function d3(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s}let d5=["general","models","archives","skills","agents","plugins","mcp"],d6="pi-web:settings-navigation",d9=new Set(["skills","agents","plugins"]);function d7(e){return d9.has(e)}function ce(){try{return window.localStorage}catch{return null}}function ct(e){let t=e.getItem(d6);if(!t)return{};try{let e=JSON.parse(t);if(null===e||"object"!=typeof e||Array.isArray(e))return{};return{section:"string"==typeof e.section?e.section:void 0,selections:null===e.selections||"object"!=typeof e.selections||Array.isArray(e.selections)?void 0:e.selections}}catch{return{}}}function cn(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function cr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ce();if(t)try{let n=ct(t);n.section=e,t.setItem(d6,JSON.stringify(n))}catch{}}function ci(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ce();if(!n)return null;let r=cn(e,t);if(!r)return null;try{let e=ct(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function cs(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:ce();if(!r||!t)return;let i=cn(e,n);if(i)try{let e=ct(r);e.selections={...e.selections,[i]:t},r.setItem(d6,JSON.stringify(e))}catch{}}function cl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class co extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function ca(e){if("string"==typeof e){let t=/^\d+$/.test(e.trim())?Number(e.trim()):0;return Number.isSafeInteger(t)&&t>0?t:void 0}return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}let cd={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class cc extends Error{constructor(e,t){super(cd[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function cu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return!cu(e)||"string"!=typeof e.id||e.id.trim().length>0}function ch(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cf(e){let t=ch(e.inputLimits)?e.inputLimits.images:void 0,n=ch(t)?t.resize:void 0;return ch(n)?n.maxBytes:void 0}function cm(e){let t="string"==typeof e?/^\d+$/.test(e.trim())?Number(e.trim()):0:e;return"number"==typeof t&&Number.isSafeInteger(t)&&t>=1?t:void 0}function cg(e){let t=["B","KiB","MiB","GiB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=0===r?String(n):String(Math.round(10*n)/10);return`${i} ${t[r]}`}class cx extends Error{constructor(e){super(`Image size limit of ${e} must be a positive whole number of bytes`),this.name="ImageMaxBytesError",this.model=e}}let cv=["input","output","cacheRead","cacheWrite"];function cb(e){return{input:e?.input===void 0?"":String(e.input),output:e?.output===void 0?"":String(e.output),cacheRead:e?.cacheRead===void 0?"":String(e.cacheRead),cacheWrite:e?.cacheWrite===void 0?"":String(e.cacheWrite)}}function cy(e){if(!cw(e))return;let t=e=>{if(!e.trim())return 0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0},n=t(e.input),r=t(e.output),i=t(e.cacheRead),s=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==s)return{input:n,output:r,cacheRead:i,cacheWrite:s}}function cw(e){return cv.some(t=>""!==e[t].trim())}function cj(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function ck(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function cS(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function cC(e,t){let{renames:n,savedProviders:r}=e;for(let[e,r]of n)if(r===t)return e;return!n.has(t)&&r.has(t)?t:null}function cN(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function c$(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:l,children:o,width:a=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${a}px`,"--config-panel-height":d};return(0,r.jsx)("div",{role:t?void 0:"dialog","aria-modal":t?void 0:"true","aria-label":n,className:`config-panel-root ${t?"is-embedded":"is-modal"}`,onClick:e=>{t||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:c,children:[!t&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:n}),i&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:i,children:i}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:l,title:s,"aria-label":s,children:"\xd7"})]}),o]})})}function cE(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function cI(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function cM(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function cT(e){let{children:t,aside:n}=e;return(0,r.jsxs)("div",{className:"config-sidebar-group-label",children:[(0,r.jsx)("span",{className:"config-sidebar-group-label-text",children:t}),n]})}function cR(e){let{enabled:t,total:n,checked:i,label:s,disabled:l=!1,loading:o=!1,describedBy:a,onChange:d}=e;return(0,r.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,r.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,r.jsx)(c4,{checked:i??(n>0&&t===n),disabled:l,loading:o,label:s,describedBy:a,onChange:d})]})}function cA(e){let{error:t,note:n}=e;return t||n?(0,r.jsxs)("div",{className:"config-sidebar-group-status",children:[n&&(0,r.jsx)("div",{role:"status",className:"config-sidebar-group-note",children:n}),t&&(0,r.jsx)("div",{role:"alert",className:"config-sidebar-group-error",children:t})]}):null}function cL(e){let{active:t=!1,className:n,children:i,...s}=e;return(0,r.jsx)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function cz(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function cP(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function cW(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function cO(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function cF(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function cD(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function cB(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function cH(e){let{label:t,children:n,style:i,ref:s}=e;return(0,r.jsxs)("div",{ref:s,className:"config-field",style:i,children:[(0,r.jsx)("span",{className:"config-field-label",children:t}),n]})}function c_(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function cU(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:l,children:o}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,s].filter(Boolean).join(" "),style:l,children:o})]})}function cq(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function cK(e){let{value:t,options:n,label:s,disabledReason:l,size:o="default",onChange:a,children:d}=e,c=(0,i.useId)(),u=l&&n.some(e=>e.disabled)?l:null;return(0,r.jsxs)("div",{className:"config-scope-switch-field",children:[(0,r.jsxs)("div",{className:"config-scope-switch-row",children:[(0,r.jsx)("div",{role:"group","aria-label":s,className:`config-scope-switch${"small"===o?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?c:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||a(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function cV(e){let{value:t,options:n,label:s,path:l,disabledReason:o,onChange:a,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(cK,{value:t,options:n,label:s,disabledReason:o,size:"small",onChange:a,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof l?l.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):l})}),d]})}function cZ(e){let{title:t,catalogs:n,target:i}=e;return(0,r.jsxs)("div",{className:"config-add-source-heading",children:[(0,r.jsxs)("div",{className:"config-add-source-title-row",children:[(0,r.jsx)(cD,{children:t}),(0,r.jsx)("span",{className:"config-add-source-catalogs",children:n.map(e=>(0,r.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"config-add-source-catalog",children:[e.icon,e.label]},e.href))})]}),i]})}function cJ(e){let{title:t,catalogs:n,target:s,inputLabel:l,inputId:o,placeholder:a,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:f,examples:m,error:g,multiline:x=!1,children:v}=e,b=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():b.current?.focus()},[x]);let w=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(cP,{className:"is-fill",children:[(0,r.jsx)(cZ,{title:t,catalogs:n,target:s}),(0,r.jsx)(cH,{label:l,children:x?(0,r.jsx)("textarea",{id:o,ref:y,value:d,"aria-label":l,className:"config-add-source-input is-multiline",placeholder:a,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),c&&h())}}):(0,r.jsx)("input",{id:o,ref:b,value:d,"aria-label":l,className:"config-add-source-input",placeholder:a,onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&c&&h()}})}),v,m.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:f}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:m.map(e=>"string"==typeof e?(0,r.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,r.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,r.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,r.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),g&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:g})]})}function cY(e){let{id:t,action:n,children:i}=e;return(0,r.jsxs)("div",{id:t,role:"status",className:`config-notice${n?" has-action":""}`,children:[n?(0,r.jsx)("span",{className:"config-notice-text",children:i}):i,n]})}function cG(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:l}=e;return(0,r.jsx)(cY,{id:t,action:l&&i?(0,r.jsx)(c2,{size:"small",onClick:l,disabled:s,children:i}):void 0,children:n})}function cX(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function cQ(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function c0(e){let{status:t,children:n}=e;return(0,r.jsxs)("footer",{className:"config-footer",children:[(0,r.jsx)("div",{className:"config-footer-status",children:t}),(0,r.jsx)("div",{className:"config-footer-actions",children:n})]})}function c1(e){let{summary:t,tone:n="default",details:i}=e,s=`config-footer-status-summary${"default"===n?"":` is-${n}`}`;return i?.length?(0,r.jsxs)("details",{className:"config-footer-status-details",children:[(0,r.jsx)("summary",{className:s,children:t}),(0,r.jsx)("ul",{className:"config-footer-status-list",children:i.map((e,t)=>(0,r.jsx)("li",{children:e},t))})]}):(0,r.jsx)("span",{className:s,children:t})}function c2(e){let{variant:t="secondary",size:n="default",className:i,children:s,...l}=e;return(0,r.jsx)("button",{type:"button",...l,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function c4(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:l,describedBy:o,onChange:a}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":l,"aria-describedby":o,title:l,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>a(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function c8(e){let{active:t=!1,children:n,className:i,...s}=e;return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-list-action-button",i].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function c3(e){let{active:t,color:n}=e;return(0,r.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${t?" is-active":!1===t?" is-inactive":""}`,style:n?{backgroundColor:n}:void 0})}function c5(e,t){let n=t.filter(e=>!e.enabled).map(e=>e.ref),r=t.filter(e=>e.enabled).map(e=>e.ref),i=e?.editable===!0;return{enableRefs:n,disableRefs:r,canEnable:i&&n.length>0,canDisable:i&&r.length>0&&(e?.enabledTotal??0)-r.length>=1}}function c6(e,t){let n=c5(e,t.models),r=t.models.length>0&&t.enabledCount===t.models.length,i=r?!n.canDisable:!n.canEnable;return{checked:r,blocked:i,reason:i?e?.editable?"last-model":"project-scope":null}}function c9(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function c7(e,t){return e?.providers.find(e=>e.id===t)}function ue(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:l=!1,describedBy:o}=e,{t:a}=(0,e0.s)(),d=void 0!==i&&void 0===ca(i);return(0,r.jsx)("input",{type:"text",inputMode:"numeric",className:"model-context-input",value:void 0===i?"":String(i),placeholder:void 0===n?void 0:String(n),title:a("models.contextWindow"),"aria-label":a("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":o,disabled:l,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let ut={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function un(e){let{controller:t}=e,{t:n}=(0,e0.s)(),{view:i,pending:s}=t;if(!i)return null;let l=!i.allEnabled,o=i.stalePatterns.length;return l||0!==o?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...o>0?{title:n("models.enabledStaleHint")}:{},children:[(0,r.jsx)("code",{className:"enabled-models-banner-key",title:i.settingsPath,children:i.settingsPath}),(0,r.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${i.enabledTotal}/${i.availableTotal}`,o>0&&` \xb7 ${n("models.enabledStale",{count:o})}`]})]}),i.editable&&o>0&&(0,r.jsx)(c2,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&l&&(0,r.jsx)(c2,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function ur(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,e0.s)(),{view:l,loading:o,pending:a,failure:d}=n,c=c7(l,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=ui(n,t)?i:void 0;if(o&&!l)return null;if(!c)return(0,r.jsx)(c4,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=c6(l,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(c4,{checked:h.checked,loading:a===`provider:${c.id}`,disabled:null!==a||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function ui(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=c7(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=c6(n,i);return s?ut[s]:null}function us(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,e0.s)(),l=ui(n,t);return l?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(l)}):null}function ul(e){var t;let n,{providerId:s,controller:l,contextSettings:o}=e,{t:a}=(0,e0.s)(),[d,c]=(0,i.useState)(""),{view:u,loading:p,pending:h,failure:f}=l,m=c7(u,s),g=function(e,t){let[n,r]=(0,i.useState)(!1),[s,l]=(0,i.useState)(null);return(0,i.useEffect)(()=>l(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),l(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);"offline"===r.reason?l("models.catalogOffline"):r.completed?l(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):l("models.catalogUnreachable"),r.changed&&t()}catch{l("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,l.refresh),x=(0,i.useId)();if((0,i.useEffect)(()=>c(""),[s]),p&&!u)return(0,r.jsx)("div",{className:"enabled-models-empty",children:a("agents.modelsLoading")});if(!m)return f?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:f.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledUnavailable")});let v=(t=m.models,(n=d.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),b=c5(u,v),y=v.length!==m.models.length,w=null!==h,j=`provider:${m.id}`,k=u?.editable===!0,S=`${x}-scope`,C=`${x}-last`,N=`${x}-context`,$=k&&!b.canDisable&&b.disableRefs.length>0,E=$||k&&v.some(e=>c9(u,e)),I=(e,t)=>{y?l.setModels(j,t,e):l.setProvider(m.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:a("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:a("models.enabledCount",{enabled:m.enabledCount,total:m.models.length})}),(0,r.jsx)(c2,{size:"small",disabled:w||!b.canEnable,"aria-describedby":k?void 0:S,onClick:()=>I(!0,b.enableRefs),children:y?a("models.enableShown"):a("models.enableAll")}),(0,r.jsx)(c2,{size:"small",disabled:w||!b.canDisable,"aria-describedby":k?$?C:void 0:S,onClick:()=>I(!1,b.disableRefs),children:y?a("models.disableShown"):a("models.disableAll")}),(0,r.jsx)(c2,{size:"small",disabled:w||g.refreshing,title:a("models.refreshCatalogHint"),onClick:g.refresh,children:g.refreshing?a("models.refreshingCatalog"):a("models.refreshCatalog")})]}),g.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:a(g.note)}),!k&&(0,r.jsx)("div",{id:S,className:"enabled-models-note",children:a("models.enabledProjectScope")}),E&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:a("models.enabledLastModel")}),f&&(0,r.jsx)("div",{className:"enabled-models-error",children:f.messageKey?a(f.messageKey):f.message}),m.models.length>8&&(0,r.jsx)("input",{value:d,onChange:e=>c(e.target.value),placeholder:a("models.enabledFilterPlaceholder",{count:m.models.length}),"aria-label":a("models.enabledFilter"),className:"enabled-models-filter"}),o&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:a("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledNoMatches")}):v.map(e=>{let t=c9(u,e),n=o?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:a("models.enabledPinHint"),children:e.thinkingPin}),o&&(0,r.jsx)(ue,{modelName:e.name,effective:e.contextWindow,value:i,disabled:o.disabled,describedBy:N,onChange:t=>o.onChange(e.id,t)}),(0,r.jsx)(c4,{checked:e.enabled,loading:h===e.ref,disabled:w||!u?.editable||t,label:a("models.enabledToggle",{model:e.name}),describedBy:k?t?C:void 0:S,onChange:t=>l.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function uo(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:l,inputLabel:o,disabled:a=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!a&&i.trim().length>0;return(0,r.jsxs)("div",{className:"oauth-paste-panel",children:[(0,r.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,r.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,r.jsxs)("div",{className:"oauth-paste-row",children:[(0,r.jsx)("input",{ref:c,value:i,className:"oauth-paste-input",placeholder:s,"aria-label":o,disabled:a||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:l})]})]})}let ua={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function ud(e){let{id:t,size:n}=e,i=ua[t];if(i)return(0,r.jsx)("svg",{"aria-hidden":"true",width:n,height:n,viewBox:"0 0 24 24",fill:i.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${i.symbol}`})});let s=t.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:n,height:n,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*n)),fontWeight:700,lineHeight:1},children:s})}let uc=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],uu="pi-web:provider-usage:";function up(e){let{providerId:t,enabled:n}=e;return uc.includes(t)?(0,r.jsx)(uh,{providerId:t,enabled:n}):null}function uh(e){let{providerId:t,enabled:n}=e,[s,l]=(0,i.useState)(null),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:f,t:m}=(0,e0.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),l(null);try{let e=localStorage.getItem(`${uu}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&l(t)}}catch{try{localStorage.removeItem(`${uu}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{a(!0),c(null);try{let e=await fetch("/api/provider-usage/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:t})}),n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);if("ready"===n.status){l(n);try{localStorage.setItem(`${uu}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??m("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:m("providerUsage.queryFailed"))}finally{a(!1)}},[t,m]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:m("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:g,disabled:!n||o,title:m(o?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":m(o?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:u?"#4ade80":"var(--text-dim)",cursor:n&&!o?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:u?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:o?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(f),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:m("providerUsage.updated",{time:(0,t8.ob)(x.capturedAt,f)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:m("providerUsage.notQueried")}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:d}),x&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr)",columnGap:14,rowGap:8,alignItems:"baseline",minWidth:0,width:"min(100%, 420px)",maxWidth:"100%",fontSize:12},children:[x.buckets.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.groupLabel?`${e.groupLabel} / ${e.label}`:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:function(e,t){if("percent"===e.unit&&void 0!==e.remaining){let t=e.resetsAt?` / ${new Date(1e3*e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"";return`${Math.round(e.remaining)}%${t}`}return"currency"===e.unit?`${"CNY"===e.currency?"CNY ":"$"}${uf(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${uf(e.remaining)} / ${uf(e.limit)}`:e.period??t}(e,m("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function uf(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function um(){let e=ci("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}function ug(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let ux=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],uv={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function ub(e){let{label:t,children:n}=e;return(0,r.jsx)(cH,{label:t,children:n})}let uy={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function uw(e){let{value:t,onChange:n,placeholder:i,mono:s}=e;return(0,r.jsx)("input",{value:t,onChange:e=>n(e.target.value),placeholder:i,style:{...uy,fontFamily:s?"var(--font-mono)":"inherit"}})}function uj(e){let{value:t,onChange:n,placeholder:s,mono:l,onKeyDown:o,autoComplete:a="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,e0.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:o,placeholder:s,style:{...uy,paddingRight:34,fontFamily:l?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:d}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":h(u?"i18n.hideDetails":"i18n.showDetails"),title:h(u?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function uk(e){let{value:t,onChange:n,placeholder:i,invalid:s}=e;return(0,r.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:i,"aria-invalid":s||void 0,style:s?{...uy,borderColor:"#ef4444"}:uy})}function uS(e){let{value:t,onChange:n,options:i,required:s}=e,{t:l}=(0,e0.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...uy,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",l("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function uC(e){let{label:t,checked:n,onChange:i}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:n,onChange:e=>i(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),t]})}function uN(e){let{children:t}=e;return(0,r.jsx)(cB,{children:t})}function u$(e){let{name:t,editingName:n,provider:s,onChange:l,onEditingNameChange:o,onRename:a,onDelete:d,onAddModels:c,enabledModels:u}=e,{t:p}=(0,e0.s)(),[h,f]=(0,i.useState)({phase:"idle"}),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useId)(),j=(e,t)=>l({...s,[e]:t});(0,i.useEffect)(()=>{b.current+=1,f({phase:"idle"}),g(""),v([])},[t,s.baseUrl,s.api,s.apiKey]);let k=(0,i.useCallback)(async()=>{if("loading"===h.phase)return;let e=++b.current;f({phase:"loading"}),v([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...s,models:void 0}})}),r=await n.json();if(e!==b.current)return;if(!n.ok||r.error||!r.models)return void f({phase:"error",message:r.error??`HTTP ${n.status}`});f({phase:"success",models:r.models,endpoint:r.endpoint??s.baseUrl??""})}catch(t){if(e!==b.current)return;f({phase:"error",message:t instanceof Error?t.message:String(t)})}},[h.phase,t,s]),S=new Set((s.models??[]).map(e=>e.id)),C="success"===h.phase?h.models:[],N=m.trim().toLocaleLowerCase(),$=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),E=$.slice(0,300),I=E.filter(e=>!S.has(e.id)).map(e=>e.id),M=x.filter(e=>!S.has(e)).length,T=I.length>0&&I.every(e=>x.includes(e)),R=!T&&I.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:p("i18n.provider")})}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(ur,{providerId:t,controller:u,noteId:w}),(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:d,children:p("i18n.delete")})]})]}),(0,r.jsx)(us,{providerId:t,controller:u,id:w})]}),(0,r.jsxs)(ub,{label:p("i18n.providerName"),children:[(0,r.jsx)(uw,{value:n,onChange:o,placeholder:"provider-name",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>a(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:p("i18n.rename")})]}),(0,r.jsx)(ub,{label:"Base URL",children:(0,r.jsx)(uw,{value:s.baseUrl??"",onChange:e=>j("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(ub,{label:"API Key",children:(0,r.jsx)(uj,{value:s.apiKey??"",onChange:e=>j("apiKey",e||void 0),placeholder:p("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(ub,{label:"API",children:(0,r.jsx)(uS,{value:s.api??"",onChange:e=>j("api",e||void 0),options:ux})}),(0,r.jsx)(ub,{label:"Headers",children:(0,r.jsx)(uL,{headers:s.headers,onChange:e=>j("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==h.phase&&(0,r.jsx)("button",{onClick:k,disabled:"loading"===h.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===h.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===h.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===h.phase?p("models.discoveryFetching"):p("models.discoveryFetch")}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:m,onChange:e=>g(e.target.value),placeholder:p("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":p("models.discoveryFilter"),style:{...uy,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:T,disabled:0===I.length,onChange:()=>{let e=new Set(I);v(t=>T?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===E.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):E.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:$.length>E.length?p("models.discoveryShowing",{shown:E.length,total:$.length}):p("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!S.has(t.id));0!==t.length&&(c(t),v([]))},disabled:0===M,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:M?"var(--accent)":"var(--bg-panel)",color:M?"var(--accent-contrast)":"var(--text-dim)",cursor:M?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:M?p("models.discoveryAddSelectedCount",{count:M}):p("models.discoveryAddSelected")})]})]})]})]})}let uE=["off","minimal","low","medium","high","xhigh","max"],uI={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function uM(e){let{value:t,onChange:n}=e,{t:i}=(0,e0.s)(),s=t??{},l=(e,t)=>{let r={...s};"omit"===t?delete r[e]:r[e]=t,n(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:uE.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",o="string"==typeof t?t:"",a=uI[e],d={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:a,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>l(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>l(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:i("i18n.disabled")})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>l(e,o||e),style:{...d,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:i("i18n.custom")}),(0,r.jsx)("input",{value:o,onChange:t=>l(e,t.target.value),onFocus:()=>{"string"!==n&&l(e,o||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===n?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===n?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let uT={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function uR(e){return e.compat?.thinkingFormat==="deepseek"}function uA(e,t){return{...e.compat??{},...t.compat??{}}}function uL(e){let{headers:t,onChange:n}=e,{t:s}=(0,e0.s)(),[l,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),a=(0,i.useRef)(l.length),d=e=>{o(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},c=(e,t)=>{d(l.map(n=>n.id===e?{...n,...t}:n))},u={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[l.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...uy,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...uy,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void d(l.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>o(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:["+ ",s("models.addHeader")]})]})}function uz(e){let{providerName:t,provider:n,model:s,onChange:l,onDelete:o}=e,[a,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,e0.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>cb(s.cost)),x=(0,i.useRef)(m),[v,b]=(0,i.useState)(!1),y=(0,i.useRef)(0),w=s.baseUrl??n.baseUrl,j=(0,i.useRef)(0),k=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>l({...s,[e]:t}),N=(()=>{if("idle"===a.phase)return null;if("testing"===a.phase)return c("i18n.testingModel");let e=[void 0!==a.latencyMs?`${a.latencyMs}ms`:null,void 0!==a.status?`HTTP ${a.status}`:null].filter(Boolean);return"success"===a.phase?[c("i18n.connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,a.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>(y.current+=1,d({phase:"idle"}),()=>{y.current+=1}),[t,n,s]),(0,i.useEffect)(()=>{j.current+=1,p({phase:"idle"}),k.current=null},[t,w,s.id]);let $=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===a.phase)return;let e=++y.current;d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:s})}),i=await r.json();if(e!==y.current)return;if(!r.ok||!i.ok)return void d({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});d({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(t){if(e!==y.current)return;d({phase:"error",message:t instanceof Error?t.message:String(t)})}},[s,n,t,a.phase]),E=(0,i.useCallback)(async()=>{let e=s.id.trim();if(!e||"loading"===u.phase)return;let n=++j.current;p({phase:"loading"});try{let r=new URLSearchParams({q:e,provider:t,limit:"50"});w?.trim()&&r.set("baseUrl",w.trim());let i=await fetch(`/api/models-config/catalog?${r}`),o=await i.json();if(n!==j.current)return;if(!i.ok||o.error||!o.recommendation)return void p({phase:"error",message:o.error??`HTTP ${i.status}`});let a=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let l=cy(cb(i));s>0&&l&&(n.cost={...i,...l},r+=s)}return{model:n,appliedCount:r}}(s,o.recommendation.preset);a.appliedCount>0&&(k.current=s,l(a.model)),f(!1),p({phase:"success",recommendation:o.recommendation,appliedCount:a.appliedCount})}catch(e){if(n!==j.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,l,w,t]),I=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?c("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?c("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):c("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),M="error"===u.phase?u.message:I,T="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:c("models.costInput")},{key:"output",label:c("models.costOutput")},{key:"cacheRead",label:c("models.costCacheRead")},{key:"cacheWrite",label:c("models.costCacheWrite")}],A=new Set(Object.keys(s.compat??{})),L=0;uR(s)&&(L+=1,A.delete("thinkingFormat"),A.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(s.compat??{},"supportsDeveloperRole")&&(L+=1,A.delete("supportsDeveloperRole")),L+=A.size;let z=cf(s),P=cm(z),W=[s.baseUrl?c("models.baseUrlOverride"):null,s.api?`API: ${s.api}`:null,Object.keys(s.headers??{}).length?c("models.headersSummary",{count:Object.keys(s.headers??{}).length}):null,L?c("models.compatSummary",{count:L}):null,Object.keys(s.thinkingLevelMap??{}).length?c("models.thinkingSummary",{count:Object.keys(s.thinkingLevelMap??{}).length}):null,void 0!==P?c("models.imageMaxBytesSummary",{size:cg(P)}):null].filter(e=>!!e),O=W.length?W.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:c("i18n.model")})}),(0,r.jsxs)(cF,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===a.phase?"#fecaca":"success"===a.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===a.phase?"#fee2e2":"success"===a.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:N}),(0,r.jsxs)(c2,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>d({phase:"idle"}):$,disabled:!s.id.trim()||"testing"===a.phase,title:c("i18n.testConnection"),className:"success"===a.phase?"is-success":void 0,children:["success"===a.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===a.phase?c("i18n.checking"):"success"===a.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:o,children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(ub,{label:"ID *",children:(0,r.jsx)(uw,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(ub,{label:"Name",children:(0,r.jsx)(uw,{value:s.name??"",onChange:e=>C("name",e||void 0),placeholder:c("models.displayNamePlaceholder")})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void E(),disabled:!s.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:s.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:s.id.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),M&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:T,fontSize:10},children:[(0,r.jsx)("span",{title:M,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),k.current&&(0,r.jsx)("button",{onClick:()=>{let e=k.current;e&&(k.current=null,l(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(uN,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(uC,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(uC,{label:c("models.imageInput"),checked:s.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(uN,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);S.current=s.cost;let e=cb(s.cost);x.current=e,g(e),f(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?c("models.finishEditingCosts"):c("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(ub,{label:c("models.contextWindow"),children:(0,r.jsx)(uk,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(ub,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(uk,{value:void 0!==s.maxTokens?String(s.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:c("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[R.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(ub,{label:n,children:(0,r.jsx)(uk,{value:m[t],onChange:e=>{let n,r,i;return r=cy(n={...x.current,[t]:e}),i={...s},void(x.current=n,g(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,l(i))},placeholder:"0"})},t)}),cw(m)&&!cy(m)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:c("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:R.map(e=>{let t,{key:n,label:i}=e,l=s.cost?.[n]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),(0,r.jsx)("div",{style:{marginTop:3,color:l?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=s.cost?.[n])?c("models.notProvided"):`$${String(t)}`})]},n)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>b(e=>!e),"aria-expanded":v,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:c("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(ub,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(uw,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(ub,{label:c("models.apiOverride"),children:(0,r.jsx)(uS,{value:s.api??"",onChange:e=>C("api",e||void 0),options:ux})}),(0,r.jsxs)(ub,{label:c("models.headers"),children:[(0,r.jsx)(uL,{headers:s.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("models.headersHelp")})]}),(s.input?.includes("image")||void 0!==z)&&(0,r.jsxs)(ub,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(uk,{value:void 0===z?"":String(z),onChange:e=>{var t;let n,r,i,o;return l((t=e.trim()||void 0,n={...ch(s.inputLimits)?s.inputLimits:{}},r={...ch(n.images)?n.images:{}},i={...ch(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=cm(t)??t,Object.keys(i).length?r.resize=i:delete r.resize,Object.keys(r).length?n.images=r:delete n.images,o={...s},Object.keys(n).length?o.inputLimits=n:delete o.inputLimits,o))},placeholder:String(4718592),invalid:void 0===P&&void 0!==z}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==P&&`${cg(P)} \xb7 `,c("models.imageMaxBytesHelp",{size:cg(4718592)})]}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"inputLimits.images.resize.maxBytes"})]}),s.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(uN,{children:c("models.compatibility")}),(0,r.jsx)(uC,{label:c("models.deepSeekThinkingCompat"),checked:uR(s),onChange:e=>l(function(e,t){if(t)return{...e,compat:{...e.compat??{},...uT}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(s,e))}),(0,r.jsx)(uC,{label:c("models.developerRole"),checked:!1!==uA(n,s).supportsDeveloperRole,onChange:e=>l(cj(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(uC,{label:c("models.adaptiveThinking"),checked:!0===uA(n,s).forceAdaptiveThinking,onChange:e=>l(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return cj(e,t,n);if(!e.compat||!Object.prototype.hasOwnProperty.call(e.compat,t))return e;let i={...e.compat};return delete i[t],{...e,compat:Object.keys(i).length?i:void 0}}(s,"forceAdaptiveThinking",e,n.compat?.forceAdaptiveThinking===!0))}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",paddingLeft:19},children:"compat.forceAdaptiveThinking"})]}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(uN,{children:c("models.thinkingLevelMap")}),s.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:c("models.clearAll")})]}),(0,r.jsx)(uM,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function uP(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:l}=e,[o,a]=(0,i.useState)({phase:"idle"}),{t:d}=(0,e0.s)(),[c,u]=(0,i.useState)(""),p=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===o.phase||"prompt"===o.phase)&&setTimeout(()=>h.current?.focus(),50)},[o.phase]),(0,i.useEffect)(()=>{a({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let f=(0,i.useCallback)(()=>{p.current?.close(),a({phase:"connecting"}),u("");let e=new EventSource(`/api/auth/login/${encodeURIComponent(t.id)}`);p.current=e,e.onmessage=t=>{let r=JSON.parse(t.data);"auth"===r.type?(a({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(a({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?a({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?a({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?a({phase:"progress",message:r.message}):"success"===r.type?(e.close(),a({phase:"success"}),n()):"error"===r.type?(e.close(),a({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),a({phase:"idle"}))},e.onerror=()=>{e.close(),a(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[t.id,n]),m=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),a({phase:"idle"}),n()},[t.id,n]),g=(0,i.useCallback)(async(e,n)=>{if(n.trim()){a({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??`Server error ${r.status}`});return}u("")}catch(e){a({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[t.id]),x=(0,i.useCallback)(async(e,n)=>{a({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){a({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[t.id]),v="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===o.phase?0:16},children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:d("i18n.subscription")})}),(0,r.jsxs)(cF,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.loggedIn?"#4ade80":"var(--text-dim)"},children:d(t.loggedIn?"i18n.connected":"i18n.notConnected")})]}),v?(0,r.jsx)(c2,{size:"small",onClick:()=>{p.current?.close(),a({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(c2,{variant:"primary",size:"small",onClick:f,children:d(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:m,children:d("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===o.phase?0:48},children:["idle"===o.phase&&!t.loggedIn&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthConnect",{provider:t.name})}),"connecting"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:d("i18n.openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:o.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:o.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(o.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsx)(uo,{message:"auth"===o.phase?d("models.oauthPasteRedirect"):o.message,hint:"auth"===o.phase?(0,r.jsxs)(r.Fragment,{children:[d("models.oauthNoBrowser")," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",children:d("models.oauthOpenLoginPage")}),d("models.oauthOpenLoginPageEnd")]}):void 0,value:c,placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??d("models.oauthValuePlaceholder"),submitLabel:d("i18n.submit"),inputRef:h,onValueChange:u,onSubmit:()=>void g(o.token,c)}),"device_code"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthDeviceCode")}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:o.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:o.verificationUri}),o.expiresInSeconds?` Expires in ${Math.ceil(o.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o.message}),"success"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:d("i18n.connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:o.message})]}),(0,r.jsx)(up,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(ul,{providerId:t.id,controller:s,contextSettings:l})]})}function uW(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:l}=e,[o,a]=(0,i.useState)(""),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),{t:x}=(0,e0.s)();(0,i.useEffect)(()=>{a(""),f(null),g(!1)},[t.id]);let v=(0,i.useCallback)(async()=>{if(o.trim()){c(!0),f(null),g(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o.trim()})}),r=await e.json();!e.ok||r.error?f(r.error??`HTTP ${e.status}`):(a(""),g(!0),setTimeout(()=>g(!1),2e3),n())}catch(e){f(String(e))}finally{c(!1)}}},[o,t.id,n]),b=(0,i.useCallback)(async()=>{p(!0),f(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?f(r.error??`HTTP ${e.status}`):n()}catch(e){f(String(e))}finally{p(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:"API Key"})}),(0,r.jsxs)(cF,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:x(t.configured?"i18n.configured":"i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:b,disabled:u,children:x(u?"i18n.removing":"i18n.disconnect")})]})]}),!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?x("models.apiKeyEnableOne",{provider:t.displayName}):x("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(uj,{value:o,onChange:a,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&v()},placeholder:t.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:v,disabled:d||!o.trim()||m,style:{padding:"6px 12px",background:m?"#16a34a":o.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:m?"#fff":o.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:d||!o.trim()||m?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[m&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),x(m?"i18n.saved":d?"i18n.saving":"i18n.save")]})]}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),(0,r.jsx)(up,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(ul,{providerId:t.id,controller:s,contextSettings:l})]})}function uO(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:l,onAddCustom:o,onClose:a}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,e0.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),f=t.filter(e=>!e.loggedIn&&cN(h,e.id,e.name)),m=n.filter(e=>!e.configured&&cN(h,e.id,e.displayName)),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=f.length+m.length+ +!!g,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),a())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:p,value:d,onChange:e=>c(e.target.value),placeholder:u("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{o(),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),f.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(ud,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(f.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{l(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:1===e.modelCount?u("models.modelCountOne"):u("models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(ud,{id:e.id,size:28})]},e.id))]})})]})})}function uF(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:l}=(0,e0.s)(),o=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[l,o]=(0,i.useState)(null),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),d(null)}).catch(e=>{t.signal.aborted||d({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||s(!1)}),()=>t.abort()},[e,h]);let m=(0,i.useCallback)((t,r)=>{if(c.current){u.current={key:t,body:r};return}c.current=t,o(t),d(null),(async()=>{try{let t=await fetch("/api/models/enabled",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...e?{cwd:e}:{}})}),i=await t.json();if(!t.ok||i.error){let e=i.reason?ut[i.reason]:void 0;d(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){d({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,o(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=m;let g=(0,i.useCallback)((e,t,n)=>{m(e,{op:"models",refs:t,enabled:n})},[m]),x=(0,i.useCallback)((e,t)=>{m(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[m]),v=(0,i.useCallback)(()=>m("clear",{op:"clear"}),[m]),b=(0,i.useCallback)(()=>m("prune",{op:"prune"}),[m]),y=(0,i.useCallback)(()=>f(e=>e+1),[]),w=(0,i.useCallback)((e,n)=>{m("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[m,t]);return{view:t,loading:r,pending:l,failure:a,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:w}}(s),[a,d]=(0,i.useState)({providers:{}}),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(um),[j,k]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,$]=(0,i.useState)(!1),[E,I]=(0,i.useState)(!1),M=(0,i.useRef)(new Set),T=(0,i.useRef)(new Map),R=(0,i.useRef)(new Map),[A,L]=(0,i.useState)(null),z=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&k(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&C(e.apiKeyProviders)}).catch(()=>{}).finally(()=>$(!0))},[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{let t=e.providers?e:{...e,providers:{}};d(t),M.current=new Set(Object.keys(t.providers??{})),R.current=ck(t);let n=Object.keys(t.providers??{});w(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>u(!1)),z()},[z]),(0,i.useEffect)(()=>{y&&cs("models",JSON.stringify(y))},[y]),(0,i.useEffect)(()=>{if(y?.type!=="provider")return;let e=a.providers?.[y.name];e&&ug(e)&&(j.some(e=>e.id===y.name)?w({type:"oauth",providerId:y.name}):S.some(e=>e.id===y.name)&&w({type:"apikey",providerId:y.name}))},[S,a.providers,j,y]);let P=e=>({overrides:a.providers?.[e]?.modelOverrides,disabled:c||p||null!==g,onChange:(t,n)=>{try{d(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},l={...s.modelOverrides},o=Object.hasOwn(l,n)?l[n]:void 0;if(void 0!==o&&!cl(o))throw Error("Model override must be an object");let a={...o};return void 0===r?delete a.contextWindow:a.contextWindow=r,Object.keys(a).length?Object.defineProperty(l,n,{value:a,enumerable:!0,configurable:!0}):delete l[n],Object.keys(l).length?s.modelOverrides=l:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(a,e,t,n)),b(!1),m(null)}catch(e){m(String(e))}}}),W=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;a.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),w({type:"provider",name:e})},[a.providers]),O=(0,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),F=(0,i.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:l}=t,o=cC(t,n);o===r?s.delete(o):null!==o&&s.set(o,r);let a=l.get(n);a&&(l.delete(n),l.set(r,a));let d=Object.entries(i),c=d.findIndex(e=>{let[t]=e;return t===n});return d[c]=[r,d[c][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:M.current,renames:T.current,slots:R.current},t,n);return r?(d(r),L(null),w(e=>e?"provider"===e.type&&e.name===t?{type:"provider",name:n}:"model"===e.type&&e.providerName===t?{...e,providerName:n}:e:e),r):null},[]),D=(0,i.useCallback)((e,t)=>{F(a,e,t)?m(null):m(l("models.providerNameTaken",{name:t}))},[F,a,l]),B=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=cC(t={savedProviders:M.current,renames:T.current,slots:R.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...a.providers??{}},delete r[e],{...a,providers:r}),s=Object.keys(i.providers??{});L(t=>t?.provider===e?null:t),d(i),w(s.length>0?{type:"provider",name:s[0]}:null)},[a]),H=(0,i.useCallback)(e=>{cS(R.current,e,1),d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return w({type:"model",providerName:e,index:n}),t})},[]),_=(0,i.useCallback)((e,t)=>{d(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));cS(R.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],l=new Set(s.map(e=>e.id));for(let e of t)l.has(e.id)||(l.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),U=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),q=(0,i.useCallback)((e,t)=>{R.current.get(e)?.splice(t,1),d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),w({type:"provider",name:e})},[]),K=(0,i.useCallback)(async()=>{if(g)return;h(!0),m(null),b(!1);let e=a,t=A?.name.trim();if(A&&t&&a.providers?.[A.provider]){let n=F(a,A.provider,t);if(!n){m(l("models.providerNameTaken",{name:t})),h(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!cl(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(cl(n)&&cl(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!cl(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=ca(r.contextWindow);if(void 0===n)throw new co(`${e}/${t}`);r.contextWindow=n}return t}(e);if(cu(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!cu(t))continue;if(t.oauth&&!t.baseUrl)throw new cc(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(cp),r=cu(t.modelOverrides)&&Object.keys(t.modelOverrides).length>0;if(!n&&!t.baseUrl&&!t.headers&&!t.compat&&!r&&!t.apiKey&&!t.oauth&&void 0===t.authHeader)throw new cc(e,"empty")}var r=e;if(ch(r.providers)){for(let[e,t]of Object.entries(r.providers))if(ch(t)&&Array.isArray(t.models))for(let n of t.models){if(!ch(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=cf(n);if(void 0!==t&&void 0===cm(t))throw new cx(`${e}/${"string"==typeof n.id?n.id:"?"}`)}}let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),i=await t.json();if(!t.ok||i.error)m(i.error??`HTTP ${t.status}`);else{b(!0),setTimeout(()=>b(!1),2e3);let t=[...T.current].map(e=>{let[t,n]=e;return{from:t,to:n}}),n=function(e,t,n){let r=e=>{for(let[t,r]of n)if(r===e)return t;return e},i=[];for(let[n,s]of Object.entries(e.providers??{})){let e=t.get(n);e&&(s.models??[]).forEach((t,s)=>{let l=e[s];l&&t.id&&l!==t.id&&i.push({from:`${r(n)}/${l}`,to:`${n}/${t.id}`})})}return i}(e,R.current,T.current);M.current=new Set(Object.keys(e.providers??{})),R.current=ck(e),T.current.clear(),o.resync(t,n)}}catch(e){e instanceof cc?(m(l(uv[e.problem],{provider:e.provider})),w({type:"provider",name:e.provider})):e instanceof co?m(l("models.contextInvalid",{model:e.model})):m(e instanceof cx?l("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{h(!1)}},[F,a,o,g,A,l]),V=Object.entries(a.providers??{}).filter(e=>{let[t,n]=e;if(!ug(n))return!0;let r=j.some(e=>e.id===t)||S.some(e=>e.id===t);return N&&!r}),Z=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=c7(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(o.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},J=j.filter(e=>e.loggedIn),Y=S.filter(e=>e.configured),G=(()=>{if(!y)return null;if("oauth"===y.type){let e=j.find(e=>e.id===y.providerId);return e?(0,r.jsx)(uP,{provider:e,onRefresh:z,enabledModels:o,contextSettings:P(e.id)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(uW,{provider:e,onRefresh:z,enabledModels:o,contextSettings:P(e.id)},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e&&V.some(e=>{let[t]=e;return t===y.name})?(0,r.jsx)(u$,{name:y.name,editingName:A?.provider===y.name?A.name:y.name,provider:e,onChange:e=>O(y.name,e),onEditingNameChange:e=>L(e===y.name?null:{provider:y.name,name:e}),onRename:e=>D(y.name,e),onDelete:()=>B(y.name),onAddModels:e=>_(y.name,e),enabledModels:o},y.name):null}let e=a.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(uz,{providerName:y.providerName,provider:e,model:t,onChange:e=>U(y.providerName,y.index,e),onDelete:()=>q(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(c$,{embedded:n,title:l("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:l("i18n.close"),onClose:t,children:[(0,r.jsx)(un,{controller:o}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsxs)(cM,{children:[J.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(cL,{active:t,onClick:()=>w({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(ud,{id:e.id,size:16}),(0,r.jsx)(cz,{className:"is-grow",children:e.name}),Z(e.id)]},e.id)}),Y.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(cL,{active:t,onClick:()=>w({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(ud,{id:e.id,size:16}),(0,r.jsx)(cz,{className:"is-grow",children:e.displayName}),Z(e.id)]},e.id)}),(J.length>0||Y.length>0)&&V.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):V.map(e=>{let[t,n]=e,i=y?.type==="provider"&&y.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(cL,{onClick:()=>w({type:"provider",name:t}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(cz,{className:"is-grow",children:t}),Z(t)]}),s.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(cL,{active:i,className:"models-sidebar-indented-item",onClick:()=>w({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(cz,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:e.name?.trim()||e.id||l("i18n.newModel")}),e.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)(cL,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),H(t)},children:(0,r.jsxs)(cz,{children:["+ ",l("i18n.model")]})})]},t)})]}),(0,r.jsx)(c8,{onClick:()=>I(!0),children:l("i18n.addProvider")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:c?null:G??(0,r.jsx)(cX,{children:l("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(c0,{status:g||f?(0,r.jsx)("span",{style:{color:"#f87171"},children:g?l("models.configUnreadable",{error:g}):f}):l("models.applyHelp"),children:[!n&&(0,r.jsx)(c2,{onClick:t,children:l("i18n.cancel")}),(0,r.jsxs)(c2,{variant:"primary",onClick:K,disabled:p||v||null!==g,className:v?"is-success":void 0,children:[v&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:v?l("i18n.saved"):p?l("i18n.saving"):l("i18n.save")})]})]})]}),E&&(0,r.jsx)(uO,{oauthProviders:j,apiKeyProviders:S,onSelectOAuth:e=>w({type:"oauth",providerId:e}),onSelectApiKey:e=>w({type:"apikey",providerId:e}),onAddCustom:W,onClose:()=>I(!1)})]})}let uD=null;async function uB(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(uD)return uD;let t=(async()=>{try{let t=await fetch("/api/push/config");if(!t.ok)return!1;let{publicKey:n}=await t.json();if(!n)return!1;let r=await navigator.serviceWorker.ready,i=await r.pushManager.getSubscription();return i||(i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}(n)})),(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscription:i.toJSON(),locale:e})})).ok}catch{return uD=null,!1}})();return uD=t,t.then(e=>{e||uD!==t||(uD=null)}),t}function uH(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function u_(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function uU(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function uq(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function uK(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function uV(e,t){return e?e.slice(0,8):t}function uZ(e){let{skill:t,cwd:n,onToggle:s,toggling:l,saveError:o,updateStatus:a,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:f}=(0,e0.s)(),m=uU(t),g=!t.disableModelInvocation,[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),w=t.filePath.split(/[\\/]/).pop(),[j,k]=(0,i.useState)([]),S=j.at(-1)??w,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[$,E]=(0,i.useState)(0),I=(0,i.useCallback)(e=>{let t=function(e,t){let n=e.indexOf("#"),[r,i]=[n<0?e:e.slice(0,n),n<0?"":e.slice(n+1)].map(e=>{try{return decodeURIComponent(e)}catch{return e}});if(!r)return{document:t,anchor:i};if(r.startsWith("/"))return{document:r,anchor:i};let s=t.split("/").slice(0,-1);for(let e of r.split("/"))".."===e&&s.length&&".."!==s[s.length-1]?s.pop():e&&"."!==e&&s.push(e);return{document:s.join("/"),anchor:i}}(e,S);N.current=t.anchor,t.document===S?E(e=>e+1):k(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||b)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,b,$]),(0,i.useEffect)(()=>{let e=new AbortController;return v(null),y(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});S!==w&&i.set("document",S);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),l=await s.json();if(!s.ok||l.error||"string"!=typeof l.content)throw Error(l.error??`HTTP ${s.status}`);v((r=l.content,dN(r).rest.trim()))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,S,w]),(0,r.jsxs)(cP,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(cW,{children:[(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:m,children:uq(m,f)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===m?ew(t.filePath,n):ey(t.filePath)})]}),(0,r.jsx)(cF,{children:(0,r.jsx)(c4,{checked:g,loading:l,label:f(g?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!g&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:f("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(cH,{label:f("config.source"),children:(0,r.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:t.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[t.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),t.install&&(0,r.jsxs)(cH,{label:f("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:uV(a?.currentVersion??t.install.versionHash,f("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(c2,{size:"small",onClick:p,disabled:d||c,children:f("i18n.check")}),a?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:uV(a.latestVersion,f("i18n.unknown"))}),(d||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":a?.state==="up-to-date"?"is-success":a?.state==="error"?"is-error":"is-muted"}`,children:d?f("i18n.checking"):a?.state==="up-to-date"?f("i18n.upToDate"):a?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):a?.message||f("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.jsx)(c2,{variant:"primary",size:"small",onClick:h,disabled:c||d,children:f(c?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(cH,{label:f("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(cH,{label:f("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(cH,{label:f("skills.instructions"),ref:C,children:[j.length>0&&(0,r.jsx)(cW,{children:(0,r.jsxs)(cO,{children:[(0,r.jsx)(c2,{size:"small",onClick:()=>{N.current="",k(e=>e.slice(0,-1))},children:f("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),b?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:b}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:f("i18n.loading")}):x?(0,r.jsx)(sk,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:I,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:f("skills.noInstructions")})]})]})}function uJ(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(new Set),[j,k]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);u(n.results??[]),0===(n.results??[]).length&&m(o("i18n.noSkills"))}catch(e){m(String(e))}finally{h(!1)}}},[o]),N=(0,i.useCallback)(async e=>{x(e),b(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:j,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);w(t=>new Set(t).add(`${j}:${e}`)),l()}catch(e){b(String(e))}finally{x(null)}},[l,j,t]),$="global"===j?"~/.pi/agent/skills/":`${ey(t)}/.pi/skills/`;return(0,r.jsxs)(cP,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(cZ,{title:o("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(cV,{value:j,label:o("config.saveTo"),options:[{value:"global",label:uq("global",o)},{value:"project",label:uq("project",o),disabled:!s}],path:$,disabledReason:o("trust.projectScopeUnavailable"),onChange:k})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(a)},placeholder:o("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(c2,{variant:"primary",onClick:()=>C(a),disabled:p||!a.trim(),children:p?o("i18n.searching"):o("i18n.search")})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:f}),v&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:v})]}),c.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let t=n[j].has(e.package)||y.has(`${j}:${e.package}`),i=g===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,a=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:a??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(c2,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==g,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${o("i18n.installed")}`:i?o("i18n.installing"):o("i18n.install")})]},e.package)})})]})}function uY(e){let{cwd:t,onClose:n,embedded:s=!1,trust:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>ci("skills",t)),[g,x]=(0,i.useState)(new Set),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,$]=(0,i.useState)({}),[E,I]=(0,i.useState)(new Set),[M,T]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!0),O=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return d(r),W(n.projectResourcesLoaded??!0),m(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{$({}),z(null),O()},[t]);let F=u_(l),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,O())},[F,O]),(0,i.useEffect)(()=>{f&&cs("skills",f,t)},[t,f]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(uK).filter(e=>!!e);if(0!==n.length){z(null),I(e=>new Set([...e,...n])),e||T(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);$(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{I(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||T(!1)}}},[t,a]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=uK(e);A(n),z(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await O();let s=i.skill?.install?.versionHash;$(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,O]),_=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),b(null),k(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),U=(0,i.useCallback)(async(e,t,n)=>{let r=uH(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;x(e=>new Set([...e,...i])),w(e),b(null),k(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let l=n.results;d(e=>{let t;return t=new Set(l.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let a=l.filter(e=>e.error);if(a.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));k({group:e,error:[o("skills.bulkFailed",{count:a.length,total:l.length}),...a.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){k({group:e,error:t instanceof Error?t.message:String(t)})}finally{w(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[o]),q=a.find(e=>e.filePath===f)??null,K=c||g.size>0||null!==R;return(0,r.jsxs)(c$,{embedded:s,title:o("common.skills"),subtitle:ey(t),closeLabel:o("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(cG,{message:o("trust.skillsNotLoaded")}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===a.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:o("i18n.noSkills")}):(()=>{let e=[],t={project:o("skills.scope.project"),global:o("skills.scope.global"),path:o("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===uU(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===uU(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===uU(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===uU(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===uU(e)}]){let t=a.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&f===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(cL,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(c3,{active:!s}),(0,r.jsx)(cz,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=uK(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:o("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,s=i.filter(e=>!e.disableModelInvocation).length,l=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{aside:(0,r.jsx)(cR,{enabled:s,total:i.length,disabled:K,loading:y===t,label:o(l?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),j?.group===t&&(0,r.jsx)(cA,{error:j.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(c8,{onClick:()=>C(!0),active:S,children:o("i18n.addSkill")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:S?(0,r.jsx)(uJ,{cwd:t,projectResourcesLoaded:P,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{O()}}):c?null:q?(0,r.jsx)(uZ,{skill:q,cwd:t,onToggle:_,toggling:g.has(q.filePath),saveError:v,updateStatus:uK(q)?N[uK(q)]:void 0,checkingUpdate:!!uK(q)&&E.has(uK(q)),updating:R===uK(q),updateError:L,onCheckUpdate:()=>void B(q),onUpdate:()=>void H(q)},q.filePath):(0,r.jsx)(cX,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(c0,{status:Object.values(N).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(N).filter(e=>"update-available"===e.state).length," ",1===Object.values(N).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!s&&(0,r.jsx)(c2,{onClick:n,children:o("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(c2,{variant:"secondary",onClick:()=>void B(),disabled:M||null!==R,children:M?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let uG={builtin:0,global:1,workspace:2,project:3},uX=["read","bash","edit","write","grep","find","ls"],uQ=["","off","minimal","low","medium","high","xhigh","max"],u0={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,codemode:"off",mcp:"off",promptMode:"append",inheritContext:!1,runInBackground:!1,enabled:!0},u1={width:"100%",minWidth:0,height:34,padding:"0 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},u2={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function u4(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,...void 0!==e.skills?{skills:[...e.skills]}:{},loadExtensions:e.loadExtensions,codemode:e.codemode??"off",mcp:e.mcp??"off",...void 0!==e.extensions?{extensions:[...e.extensions]}:{},promptMode:e.promptMode,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.maxTurns?{maxTurns:e.maxTurns}:{},inheritContext:e.inheritContext,runInBackground:e.runInBackground,enabled:e.enabled}}function u8(e){return`${e.scope}:${e.name}`}function u3(e){return"global"===e||"project"===e}function u5(e){return u3(e)||"builtin"===e}function u6(e){let{label:t,children:n}=e;return(0,r.jsx)(cH,{label:t,children:n})}function u9(e){let{checked:t,disabled:n,label:i,onChange:s}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:7,color:n?"var(--text-dim)":"var(--text-muted)",fontSize:12,cursor:n?"default":"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,disabled:n,onChange:e=>s(e.target.checked)}),i]})}function u7(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:l,embedded:o=!1,trust:a}=e,d=te(),{t:c}=(0,e0.s)(),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(!0),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(()=>ci("agents",t)),[w,j]=(0,i.useState)(u0),[k,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[$,E]=(0,i.useState)(!0),[I,M]=(0,i.useState)(!1),[T,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[V,Z]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),G=(0,i.useMemo)(()=>u.find(e=>u8(e)===b)??null,[u,b]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{E(!0),P(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let s=e??ci("agents",t),l=i.find(e=>u8(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(l?u8(l):null),l&&(j(u4(l)),S(u3(l.scope)?"edit":"view"),u3(l.scope)&&N(l.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{E(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&cs("agents",b,t)},[t,b]);let ee=u_(a);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);f(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{M(!0),P(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:w})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(u8(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}},en=async()=>{if(G&&u3(G.scope)&&window.confirm(c("agents.deleteConfirm",{name:G.displayName}))){M(!0),P(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}}},er="view"!==k,ei="create"===k,es=!er||I||A,el=ei?C:G?.scope,eo=ei?"global"===C?`~/.pi/agent/agents/${w.name||"..."}.md`:`./.pi/agents/${w.name||"..."}.md`:G?(G.filePath?"project"===G.scope||"workspace"===G.scope?ew(G.filePath,t):ey(G.filePath):null)??c("agents.builtinPath"):"",ea=ei?eo:G?.filePath??eo,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=w.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&uQ.includes(r)?e.slice(0,n):e}(w.model,ed),eu=!ec||ed(ec),ep=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eh=es?{...u1,...u2}:u1,ef=ei?es:!G||!u5(G.scope)||I||A,em=(e,t)=>{j(n=>({...n,[e]:t}))},eg=0===w.tools.length&&!w.loadSkills&&!w.loadExtensions,ex=async e=>{if(ei)return void em("enabled",e);if(G&&u5(G.scope)){L(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>u8(e)===u8(i)?i:e)),j(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ev=async e=>{U(!0),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),Z(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{U(!1)}},eb=async e=>{D(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ej=async()=>{if(n){Y(!0),K(null);try{await aI(n,{type:"reload"}),Z(!1),l?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(c$,{embedded:o,title:c("common.agents"),subtitle:ey(t),closeLabel:c("agents.close"),onClose:s,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:c("agents.builtInTitle")}),(0,r.jsx)("span",{children:c("agents.builtInDescription")}),V&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[V&&n&&(0,r.jsx)(c2,{size:"small",onClick:()=>void ej(),disabled:J||_,children:J?c("agents.reloading"):c("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:c("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:c("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":c("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:B||_,onChange:e=>D(Number(e.target.value)),onBlur:()=>void eb(F)})]}),(0,r.jsx)(c4,{checked:W,disabled:B||J,loading:_,label:c("agents.builtInTitle"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:$?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:c("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=u.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=uG[e.scope],u.some(e=>e.name.toLowerCase()===t&&uG[e.scope]>n));return(0,r.jsxs)(cL,{active:b===u8(e)&&!ei,onClick:()=>{y(u8(e)),j(u4(e)),S(u3(e.scope)?"edit":"view"),u3(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(c3,{active:e.enabled}),(0,r.jsx)(cz,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},u8(e))})]},e)})}),(0,r.jsx)(c8,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),j({...u0,name:e,displayName:e}),S("create"),N("global"),P(null)},children:c("agents.new")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:G||ei?(0,r.jsxs)(cP,{children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:ei?(0,r.jsx)(cV,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:I})),path:eo,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[el&&(0,r.jsx)(cq,{scope:el,children:c(`agents.scope.${el}`)}),(0,r.jsx)("span",{title:ea,className:"config-detail-path",children:eo})]})}),(0,r.jsxs)(cF,{children:[G&&("view"===k||"edit"===k)&&(0,r.jsx)(c2,{size:"small",onClick:()=>{if(!G)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(G.name,u);y(null),j({...u4(G),name:e,displayName:c("agents.copyName",{name:G.displayName})}),S("create"),N(u3(G.scope)?G.scope:"global"),P(null)},disabled:I||A,children:c("agents.duplicate")}),G&&u3(G.scope)&&"edit"===k&&(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:()=>void en(),disabled:I||A,children:c("agents.delete")}),(0,r.jsx)(c4,{checked:w.enabled,disabled:ef,label:w.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ex(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(u6,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:w.name,disabled:es,onChange:e=>em("name",e.target.value),style:u1}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:w.name})}),(0,r.jsx)(u6,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:w.displayName,disabled:es,onChange:e=>em("displayName",e.target.value),style:eh})})]}),(0,r.jsx)(u6,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:w.description,disabled:es,onChange:e=>em("description",e.target.value),style:eh})}),(0,r.jsx)(u6,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:w.systemPrompt,disabled:es,onChange:e=>em("systemPrompt",e.target.value),style:{...eh,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(u6,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:uX.map(e=>(0,r.jsx)(u9,{label:e,disabled:es,checked:w.tools.includes(e),onChange:t=>em("tools",t?[...w.tools,e]:w.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(u6,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(u9,{label:c("agents.loadSkills"),disabled:es,checked:w.loadSkills,onChange:e=>em("loadSkills",e)}),(0,r.jsx)(u9,{label:c("agents.loadExtensions"),disabled:es,checked:w.loadExtensions,onChange:e=>em("loadExtensions",e)}),(0,r.jsx)(u9,{label:c("agents.mcp"),disabled:es||eg&&"on"!==w.mcp,checked:"on"===w.mcp,onChange:e=>em("mcp",e?"on":"off")})]}),w.loadSkills&&void 0!==w.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:w.skills.length>0?c("agents.skillsOnly",{skills:w.skills.join(", ")}):c("agents.skillsNone")}),w.loadExtensions&&void 0!==w.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:w.extensions.length>0?c("agents.extensionsOnly",{extensions:w.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eg?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===w.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(u6,{label:c("agents.codemode"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsxs)("select",{"aria-label":c("agents.codemode"),value:w.codemode??"off",disabled:es,onChange:e=>em("codemode",e.target.value),style:{...eh,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,r.jsx)("option",{value:"inherit",children:c("agents.codemode.inherit")}),(0,r.jsx)("option",{value:"on",children:c("agents.codemode.on")}),(0,r.jsx)("option",{value:"off",children:c("agents.codemode.off")})]}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.codemodeHint")})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(u6,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(oW,{options:X,value:ep,onChange:(e,t)=>em("model",`${e}/${t}`),onClear:()=>em("model",void 0),emptyLabel:m?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:w.model&&!eu?c("agents.modelUnavailable",{model:w.model}):w.model!==ec?w.model:void 0,disabled:es||m||0===h.length&&!w.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(u6,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:w.thinking??"",disabled:es,onChange:e=>em("thinking",e.target.value||void 0),style:eh,children:uQ.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(u6,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:w.maxTurns??"",disabled:es,onChange:e=>em("maxTurns",e.target.value?Number(e.target.value):void 0),style:eh})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(u9,{label:c("agents.inheritContext"),disabled:es,checked:w.inheritContext,onChange:e=>em("inheritContext",e)}),(0,r.jsx)(u9,{label:c("agents.background"),disabled:es,checked:w.runInBackground,onChange:e=>em("runInBackground",e)})]})]}):(0,r.jsx)(cX,{children:c("agents.empty")})})})]}),(0,r.jsx)(c0,{status:(q||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||z}),children:er&&(0,r.jsxs)(c2,{variant:"primary",onClick:()=>void et(),disabled:I||T||A||!w.name.trim(),className:T?"is-success":void 0,children:[T&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:T?c("i18n.saved"):I?c("agents.saving"):c("agents.save")})]})})]})}let pe=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function pt(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function pn(e){return`${e.scope}\0${e.source}`}function pr(e){return`extension\0${e.path}`}function pi(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function ps(e,t){return t(`plugins.status.${e}`)}function pl(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function po(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function pa(e){let{pkg:t}=e,{t:n}=(0,e0.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n(t.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function pd(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:l,actionError:o,onSourceChange:a,onScopeChange:d,onInstall:c}=e,{t:u}=(0,e0.s)();return(0,r.jsx)(cJ,{title:u("i18n.addPlugin"),catalogs:[{href:"https://pi.dev/packages",label:"pi.dev/packages",icon:(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]})}],target:(0,r.jsx)(cV,{value:i,label:u("config.saveTo"),options:[{value:"global",label:pi("global",u)},{value:"project",label:pi("project",u),disabled:!s}],path:"project"===i?`${ey(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:d}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!l&&!!n.trim(),normalizeValue:pt,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:pe,error:o,children:(0,r.jsx)(c2,{variant:"primary",onClick:c,disabled:l||!n.trim(),className:"is-pushed-right",children:u(l?"i18n.installing":"i18n.install")})})}function pc(e){let t,{pkg:n,cwd:s,busyKey:l,actionError:o,actionMessage:a,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:f,onReloadSession:m}=e,{t:g}=(0,e0.s)(),x=pn(n),v=(l?.endsWith(x)||l?.startsWith("bulk:"))??!1,b="reload"===l,y=!n.disabled,w=n.canCheckForUpdates,j=c?.state==="update-available",k=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(cP,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cW,{className:"is-top-aligned",children:[(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:n.scope,children:pi(n.scope,g)}),n.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:g("i18n.disabled")}):n.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:g("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.source})]}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(c2,{size:"small",variant:j?"primary":void 0,onClick:j||!w?()=>h("update",n):f,disabled:v||b||u,title:j?g("i18n.updateAvailable"):void 0,children:g(l===`update:${x}`?"i18n.updating":u?"i18n.checking":j||!w?"i18n.update":"i18n.check")}),(0,r.jsx)(c2,{size:"small",onClick:m,disabled:!d||b||v,"aria-describedby":d?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(l===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(c4,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(c_,{children:[k&&(0,r.jsx)(cU,{label:g("i18n.description"),children:k}),(0,r.jsx)(cU,{label:g("i18n.status"),tone:"plain",style:{color:po(n.status),textTransform:"capitalize"},children:ps(n.status,g)}),(0,r.jsxs)(cU,{label:g("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],n.version&&t.push(g("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(g("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):g("i18n.unknown"))}),j&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:g("i18n.updateAvailable")}),w&&(u||c&&!j)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):c?.state==="up-to-date"?g("i18n.upToDate"):c?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):c?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(cU,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(cU,{label:g("i18n.resources"),children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(n,g)}),(0,r.jsx)(cU,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?ey(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(cU,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:ey(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(cB,{children:g("i18n.resolvedResources")}),(0,r.jsx)(pa,{pkg:n})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function pu(e){let{extension:t}=e,{t:n}=(0,e0.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(cP,{children:[(0,r.jsx)(cW,{children:(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:t.scope,children:pi(t.scope,n)}),(0,r.jsx)(cD,{children:t.name})]})}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(cU,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:ps(i,n)}),(0,r.jsx)(cU,{label:n("i18n.installedPath"),mono:!0,children:ey(t.path)})]})]})}function pp(e){var t;let{cwd:n,sessionId:s,onClose:l,onReloaded:o,embedded:a=!1,trust:d}=e,{t:c}=(0,e0.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>ci("plugins",n)),[b,y]=(0,i.useState)(!1),[w,j]=(0,i.useState)(""),[k,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[$,E]=(0,i.useState)(null),[I,M]=(0,i.useState)(null),[T,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[z,P]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),q=_.find(e=>pn(e)===x)??null,K=U.find(e=>pr(e)===x)??null,V=u?.projectResourcesLoaded??!0,Z=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:_.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[_]),J=(0,i.useCallback)(async()=>{f(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>pn(t)===e)||t.standaloneExtensions.some(t=>pr(t)===e))?e:t.packages[0]?pn(t.packages[0]):t.standaloneExtensions[0]?pr(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let Y=u_(d),G=(0,i.useRef)(Y);(0,i.useEffect)(()=>{G.current!==Y&&(G.current=Y,J())},[Y,J]),(0,i.useEffect)(()=>{x&&cs("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(pn);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);L(e=>{let t={...e};for(let e of r.updates??[])t[pn(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||O(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),E(null),M(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),L({}),M(c("i18n.packagesUpdated")),s&&M(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){E(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=pn(t);N(`${e}:${r}`),E(null),M(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)v(s.packages[0]?pn(s.packages[0]):s.standaloneExtensions[0]?pr(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),M(c("i18n.packageRemoved")),L(e=>{let t={...e};return delete t[r],t});else{let t={install:c("i18n.packageInstalled"),update:c("i18n.packageUpdated"),disable:c("i18n.packageDisabled"),enable:c("i18n.packageEnabled")};M(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t,r)=>{let i=uH(t,r,e=>!e.disabled,e=>e.filtered),l=r?0:t.filter(e=>!e.disabled&&e.filtered).length,o=l>0?c("plugins.bulkKeptFiltered",{count:l}):void 0;if(E(null),M(null),R(o?{scope:e,note:o}:null),0===i.length)return;let a=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:a,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),l=await t.json();if(!t.ok||l.error||!l.results)throw Error(l.error??`HTTP ${t.status}`);let{results:d,...u}=l;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");M(s?`${e} ${c("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:o,error:[c("plugins.bulkFailed",{count:h.length,total:d.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:o,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,s,c]),en=(0,i.useCallback)(async()=>{let e=pt(w).trim();if(!e)return;j(e);let t=`${k}\0${e}`;N(`install:${t}`),E(null),M(null),R(null);try{var r;let i,s,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:k,cwd:n})}),o=await l.json();if(!l.ok||o.error)throw Error(o.error??`HTTP ${l.status}`);p(o);let a=(r=o.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===k&&e.source===i)??r.find(e=>e.scope===k&&e.source===`npm:${s}`)??r.find(e=>e.scope===k&&e.source.endsWith(i)));v(a?pn(a):t),y(!1),j(""),M(c("i18n.packageInstalled"))}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,k,w,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),E(null),M(null),R(null);try{await aI(s,{type:"reload"}),o?.(),await J(),M(c("i18n.sessionReloaded"))}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,o,s,c]),ei=C?.startsWith("install:")??!1,es=Object.values(A).filter(e=>"update-available"===e.state).length,el=_.some(e=>e.canCheckForUpdates),eo=h||null!==C||z.size>0||B;return(0,r.jsxs)(c$,{embedded:a,title:c("common.plugins"),subtitle:ey(n),closeLabel:c("i18n.close"),onClose:l,children:[!V&&(0,r.jsx)(cG,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):m?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:m}):0===_.length&&0===U.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:c("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[U.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{children:c("i18n.extensions")}),U.map(e=>{let t=pr(e);return(0,r.jsxs)(cL,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),E(null),M(null)},children:[(0,r.jsx)(c3,{active:e.enabled}),(0,r.jsx)(cz,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),Z.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{aside:(0,r.jsx)(cR,{enabled:t,total:e.packages.length,disabled:eo,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:pi(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:pi(e.scope,c)}),T?.scope===e.scope&&(0,r.jsx)(cA,{error:T.error,note:T.note}),e.packages.map(e=>{let t=pn(e),n=!b&&x===t;return(0,r.jsxs)(cL,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),E(null),M(null)},children:[(0,r.jsx)(c3,{active:!e.disabled,color:po(e.status)}),(0,r.jsx)(cz,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[pn(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(c8,{active:b,onClick:()=>{y(!0),E(null),M(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:b?(0,r.jsx)(pd,{cwd:n,source:w,scope:k,projectResourcesLoaded:V,busy:ei,actionError:$,onSourceChange:j,onScopeChange:S,onInstall:en}):h?null:K?(0,r.jsx)(pu,{extension:K}):q?(0,r.jsx)(pc,{pkg:q,cwd:n,busyKey:C,actionError:$,actionMessage:I,sessionId:s,updateStatus:A[pn(q)],checkingUpdate:z.has(pn(q)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(q),onReloadSession:er},pn(q)):(0,r.jsx)(cX,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(c0,{status:es>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[es," ",1===es?c("i18n.update"):c("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(c1,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?c("plugins.diagnostic"):c("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(pl)}):(0,r.jsx)(c1,{summary:u?[c("i18n.resourceCount",{count:(t=u.totals).extensions,label:c("i18n.extensionShort")}),c("i18n.resourceCount",{count:t.skills,label:c("i18n.skillShort")}),c("i18n.resourceCount",{count:t.prompts,label:c("i18n.promptShort")}),c("i18n.resourceCount",{count:t.themes,label:c("i18n.themeShort")})].join(" \xb7 "):""}),children:[!a&&(0,r.jsx)(c2,{onClick:l,children:c("i18n.close")}),el&&(0,r.jsx)(c2,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?Q():X()),disabled:eo,title:es>0?c("i18n.updateAllPluginsHint"):void 0,children:B?c("i18n.updating"):W?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(c2,{variant:"secondary",onClick:()=>void J(),disabled:eo,children:c("i18n.refresh")})]})]})}let ph={en:{title:"Archives",empty:"No archived projects.",loadFailed:"Could not load archives.",sessions:"{count} sessions",unarchive:"Unarchive",deleteSessions:"Delete",deleteConfirmLead:"Deletes {count} chat sessions. Does not delete the code folder.",deleteConfirmHint:"Type confirm to continue.",deleteConfirmName:"confirm",cancel:"Cancel",busy:"Working…",runningBlocked:"Stop the running agent in this project first.",deleteFailed:"Could not delete those sessions.",path:"Path",untitled:"Untitled session",messages:"{count} messages"},"zh-CN":{title:"归档",empty:"没有已归档的项目。",loadFailed:"无法加载归档列表。",sessions:"{count} 个会话",unarchive:"取消归档",deleteSessions:"删除",deleteConfirmLead:"将删除该项目下 {count} 个聊天会话,不会删除磁盘上的代码目录。",deleteConfirmHint:"输入「确认」继续。",deleteConfirmName:"确认",cancel:"取消",busy:"处理中…",runningBlocked:"请先停止该项目中正在运行的 agent。",deleteFailed:"删除会话失败。",path:"路径",untitled:"未命名会话",messages:"{count} 条消息"},"zh-TW":{title:"封存",empty:"沒有已封存的專案。",loadFailed:"無法載入封存清單。",sessions:"{count} 個工作階段",unarchive:"取消封存",deleteSessions:"刪除",deleteConfirmLead:"將刪除該專案下 {count} 個聊天工作階段,不會刪除磁碟上的程式碼目錄。",deleteConfirmHint:"輸入「確認」繼續。",deleteConfirmName:"確認",cancel:"取消",busy:"處理中…",runningBlocked:"請先停止該專案中正在執行的 agent。",deleteFailed:"刪除工作階段失敗。",path:"路徑",untitled:"未命名工作階段",messages:"{count} 則訊息"}};function pf(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function pm(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function pg(e){var t;let n,{onClose:s,embedded:l=!1}=e,{locale:o}=(0,e0.s)(),a=ph[o]??ph.en,[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,j]=(0,i.useState)(""),[k,S]=(0,i.useState)(null),C=(0,i.useCallback)(async()=>{g(!1);try{let[e,t]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok)throw Error("load failed");let n=await e.json(),r=await t.json().catch(()=>({}));"string"==typeof r.home&&f(r.home);let i=Array.isArray(n.projects)?n.projects:[];c(i),p(e=>e&&i.some(t=>t.key===e)?e:i[0]?.key??null)}catch{g(!0)}},[]);(0,i.useEffect)(()=>{C()},[C]);let N=d.find(e=>e.key===u)??null,$=async e=>{if(0!==e.length){v(!0),S(null);try{for(let t of L(e)){let e={action:"set",ids:t,archived:!1},n=await fetch("/api/sessions/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"});if(!n.ok)throw Error(`unarchive failed: ${n.status}`)}y(!1),j(""),await C()}catch{S(a.loadFailed)}finally{v(!1)}}},E=async e=>{v(!0),S(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:w.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void S(a.runningBlocked);if(!t.ok)throw Error(n.error??"delete failed");y(!1),j(""),c(t=>t.filter(t=>t.key!==e.key)),p(t=>t===e.key?null:t)}catch{S(a.deleteFailed)}finally{v(!1)}};return(0,r.jsx)(c$,{embedded:l,title:a.title,onClose:s,children:m?(0,r.jsx)(cX,{children:a.loadFailed}):0===d.length?(0,r.jsx)(cX,{children:a.empty}):(0,r.jsxs)(cE,{children:[(0,r.jsx)(cI,{children:(0,r.jsx)(cM,{children:d.map(e=>(0,r.jsx)(cL,{active:e.key===u,onClick:()=>{p(e.key),y(!1),j(""),S(null)},children:(0,r.jsx)(cz,{title:e.root,children:pm(e.root)})},e.key))})}),(0,r.jsx)(cQ,{children:N?(0,r.jsxs)(cP,{children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(cD,{children:pm(N.root)})}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(c2,{variant:"secondary",size:"small",disabled:x||0===N.families.length,onClick:()=>void $(N.families.map(e=>e.id)),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:x||0===N.families.length,onClick:()=>{y(!0),j(""),S(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(cH,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=N.root,h&&t.startsWith(h)?"~"+t.slice(h.length):t)})}),b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:pf(a.deleteConfirmLead,{count:N.families.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:a.deleteConfirmHint}),(0,r.jsx)("input",{value:w,onChange:e=>j(e.target.value),placeholder:a.deleteConfirmName,"aria-label":a.deleteConfirmName,autoComplete:"off",style:{alignSelf:"flex-start",width:"min(220px, 100%)",fontFamily:"var(--font-mono)",fontSize:12,padding:"6px 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=w.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void E(N),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(c2,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),j("")},children:a.cancel})]})]}),(0,r.jsx)(cB,{children:pf(a.sessions,{count:N.families.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:N.families.map(e=>{let t=function(e,t){let n=e.name?.trim();if(n)return n;let r=e.firstMessage?.replace(/\s+/g," ").trim();return r&&"(no messages)"!==r?r:t}(e,a.untitled);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:6,background:"var(--bg-hover)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsx)(c2,{variant:"ghost",size:"small",disabled:x,onClick:()=>void $([e.id]),children:x?a.busy:a.unarchive})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,t8.fw)(new Date(e.archivedAt),o)}),(0,r.jsx)("span",{children:pf(a.messages,{count:e.messageCount})})]})]},e.id)})}),k&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:k})]}):(0,r.jsx)(cX,{children:a.empty})})]})})}let px="\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\u00A0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000\\uFE00-\\uFE0F\\u{E0100}-\\u{E01EF}\\u115F\\u1160\\u3164\\uFFA0\\u2800",pv=RegExp(`[${px}]`,"gu"),pb=RegExp(`[${px}]`,"u");function py(e){return e.replace(pv,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let pw=/[\s"'`$|&;<>()*?#~]/;function pj(e){let t=pb.test(e),n=py(e);return""===n||t||pw.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function pk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(pj).join(" ")}function pS(e){let t=void 0!==e.command?pk(e.command,e.args):void 0,n=void 0!==e.url?py(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function pC(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&pb.test(e))}function pN(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:py(e.name??"")}}}function p$(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function pE(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function pI(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function pM(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?py(e.error):"link-outside"===e.reason?void 0===t?void 0:py(t):void 0}let pT="codemode";function pR(e){return`${e.scope}\0${e.name}`}function pA(e){return e?.trust?.decision===!0}function pL(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function pz(e,t){return void 0!==e.invalidError?"invalid":e.webPasswordField?"web-password":e.enabled?"project"!==e.scope||t.projectServersLoad?"global"===e.scope&&e.shadowedByProject&&t.projectServersLoad?"replaced":"global"===e.scope&&e.overriddenByProject&&t.projectServersLoad?"overridden":t.mcpAvailable?e.status?pL(e.status):"on":"mcp-off":"not-trusted":"disabled"}let pP={invalid:"mcp.state.invalid","web-password":"mcp.state.web-password",disabled:"mcp.state.disabled","not-trusted":"mcp.state.not-trusted",replaced:"mcp.state.replaced",overridden:"mcp.state.overridden","mcp-off":"mcp.state.mcp-off",connected:"mcp.state.connected","needs-auth":"mcp.state.needs-auth",failed:"mcp.state.failed",connecting:"mcp.state.connecting",disconnected:"mcp.state.disconnected",conflict:"mcp.state.conflict",on:"mcp.state.on"},pW={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function pO(e,t){return(t?.origin==="session"?pW[e]:void 0)??pP[e]}let pF={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},pD={invalid:"mcp.stateShort.invalid","web-password":"mcp.stateShort.web-password",disabled:"mcp.stateShort.disabled","not-trusted":"mcp.stateShort.not-trusted",replaced:"mcp.stateShort.replaced",overridden:"mcp.stateShort.overridden","needs-auth":"mcp.stateShort.needs-auth",failed:"mcp.stateShort.failed",connecting:"mcp.stateShort.connecting",disconnected:"mcp.stateShort.disconnected",conflict:"mcp.stateShort.conflict"};function pB(e){return"on"===e||"connected"===e?"on":"invalid"===e||"web-password"===e||"failed"===e||"conflict"===e?"error":"not-trusted"===e||"needs-auth"===e||"disconnected"===e?"warning":"off"}function pH(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function p_(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=new Date(e),i=new Date(n);return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?r.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"}):r.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}let pU={connecting:"mcp.session.state.connecting",connected:"mcp.session.state.connected","needs-auth":"mcp.session.state.needs-auth",failed:"mcp.session.state.failed",disconnected:"mcp.session.state.disconnected",conflict:"mcp.session.state.conflict","not-trusted":"mcp.session.state.not-trusted"},pq={connecting:"mcp.session.summary.connecting",connected:"mcp.session.summary.connected","needs-auth":"mcp.session.summary.needs-auth",failed:"mcp.session.summary.failed",disconnected:"mcp.session.summary.disconnected",conflict:"mcp.session.summary.conflict","not-trusted":"mcp.session.summary.not-trusted"},pK={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},pV={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},pZ=["codemode","deferred","direct","hidden"],pJ={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function pY(e){return"auto-enable-codemode-invalid"!==e.reason}function pG(e,t){return(t?["project","global"]:["global"]).map(t=>{let n=e.files.find(e=>e.scope===t);return{scope:t,...n?{file:n}:{},servers:e.servers.filter(e=>e.scope===t)}})}function pX(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function pQ(e,t){let n=e.flatMap(e=>e.servers.map(pR));return t===pT||null!==t&&n.includes(t)?t:n[0]??null}function p0(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function p1(e){return e.projectOverride?.preference??e.preference}let p2={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},p4={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},p8={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},p3={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function p5(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let p6=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function p9(e,t){let n=e??{},r=n.breadth,i=n.trust;return{error:"string"==typeof n.error?n.error:`HTTP ${t}`,..."string"==typeof n.reason?{reason:n.reason}:{},..."string"==typeof n.path?{path:n.path}:{},..."string"==typeof n.name?{name:n.name}:{},..."string"==typeof n.suggestedName?{suggestedName:n.suggestedName}:{},...p6(n.names)?{names:n.names}:{},...p6(n.fields)?{fields:n.fields}:{},...Array.isArray(n.notes)?{notes:n.notes.filter(e=>"string"==typeof e?.code)}:{},..."string"==typeof r?.kind&&"string"==typeof r.path?{breadth:r}:{},..."boolean"==typeof i?.requiresTrust&&"boolean"==typeof i.trusted?{trust:i}:{},...!0===n.trustKept?{trustKept:!0}:{}}}async function p7(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},l=new AbortController,o=()=>l.abort();r?.aborted?l.abort():r?.addEventListener("abort",o,{once:!0});let a=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&l.abort()},n)});try{return await Promise.race([e(l.signal),a])}finally{clearTimeout(i),r?.removeEventListener("abort",o)}}function he(e){return null!==e&&"object"==typeof e&&"object"==typeof e.mcp&&null!==e.mcp&&"object"==typeof e.codemode&&null!==e.codemode&&Array.isArray(e.files)&&Array.isArray(e.servers)}async function ht(e,t,n){let r,i;try{r=await t(e?`/api/mcp?cwd=${encodeURIComponent(e)}`:"/api/mcp",{cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&he(i)?{ok:!0,data:i}:{ok:!1,error:p9(i,r.status)}}let hn=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function hr(e,t,n){let r=await ht(e,t,n);if(r.ok||!e||!r.error.reason||!hn.has(r.error.reason))return r;let i=await ht(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function hi(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(n=>hr(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function hs(e,t,n,r){let i,s;try{i=await n("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{s=await i.json()}catch{return{ok:!1,error:{error:`HTTP ${i.status}`}}}let l=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==l?{ok:!0,stored:l}:{ok:!1,error:p9(s,i.status)}}async function hl(e,t,n){let r=await hs({codemode:e},e=>{var t;return"automatic"===(t=e.codemode)||"always"===t?e.codemode:void 0},t,n);return r.ok?{ok:!0,preference:r.stored}:r}async function ho(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(n=>hl(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function ha(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(async n=>{let r=await hs({codemodeMode:e},e=>{var t;return null!==(t=e.codemodeMode)&&"object"==typeof t&&("on"===t.value||"only"===t.value)&&(void 0===t.invalid||"string"==typeof t.invalid)?e.codemodeMode:void 0},t,n);return r.ok?{ok:!0,mode:r.stored}:r},()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function hd(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(async n=>{let r=await hs({codemodeInlineBudget:e},e=>{var t;return null!==(t=e.codemodeInlineBudget)&&"object"==typeof t&&(void 0===t.value||"number"==typeof t.value)&&(void 0===t.invalid||"string"==typeof t.invalid)?e.codemodeInlineBudget:void 0},t,n);return r.ok?{ok:!0,inlineBudget:r.stored}:r},()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}function hc(e){return!e.available&&"builtin-disabled"!==e.reason}function hu(e,t){if(hc(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!pA(t.project))return"project-untrusted"}}let hp={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function hh(e){return!0!==e.notAnObject}function hf(e){return hh(e)&&void 0===e.webPasswordField}async function hm(e,t,n){let r,i;try{r=await t("/api/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&he(i)?{ok:!0,data:i}:{ok:!1,error:p9(i,r.status)}}async function hg(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3,s={...e,...t?{cwd:t}:{}};return p7(e=>hm(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let hx={"mcp-off":"mcp.test.blocked.mcp-off","project-untrusted":"mcp.test.blocked.project-untrusted","trust-unreadable":"mcp.test.blocked.trust-unreadable",invalid:"mcp.test.blocked.invalid","web-password":"mcp.test.blocked.web-password"};function hv(e,t){let n=hu(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let hb={"mcp-off":"mcp.test.blocked.mcp-off","project-untrusted":"mcp.test.blocked.project-untrusted","trust-unreadable":"mcp.test.blocked.trust-unreadable","server-invalid":"mcp.test.blocked.invalid","web-password":"mcp.test.blocked.web-password","entry-not-object":"mcp.test.refused.entry-not-object","invalid-request":"mcp.test.refused.invalid-request",unparsable:"mcp.test.refused.unparsable","invalid-shape":"mcp.test.refused.invalid-shape","link-dangling":"mcp.test.refused.link-dangling","link-outside":"mcp.test.refused.link-outside","not-a-file":"mcp.test.refused.not-a-file","too-large":"mcp.test.refused.too-large","too-many-servers":"mcp.test.refused.too-many-servers"},hy={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},hw={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},hj={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function hk(e){return(Math.max(0,e)/1e3).toFixed(1)}async function hS(e,t,n){let r,i;try{r=await t("/api/mcp/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&function(e){if(null===e||"object"!=typeof e)return!1;let t=e.result;return"string"==typeof e.configKey&&"string"==typeof e.name&&("global"===e.scope||"project"===e.scope)&&"object"==typeof t&&null!==t&&"string"==typeof t.state&&Array.isArray(t.tools)&&"number"==typeof t.testedAt}(i)?{ok:!0,data:i}:{ok:!1,error:p9(i,r.status)}}async function hC(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4,s={scope:e.scope,name:e.name,...t?{cwd:t}:{}};return p7(e=>hS(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let hN="•••",h$=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),hE=new Set([...h$,"auth","sig","code","pw"]),hI=["token","secret","password","passwd","apikey"],hM=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),hT=new Set(["-k"]);function hR(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function hA(e,t){let n=hR(e);return!(n.length>1&&hM.has(n[n.length-1]))&&n.some(e=>t.has(e)||hI.some(t=>e.length>t.length&&e.endsWith(t)))}function hL(e){return hA(e,h$)}let hz=RegExp("^(?:sk-[A-Za-z0-9_-]{16,}|(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abposr]-[A-Za-z0-9-]{10,}|(?:AKIA|ASIA)[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|ya29\\.[0-9A-Za-z_-]{20,}|npm_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{30,}|shp(?:at|ss|ca|pa)_[A-Fa-f0-9]{20,}|dop_v1_[a-f0-9]{40,}|lin_api_[A-Za-z0-9]{20,})"),hP=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,hW=/^[A-Za-z0-9_\-+/=.~]+$/;function hO(e){return!(/\s/.test(e)||h_(e))&&(!!(hz.test(e)||hP.test(e))||!(e.length<24||!hW.test(e)||/^[./~]/.test(e)||/\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(e)||e.split("/").length>2)&&!!/\d/.test(e)&&!!/[A-Za-z]/.test(e)&&(/[a-z]/.test(e)&&/[A-Z]/.test(e)||/^[0-9a-f]+$/i.test(e)||!/[-_.]/.test(e))&&function(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0;for(let r of t.values()){let t=r/e.length;n-=t*Math.log2(t)}return n}(e)>=3.5)}let hF=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,hD=RegExp(hF.source,"g"),hB=/^(?:bearer|basic|token)\s+/i;function hH(e,t,n){let r=e.replace(hB,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function h_(e){return hH(e.replace(/\$[$!]/g,"_x"),hF,hD)}let hU=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,hq=RegExp(hU.source,"g");function hK(e){return hH(e,hU,hq)}function hV(e,t){if(!e||""===t)return;e.push(t);let n=hY(t);n!==t&&e.push(n)}let hZ=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function hJ(e,t,n){let r=!1,i=e,s="",l=hZ.exec(e);if(l){let[o,a,d]=l,c=d.lastIndexOf("@");if(c>=0&&!t(hY(d.slice(0,c)))){s=`${a}${hN}${d.slice(c)}`,r=!0;let e=d.slice(0,c);hV(n,e);let t=e.indexOf(":");t>=0&&hV(n,e.slice(t+1))}else s=o;i=e.slice(o.length)}let o=i.search(/[?#]/),a=o<0?i:i.slice(0,o),d=o<0?"":i.slice(o),c=a.split("/").map(e=>hO(hY(e))?(r=!0,hV(n,e),hN):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let l=s.indexOf("=");if(l<0){let l=hY(s);return!hO(l)||t(l)?e:(r=!0,hV(n,s),`${i}${hN}`)}let o=s.slice(0,l),a=hY(s.slice(l+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return hA(t,hE)}(o)&&!hO(a)?e:(r=!0,hV(n,s.slice(l+1)),`${i}${o}=${hN}`)}),{value:`${s}${c}${d}`,masked:r}}function hY(e){try{return decodeURIComponent(e)}catch{return e}}let hG=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function hX(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&hL(r[1])){let[,i,s,l]=r;return t(l)?{value:e,masked:!1}:(hV(n,l.trim()),{value:`${i}:${s}${hN}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||hG.test(e)))return;let i=!1;return{value:r.map(e=>{let r=hG.exec(e);if(!r)return e;let[,s,l]=r;if(""===l.trim()||t(l))return e;if(hL(s.slice(0,-1).trim()))return i=!0,hV(n,l.trim()),`${s}${hN}`;let o=hX(l,t,n);return i||=o.masked,`${s}${o.value}`}).join(";"),masked:i}}(e,t,n):void 0;if(i)return i;let s=/^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(e);if(s&&""!==s[2]&&hL(s[1]))return t(s[2])?{value:e,masked:!1}:(hV(n,s[2]),{value:`${s[1]}=${hN}`,masked:!0});if(/\s/.test(e)){var l,o,a;let r,i;return l=e,o=t,a=n,i=h1((r=l.split(/(\s+)/)).filter((e,t)=>t%2==0),o,!0,a),{value:r.map((e,t)=>t%2==0?i.values[t/2]:e).join(""),masked:i.masked}}if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(e))return hJ(e,t,n);if(s&&""!==s[2]){let e=hX(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return hO(e)&&!t(e)?(hV(n,e),{value:hN,masked:!0}):{value:e,masked:!1}}function hQ(e){if(hT.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return hL(t)||"auth"===hR(t).at(-1)}let h0=/^(?:bearer|basic|token)$/i;function h1(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&h0.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,hV(r,e),hN)}let l=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(l){let[,e,n]=l;if(""!==n&&hQ(e)&&!t(n))return i=!0,hV(r,n),`${e}=${hN}`;let s=hX(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=hQ(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(h0.test(e)||t&&hL(t[1]))return s=!0,e}let o=hX(e,t,r);return i||=o.masked,o.value}),masked:i}}function h2(e){let{values:t,masked:n}=h1(e,hK,!1);return{args:t,masked:n}}function h4(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function h8(e){return!e.startsWith("!")&&!h_(e)}function h3(e){return JSON.parse(e.replace(/^\uFEFF/,"").replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,e=>'"'===e[0]?e:"*"===e[1]?" ":"").replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g,(e,t)=>t??('"'===e[0]?e:"")))}let h5={"empty-input":"error","unrecognized-input":"error","invalid-json":"error","no-servers-found":"error","shell-operator":"error","shell-command-substitution":"error","shell-multiple-commands":"error","shell-unterminated-quote":"error","shell-parameter":"error","shell-expansion":"error","unsupported-url-scheme":"error","github-repo-link":"error","github-mcp-page":"error","github-page":"error","by-name-link":"error","badge-image":"error","install-link-invalid":"error","claude-desktop-import":"error","cli-unsupported":"error","cli-usage":"error","cli-unknown-option":"error","cli-option-needs-value":"error","cli-option-wrong-transport":"error","cli-invalid-pair":"error","cli-not-a-server":"error","pi-help":"error","field-required":"error","field-invalid-option":"error","field-reference-invalid":"error","sse-transport":"error","websocket-transport":"error","unsupported-transport":"error","ambiguous-command-and-url":"error","no-command-or-url":"error","zed-extension-server":"error","registry-packages-unsupported":"error","invalid-config":"error","dropped-key":"warning","variable-unsupported-here":"warning","variable-fallback-dropped":"warning","bare-dollar-literal":"warning","header-env-reference":"warning","client-secret-env-reference":"warning","shell-command-value":"warning","shell-variable":"warning","unsupported-variable":"warning","input-undefined":"warning","input-command-unsupported":"warning","timeout-clamped":"warning","timeout-dropped":"warning","timeout-unit-guessed":"warning","env-null-dropped":"warning","oauth-option-dropped":"warning","oauth-disable-unsupported":"warning","callback-url-dropped":"warning","callback-port-dropped":"warning","invalid-exposure-dropped":"warning","tool-filter-imported":"warning","transport-guessed":"warning","insecure-http":"warning","literal-secret":"warning","cli-option-ignored":"warning","cli-option-as-arg":"warning","cli-extra-arguments":"warning","mcp-remote-bridge":"warning","looks-like-pi-config":"warning","workspace-folder-relative":"warning","home-variable-translated":"warning","name-taken":"warning","escaped-value":"info","variable-translated":"info","home-translated":"info","timeout-converted":"info","env-value-stringified":"info","empty-authorization-dropped":"info","imported-disabled":"info","name-derived":"info","name-sanitized":"info","name-deduplicated":"info","command-split":"info","transport-assumed-http":"info","scheme-assumed":"info","client-secret-prompt":"info","userinfo-moved-to-header":"info"};Object.keys(h5);let h6={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},h9={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},h7={...h9,bareDollar:!0},fe={...h6,braceEnv:!0},ft=/^[A-Za-z_][A-Za-z0-9_]*$/,fn=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function fr(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function fi(e,t,n){let r=[],i=0;fn.lastIndex=0;for(let s=fn.exec(e);s;s=fn.exec(e)){let[l,o,a,d,c,u]=s,p=l;if(void 0!==o&&t.dollarBrace)p=function(e,t){let n=/^env:([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);if(n)return{kind:"env",name:n[1],from:t};let r=/^input:(.+)$/.exec(e);if(r)return{kind:"input",id:r[1],from:t};if("userHome"===e)return{kind:"home",from:t};if("workspaceFolder"===e||"workspaceRoot"===e||"CLAUDE_PROJECT_DIR"===e)return{kind:"workspace",from:t};if("workspaceFolderBasename"===e)return{kind:"workspace-basename",from:t};if("pathSeparator"===e||"/"===e)return"/";if("CLAUDE_PLUGIN_ROOT"===e||"CLAUDE_PLUGIN_DATA"===e)return{kind:"unsupported",from:t};if(ft.test(e))return{kind:"env",name:e,from:t};let i=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(e);return i?{kind:"env",name:i[1],from:t,fallback:i[2]}:/^[A-Za-z]+:/.test(e)?{kind:"unsupported",from:t}:t}(o,l);else if(void 0!==a&&t.bareDollar)p={kind:"env",name:a,from:l};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:l};else if(void 0!==c&&t.braceEnv)p="env"===c&&ft.test(u)?{kind:"env",name:u,from:l}:{kind:"unsupported",from:l};else if(void 0!==d||void 0!==c){fr(r,e.slice(i,s.index+1)),i=s.index+1,fn.lastIndex=s.index+1;continue}fr(r,e.slice(i,s.index)),"string"==typeof p?fr(r,p):r.push(p),i=s.index+l.length}return fr(r,e.slice(i)),r}function fs(e){let{atStart:t=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.replace(/\$/g,"$$$$");return t&&n.startsWith("!")?`$${n}`:n}function fl(e){return e.startsWith("!")}function fo(e){if(fl(e))return[];let t=[];for(let n=0;n<e.length;n++){if("$"!==e[n])continue;let r=e[n+1];if("$"===r||"!"===r){n++;continue}if("{"===r){let r=e.indexOf("}",n+2);if(r<0)continue;let i=e.slice(n+2,r);ft.test(i)&&!t.includes(i)&&t.push(i),n=r;continue}let i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(n+1));i&&(t.includes(i[0])||t.push(i[0]),n+=i[0].length)}return t}let fa=/<[A-Za-z][^<>\n]{0,80}>|\{\{\s*[A-Za-z_][\w.-]*\s*\}\}|\b[Yy][Oo][Uu][Rr][_-][A-Za-z0-9_.-]*[A-Za-z0-9]|\b[A-Za-z0-9_-]{0,80}[A-Za-z0-9][_-](?:HERE|[Hh]ere)\b|\b(?:REPLACE[_-]?ME|CHANGE[_-]?ME|PLACEHOLDER)\b|\bMY_[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PAT)\b|\b(?:sk|pk|ghp|gho|github_pat|glpat|xoxb|xoxp)[_-][xX*]{4,}\b|\b[xX]{6,}\b/g,fd=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,fc=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,fu=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function fp(e){return e.join("\0")}function fh(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function ff(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function fm(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let fg=new Set(["HOME","USERPROFILE"]);class fx{constructor(e,t){this.source=e,this.rawPi=t,this.args=[],this.env=[],this.headers=[],this.oauth={},this.notes=[]}note(e,t){let n=JSON.stringify([e,t??{}]);this.notes.some(e=>JSON.stringify([e.code,e.params??{}])===n)||this.notes.push(t?{code:e,params:t}:{code:e})}}function fv(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let fb=/\$\{[^{}]*\}/g,fy=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class fw{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(fv),this.urlText=fv(e.url??[])}encode(e,t){let n,r=ff(e),i=fh(e),s=fv(t),l=[],o=!1,a=()=>l.every(e=>""===e),d=e=>{if(!r)return void l.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=fs(e,{atStart:a()});n!==e&&(o=!0),l.push(n)},c=e=>l.push(e),u=e=>l.push({field:e});if(!r&&fm(e)&&1===t.length&&"text"in t[0]&&fc.test(s)){let t="args"===e[0]?/^(?:--?[A-Za-z][A-Za-z0-9_.-]*|[A-Za-z_][A-Za-z0-9_]*)=/.exec(s)?.[0]??"":"",n=s.slice(t.length);if(fc.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,l,void 0)}let p=0;return t.forEach((l,o)=>{let h=t[o+1],f=void 0===h||"text"in h&&/^[\\/]/.test(h.text),m=(t,r,i)=>{let l=0;for(let[d,c]of function(e){let t=e.trim();if(fd.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=fu.exec(t);if(n&&fd.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];fa.lastIndex=0;for(let t=fa.exec(e);t;t=fa.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var o,a;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>l&&r(t.slice(l,d)),"url"===e[0]&&fj(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(o=e,a=h,"env"===o[0]||"headers"===o[0]?o[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||fh(o)),h)),l=c}l<t.length&&r(t.slice(l))};switch(l.kind){case"text":m(l.text,d,[]);break;case"pi":{var g;let e=h?(g=l.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):l.text;if(r&&a()&&fl(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(fb)].map(e=>[e.index,e.index+e[0].length]);m(e,c,t);break}case"env":r?(c(`\${${l.name}}`),void 0!==l.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:l.name,fallback:l.fallback}),l.shell?this.draft.note("shell-variable",{field:i,name:l.name}):l.from!==`\${${l.name}}`&&this.draft.note("variable-translated",{field:i,from:l.from,to:`\${${l.name}}`})):fm(e)&&a()&&fg.has(l.name)&&f?(c("~"),this.draft.note("home-translated",{field:i,from:l.from})):(u(this.field(e,"variable",l.name,l.from,void 0,l.fallback)),this.draft.note(l.shell?"shell-variable":"variable-unsupported-here",{field:i,name:l.name}));break;case"input":u(this.inputField(e,l));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:l.from,to:"${HOME}"})):fm(e)&&a()&&f?(c("~"),this.draft.note("home-translated",{field:i,from:l.from})):u(this.field(e,"home","userHome",l.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",l.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:l.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",l.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",l.from,l.from)),this.draft.note("unsupported-variable",{field:i,variable:l.from});break;case"prompt":"url"===e[0]&&fj(s,p)&&(n="uri-component"),u(this.promptField(e,l))}p+=("text"in l?l.text:l.from).length}),o&&this.draft.note("escaped-value",{field:i}),this.target(e,l,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>fp(t.path)===fp(e))||i.targets.push({path:e,parts:r,...n?{encoding:n}:{}})}return r.map(e=>"string"==typeof e?e:this.fields.get(e.field).placeholder??"").join("")}field(e,t,n,r,i,s){let l=fy.has(t)?`${t}.${n}`:fh(e);if(fy.has(t)){if(this.fields.has(l))return l}else for(let t=2;this.fields.has(l);t++)l=`${fh(e)}#${t}`;let o=this.isSecretContext(e,r)||hL(n),a="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(l,{id:l,kind:i??(o?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&a?{optional:!0}:{},targets:[]}),l}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return hL(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(h2([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&h2([t,"x"]).args[1]===hN}case"url":{var n;let e=this.urlText.indexOf(t),r=e<0?void 0:/[?&]([^=&?#]+)=[^&#]*$/.exec(this.urlText.slice(0,e))?.[1];return void 0!==r&&(n=r,hJ(`https://host.invalid/?${n}=x`,hK).masked)}default:return!1}}}function fj(e,t){let n=e.indexOf("//"),r=e.slice(n<0?0:n+2).search(/[/?#]/);return r>=0&&t>=(n<0?0:n+2)+r}function fk(e,t,n){let r=n?void 0:function(e){let t;try{t=new URL(e)}catch{return}if(""===t.username&&""===t.password)return;let n=e=>{try{return decodeURIComponent(e)}catch{return e}},r=new TextEncoder().encode(`${n(t.username)}:${n(t.password)}`),i="";for(let e of r)i+=String.fromCharCode(e);return t.username="",t.password="",{url:t.toString(),authorization:`Basic ${btoa(i)}`}}(t);if(!r){e.url=[{kind:"text",text:t}];return}e.url=[{kind:"text",text:r.url}],e.headers.push(["Authorization",[{kind:"text",text:r.authorization}]]),e.note("userinfo-moved-to-header")}let fS=/^[A-Za-z0-9_-]+$/;function fC(e,t){let n=new Set(t);if(!n.has(e))return e;for(let t=2;;t++){let r=`${e}-${t}`;if(!n.has(r))return r}}let fN=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function f$(e){let t=e.trim(),n=t.lastIndexOf("@");n>0&&(t=t.slice(0,n)),t=t.replace(/==.*$|\[.*\]$/,"");let r="",i=/^@([^/]+)\/(.+)$/.exec(t);if(i)r=i[1],t=i[2];else if(t.includes("/")){let e=t.split("/").filter(Boolean);t=e[e.length-1]??t}let s=fI(t);return s&&!fN.has(s.toLowerCase())?s:fI(r)||r||s||t}let fE=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function fI(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,fE)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let fM=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function fT(e){let t;try{t=new URL(e).hostname}catch{return""}if("localhost"===t||"127.0.0.1"===t||"[::1]"===t||"::1"===t)return"local";if(/^\d+(?:\.\d+){3}$/.test(t))return"";let n=t.split(".").filter(Boolean);n.length>1&&n.pop(),n.length>1&&/^(?:co|com|org|net|ac|gov)$/.test(n[n.length-1])&&n.pop();let r=n.filter(e=>!fM.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let fR=new Set(["-e","--env","--env-file","-v","--volume","-p","--publish","--name","--network","--net","-w","--workdir","-u","--user","--mount","--entrypoint","-l","--label","--platform","--pull","-h","--hostname","--add-host","--cpus","-m","--memory","--restart","--runtime","--cap-add","--cap-drop","--device","--dns","--ipc","--pid","--security-opt","--tmpfs","--ulimit","--log-driver","--log-opt","--gpus"]);function fA(e,t){for(let n=0;n<e.length;n++){let r=e[n];if("--"===r)return e[n+1];if(r.startsWith("-")){!r.includes("=")&&t.has(r)&&n++;continue}return r}}function fL(e){let t=e.split(/[\\/]/).filter(Boolean);for(let e=t.length-1;e>=0;e--){let n=t[e].replace(/\.[A-Za-z0-9]+$/,"");if(!fN.has(n.toLowerCase())&&"."!==n&&".."!==n)return fI(n.replace(/_/g,"-"))||n}return""}function fz(e,t){fP(e,t)&&fW(e,Math.ceil(t/1e3),t)}function fP(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function fW(e,t,n){let r=Math.min(Math.max(t,1),3600);void 0!==n&&e.note("timeout-converted",{from:n,to:r}),r!==t&&e.note("timeout-clamped",{from:t,to:r}),e.timeout=r}let fO=["codemode","deferred","direct","hidden"],fF={"codemode-deferred":"codemode"},fD=["localhost","127.0.0.1","[::1]"];function fB(e){return"string"==typeof e&&fO.includes(e)?e:"string"==typeof e&&Object.hasOwn(fF,e)?fF[e]:void 0}function fH(e){try{return new URL(e)}catch{return}}function f_(e){let t=fH(e);return void 0!==t&&"http:"===t.protocol&&fD.includes(t.hostname)&&""===t.search&&""===t.hash}function fU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fq(e){return fU(e)&&Object.values(e).every(e=>"string"==typeof e)}function fK(e,t){if(!fS.test(e))return{problem:"name",name:e};if(!fU(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:l,description:o}=t;if(void 0!==r&&!fB(r))return{problem:"exposure",value:String(r)};if(void 0!==l){if(!fU(l))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(l))if(!fB(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==o&&"string"!=typeof o)return{problem:"description"};if(void 0!==s&&("number"!=typeof s||!(s>0)))return{problem:"timeout",value:String(s)};if("sse"===n)return{problem:"sse"};if("string"==typeof t.url&&(void 0===n||"http"===n||"streamable-http"===n)){let e=fH(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!fq(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!fU(e))return{problem:"oauth"};if(void 0!==e.clientId&&"string"!=typeof e.clientId)return{problem:"oauth-client-id"};if(void 0!==e.clientSecret&&"string"!=typeof e.clientSecret)return{problem:"oauth-client-secret"};let r=e.callbackPort;if(void 0!==r&&("number"!=typeof r||!Number.isInteger(r)||r<1||r>65535))return{problem:"callback-port",value:String(r)};if(void 0!==e.callbackUrl){if("string"!=typeof e.callbackUrl||!f_(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?fH(e.callbackUrl):void 0;if(t&&("[::1]"===t.hostname||"/callback"!==t.pathname))return{problem:"oauth-client-registration-callback"}}if(void 0!==e.authServerMetadataUrl&&!(void 0!==(n="string"==typeof(t=e.authServerMetadataUrl)?fH(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&fD.includes(n.hostname))))return{problem:"auth-server-metadata-url",value:String(e.authServerMetadataUrl)}}(t.oauth);if(n)return n;let r=t.auth;if(void 0!==r){if(!fU(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!fD.includes(e.hostname))return{problem:"auth-url"}}return}return"string"==typeof t.command&&(void 0===n||"stdio"===n)?void 0===t.args||Array.isArray(t.args)&&t.args.every(e=>"string"==typeof e)?void 0===t.env||fq(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let fV=/[A-Za-z_]/,fZ=/[A-Za-z0-9_]/,fJ=/^[A-Za-z_][A-Za-z0-9_]*$/,fY=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),fG=new Set([..."|&;<>()"]),fX=/[0-9@*#?$!-]/,fQ={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function f0(e,t){let n=t+1;for(;" "===e[n]||" "===e[n];)n++;return"\r"===e[n]&&"\n"===e[n+1]?n+2-t:"\n"===e[n]?n+1-t:0}function f1(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class f2{constructor(e){this.input=e,this.index=0,this.words=[],this.windowsWord=!1,this.lineBreak=!1}run(){try{this.scan()}catch(e){if(e instanceof f4)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new f4(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=f1(this.input,this.index)),this.parts}endWord(){if(!this.parts)return;let e=this.parts.filter(e=>"text"!==e.type||""!==e.value),t=e.length>0?e:this.parts.slice(0,1);this.words.push({parts:t,text:t.map(e=>"text"===e.type?e.value:e.raw).join("")}),this.parts=void 0,this.windowsWord=!1}appendText(e,t){let n=this.startWord(),r=n[n.length-1];r?.type==="text"&&r.quote===t?r.value+=e:n.push({type:"text",value:e,quote:t})}scan(){let{input:e}=this;for(;this.index<e.length;){let t=e[this.index];if(" "===t||" "===t)this.endWord(),this.index++;else if("\r"===t&&"\n"===e[this.index+1])this.index++;else if("\n"===t)this.endWord(),this.words.length>0&&(this.lineBreak=!0),this.index++;else if(("\\"===t||"^"===t||"`"===t)&&f0(e,this.index)>0)this.index+=f0(e,this.index);else if("#"!==t||this.parts)"'"===t?(this.startWord(),this.singleQuoted()):'"'===t?(this.startWord(),this.doubleQuoted()):"$"===t?this.dollar("none"):"`"===t?this.fail({code:"command-substitution",syntax:"`"}):fG.has(t)?this.fail({code:"shell-operator",operator:function(e,t){let n=e.slice(t,t+2);return["||","&&",";;",">>","<<",">&","<&",">|","<(",">(","&>"].includes(n)?n:e[t]}(e,this.index)}):"\\"===t?this.backslash():(this.appendText(t,"none"),this.index++);else for(;this.index<e.length&&"\n"!==e[this.index];)this.index++}this.endWord()}backslash(){let e=this.input[this.index+1];if(this.startWord(),void 0===e||this.windowsWord||!fY.has(e)){this.appendText("\\","none"),this.index++;return}this.appendText(e,"none"),this.index+=2}singleQuoted(){let e=this.input.indexOf("'",this.index+1);e<0&&this.fail({code:"unterminated-quote",quote:"'"}),this.appendText(this.input.slice(this.index+1,e),"single"),this.index=e+1}doubleQuoted(){let{input:e}=this,t=f1(e,this.index+1);for(this.index++,this.appendText("","double");this.index<e.length;){let n=e[this.index];if('"'===n)return void this.index++;if("\\"===n){let n=e[this.index+1];"\n"===n?this.index+=2:"\r"===n&&"\n"===e[this.index+2]?this.index+=3:'"'!==n&&(t||"$"!==n&&"`"!==n&&"\\"!==n)?(this.appendText("\\","double"),this.index++):(this.appendText(n,"double"),this.index+=2)}else"$"===n?this.dollar("double"):"`"===n?this.fail({code:"command-substitution",syntax:"`"}):(this.appendText(n,"double"),this.index++)}this.fail({code:"unterminated-quote",quote:'"'})}ansiQuoted(){let{input:e}=this;this.index+=2;let t="";for(;this.index<e.length;){let n=e[this.index];if("'"===n){this.appendText(t,"ansi"),this.index++;return}if("\\"!==n){t+=n,this.index++;continue}let r=e[this.index+1];if("x"===r&&/^[0-9A-Fa-f]{1,2}/.test(e.slice(this.index+2))){let n=/^[0-9A-Fa-f]{1,2}/.exec(e.slice(this.index+2))[0];t+=String.fromCharCode(parseInt(n,16)),this.index+=2+n.length}else if(("u"===r||"U"===r)&&/^[0-9A-Fa-f]{1,8}/.test(e.slice(this.index+2))){let n=RegExp(`^[0-9A-Fa-f]{1,${"u"===r?4:8}}`).exec(e.slice(this.index+2))[0],i=parseInt(n,16);t+=i>1114111||i>=55296&&i<=57343?e.slice(this.index,this.index+2+n.length):String.fromCodePoint(i),this.index+=2+n.length}else void 0!==r&&r in fQ?(t+=fQ[r],this.index+=2):(t+="\\",this.index++)}this.fail({code:"unterminated-quote",quote:"'"})}dollar(e){let{input:t}=this,n=t[this.index+1];if("("===n&&this.fail({code:"command-substitution",syntax:"("===t[this.index+2]?"$((":"$("}),"none"===e&&"'"===n){this.startWord(),this.ansiQuoted();return}if("none"===e&&'"'===n){this.startWord(),this.index++,this.doubleQuoted();return}if("{"===n)return void this.braced(e);if(void 0!==n&&fV.test(n)){let n=this.index+1;for(;n<t.length&&fZ.test(t[n]);)n++;let r=t.slice(this.index+1,n);this.startWord().push({type:"variable",name:r,raw:`$${r}`,quote:e}),this.index=n;return}void 0!==n&&fX.test(n)&&this.fail({code:"shell-parameter",parameter:`$${n}`}),this.appendText("$",e),this.index++}braced(e){let{input:t}=this,n=t.indexOf("}",this.index+2);n<0&&this.fail({code:"unsupported-expansion",expansion:t.slice(this.index)});let r=t.slice(this.index,n+1),i=r.slice(2,-1);if(/^[0-9@*#?$!-]$/.test(i)&&this.fail({code:"shell-parameter",parameter:r}),fJ.test(i)){this.startWord().push({type:"variable",name:i,raw:r,quote:e}),this.index=n+1;return}let s=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(i);if(s&&!/[$`{}\\'"]/.test(s[2])){this.startWord().push({type:"variable",name:s[1],raw:r,quote:e,fallback:s[2]}),this.index=n+1;return}this.fail({code:"unsupported-expansion",expansion:r})}}class f4 extends Error{constructor(e){super(e.code),this.detail=e}}function f8(e){return new f2(e).run()}function f3(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function f5(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let f6=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function f9(e){if(f6.some(t=>t in e))return!0;let t=e.oauth;return f5(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function f7(e){if(!f5(e))return!1;let{command:t,url:n,serverUrl:r,httpUrl:i}=e;return"string"==typeof t&&""!==t||Array.isArray(t)&&"string"==typeof t[0]||f5(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function me(e){switch(e.toLowerCase().replace(/[-_]/g,"")){case"stdio":case"local":return"stdio";case"http":case"streamablehttp":case"remote":return"http";case"sse":return"sse";case"ws":case"wss":case"websocket":return"ws";default:return"unknown"}}function mt(e){try{let t=new URL(e);if(!/\/sse\/?$/.test(t.pathname))return;return t.pathname=t.pathname.replace(/\/sse\/?$/,"/mcp"),t.toString()}catch{return}}function mn(e,t){let n=t?mt(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function mr(e){return e?{server:e}:{}}function mi(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function ms(e,t,n){let r;if(!f5(t))return{note:{code:"no-command-or-url",params:mr(e)}};let i=new Set,s=e=>(i.add(e),t[e]),l=n.rawPi,o=function(e,t){switch(e.flavor){case"zed":return h6;case"opencode":return fe;case"vscode":return h9;default:return f9(t)?h7:h9}}(n,t),a=s("name"),d=e??("string"==typeof a?a:void 0),c=new fx(n.source,l),u=(e,t)=>{if(l)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),fi(e,o,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...ma(p)]));let h=s("type"),f=s("command"),m=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:mr(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?me(h):"unknown"))return{note:{code:"unsupported-transport",params:{...mr(d),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||f5(f),x=void 0!==m;if("sse"===r)return{note:mn(d,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...mr(d),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:mr(d)}};if(x){if(void 0!==mt(m))return{note:mn(d,m)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:mr(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...mr(d),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:mr(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let l,o=r("args"),a=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===a&&(a=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...mr(e.name),problem:"args"}};l=n[0],o=[...n.slice(1),...Array.isArray(o)?o:[]]}else if(f5(n))for(let t of(l="string"==typeof n.path?n.path:void 0,void 0===o&&(o=n.args),void 0===a&&(a=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(l=n);if(!l)return{code:"no-command-or-url",params:mr(e.name)};let d=Array.isArray(o)?[...o]:[];if(void 0!==o&&!Array.isArray(o))return{code:"invalid-config",params:{...mr(e.name),problem:"args"}};if(0===d.length&&/\s/.test(l.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(l.trim())){let t=f8(l.trim()),n=t.ok?t.words.map(f3):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:l}),l=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(l,!1),d.entries())){let r=mi(n);if(void 0===r)return{code:"invalid-config",params:{...mr(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!f5(a))return{code:"invalid-config",params:{...mr(e.name),problem:"env"}};for(let[t,n]of Object.entries(a)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=mi(n);if(void 0===r){e.note("dropped-key",{key:`env.${t}`});continue}if("string"!=typeof n&&e.note("env-value-stringified",{name:t}),""===r&&hL(t)){e.env.push([t,[{kind:"prompt",id:`env.${t}`,reason:"empty",label:t,from:"",secret:!0}]]);continue}e.env.push([t,i(r,!0)])}}let c=r("cwd");for(let n of("string"==typeof c&&""!==c?e.cwd=i(c,!1):void 0!==c&&""!==c&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,f,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),l=i(n,!1),o=f5(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===l.length&&"text"in l[0]?fk(e,n,o):e.url=l,f5(s))for(let[t,n]of Object.entries(s)){let r=mi(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):hL(t)?e.headers.push([t,[{kind:"prompt",id:`headers.${t}`,reason:"empty",label:t,from:"",secret:!0,optional:!0}]]):e.headers.push([t,[]]);continue}e.headers.push([t,i(r,!0)])}else void 0!==s&&e.note("dropped-key",{key:"headers"});let a=r("oauth"),d=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):f5(a)?ml(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),f5(d))for(let t of(ml(e,{...void 0!==d.CLIENT_ID?{clientId:d.CLIENT_ID}:{},...void 0!==d.CLIENT_SECRET?{clientSecret:d.CLIENT_SECRET}:{},...void 0!==d.scopes?{scopes:d.scopes}:{}},i,"auth."),Object.keys(d)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==d&&e.note("dropped-key",{key:"auth"});for(let n of["command","args","env","environment","cwd"])n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,m,s,u);let v=s("timeout");if(void 0!==v)if(l)"number"==typeof v&&v>0?c.timeout=v:c.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(v)});else if(f9(t))fz(c,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?fP(c,v)&&fW(c,Math.ceil(v),void 0):!function(e,t){if(!fP(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?fW(e,Math.ceil(t/1e3),t):fW(e,Math.ceil(t),void 0)}(c,v);let b=s("enabled"),y=s("disabled");!1===b||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let w=s("exposure");if(void 0!==w){let e=fB(w);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(w)})}let j=s("toolExposure");if(void 0!==j){let e=f5(j)?Object.entries(j).map(e=>{let[t,n]=e;return[t,fB(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?c.toolExposure=Object.fromEntries(e):c.note("invalid-exposure-dropped",{value:"toolExposure"})}if(l||void 0===w&&void 0===j||c.note("looks-like-pi-config"),l){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(mo(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function ml(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"oauth.";for(let[i,s]of Object.entries(t))switch(i){case"clientId":"string"==typeof s&&""!==s&&(e.oauth.clientId=n(s,!1));break;case"clientSecret":"string"==typeof s&&""!==s&&(e.oauth.clientSecret=n(s,!0));break;case"callbackPort":"number"==typeof s&&Number.isInteger(s)&&s>=1&&s<=65535?e.oauth.callbackPort=s:e.note("callback-port-dropped",{value:String(s)});break;case"clientName":"string"==typeof s&&s.trim()?e.oauth.clientName=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"clientRegistration":"dcr"===s||"cimd"===s?e.oauth.clientRegistration=s:e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"authServerMetadataUrl":"string"==typeof s&&""!==s?e.oauth.authServerMetadataUrl=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"callbackUrl":case"redirectUri":"string"==typeof s&&f_(s)?e.oauth.callbackUrl=n(s,!1):e.note("callback-url-dropped",{value:String(s)});break;case"scope":case"scopes":{let t=Array.isArray(s)?s.filter(e=>"string"==typeof e).join(" "):"string"==typeof s?s:"";t&&(e.oauth.scope=n(t,!1));break}case"enabled":!1===s&&e.note("oauth-disable-unsupported");break;default:e.note("oauth-option-dropped",{key:`${r}${i}`})}let{callbackPort:i,callbackUrl:s}=e.oauth;if(void 0!==i&&s){let t=s.map(e=>"text"in e?e.text:"").join(""),n="";try{n=new URL(t).port}catch{}n&&Number(n)!==i&&(e.note("callback-url-dropped",{value:t}),e.oauth.callbackUrl=void 0)}}function mo(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),s=r(n);if(0===i.length&&0===s.length)return;let l={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))l[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)l[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=l}function ma(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)f5(n)&&"string"==typeof n.id&&t.set(n.id,{id:n.id,..."string"==typeof n.type?{type:n.type}:{},..."string"==typeof n.description?{description:n.description}:{},...!0===n.password?{password:!0}:{},..."string"==typeof n.default?{default:n.default}:{},...Array.isArray(n.options)?{options:n.options.map(e=>f5(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function md(e,t,n,r){let i=[],s=0;for(let l of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){l.index>s&&i.push({kind:"text",text:e.slice(s,l.index)});let o=f5(t)&&f5(t[l[1]])?t[l[1]]:{};i.push(mc(`${n}${l[1]}`,l[1],l[0],o,r)),s=l.index+l[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function mc(e,t,n,r,i){let s=Array.isArray(r.choices)?r.choices.filter(e=>"string"==typeof e):[];return{kind:"prompt",id:e,reason:i,label:t,from:n,secret:!0===r.isSecret,..."string"==typeof r.description?{description:r.description}:{},..."string"==typeof r.default?{defaultValue:r.default}:{},...!0===r.isRequired?{}:{optional:"registry-header"===i},...s.length>0?{options:s}:{}}}function mu(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...fi(i,t,n)),i="")};for(let t of e)"variable"===t.type?(s(),r.push({kind:"env",name:t.name,from:t.raw,shell:!0,...void 0!==t.fallback?{fallback:t.fallback}:{}})):i+=t.value;return s(),r}function mp(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if("variable"===i.type){n+=i.raw;continue}let s=i.value.indexOf(t);if(s<0){n+=i.value;continue}n+=i.value.slice(0,s);let l=i.value.slice(s+t.length);return[n,[...l?[{...i,value:l}]:[],...e.slice(r+1)]]}}let mh=/^https?:\/\//i,mf=/^wss?:\/\//i,mm={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},mg=new Set(["pi","claude","codex","gemini"]),mx=new Set(["install","remove","uninstall","update","list","config"]);function mv(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let mb={local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},my=new Map([["-l","--local"]]),mw=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],mj=["env","cwd"];function mk(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let l=t[s],o=l.text;if("--"===o){i.afterDashDash.push(...t.slice(s+1));break}if(void 0!==r.stopAfter&&i.positional.length>=r.stopAfter){i.positional.push(...t.slice(s));break}if(!o.startsWith("-")||"-"===o){i.positional.push(l);continue}let a=o.startsWith("--")?o.indexOf("="):-1,d=a>0?o.slice(0,a):o,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(l),i.seen.set(`as-arg:${d}`,d);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:d}}}}if(i.seen.set(c.name,d),"flag"===c.kind){i.values.set(c.name,!0);continue}let u=a>0?mS(l,a+1):void 0;if("value"===c.kind||"list"===c.kind){let n=u??t[++s];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};"value"===c.kind?i.values.set(c.name,n):i.lists.set(c.name,[...i.lists.get(c.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;s+1<t.length&&r.variadic(c.name,t[s+1]);)p.push(t[++s]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};i.lists.set(c.name,[...i.lists.get(c.name)??[],...p])}return i}function mS(e,t){let n=0,r=[];for(let i of e.parts){let e="text"===i.type?i.value.length:i.raw.length;n>=t?r.push(i):n+e>t&&"text"===i.type&&r.push({...i,value:i.value.slice(t-n)}),n+=e}return{parts:r,text:e.text.slice(t)}}let mC=/^[A-Za-z_][A-Za-z0-9_]*=/,mN=/^[^\s:]+:/;function m$(e,t,n,r){for(let i of t??[]){let t=mp(i.parts,"=");if(!t||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t[0]))return{code:"cli-invalid-pair",params:{cli:r,option:"--env",value:i.text}};e.env.push([t[0],mu(t[1],n,!0)])}}function mE(e,t,n,r){for(let i of t??[]){let t=mp(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let l=function(e){let t=e.map(e=>({...e})),n=t[0];n?.type==="text"&&(n.value=n.value.replace(/^\s+/,""));let r=t[t.length-1];return r?.type==="text"&&(r.value=r.value.replace(/\s+$/,"")),t}(t[1]);if("authorization"===s.toLowerCase()&&l.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,mu(l,n,!0)])}}function mI(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function mM(e,t,n,r,i){let s,[l,o,...a]=r;if(!l||!o)return{code:"cli-usage",params:{cli:t}};e.name=l.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=mh.test(o.text)?"http":mf.test(o.text)?"ws":"stdio")&&void 0!==mt(o.text))return mn(l.text,o.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?mn(l.text,o.text):"ws"===s?{code:"websocket-transport",params:{server:l.text,url:o.text}}:"http"===s?(e.transport="http",e.url=mu(o.parts,i,!1),a.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:a.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:l.text,type:s}}:(e.transport="stdio",e.command=mu(o.parts,i,!1),e.args=a.map(e=>mu(e.parts,i,!1)),"stdio")}let mT={"-t":{name:"transport",kind:"value"},"--transport":{name:"transport",kind:"value"},"-e":{name:"env",kind:"variadic"},"--env":{name:"env",kind:"variadic"},"-H":{name:"header",kind:"variadic"},"--header":{name:"header",kind:"variadic"},"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-id":{name:"client-id",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"},"--callback-port":{name:"callback-port",kind:"value"},"--no-browser":{name:"no-browser",kind:"flag"}};function mR(e,t){return"env"===e?mC.test(t.text):mN.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function mA(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let mL={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function mz(e){let t,n=f3(e)??e.text;try{t=h3(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return f5(t)?{value:t}:{error:{code:"no-servers-found"}}}let mP={"--env":{name:"env",kind:"list"},"--url":{name:"url",kind:"value"},"--bearer-token-env-var":{name:"bearer-token-env-var",kind:"value"},"--oauth-client-id":{name:"oauth-client-id",kind:"value"},"--oauth-resource":{name:"oauth-resource",kind:"value"},"-c":{name:"config",kind:"value"},"--config":{name:"config",kind:"value"},"--enable":{name:"enable",kind:"value"},"--disable":{name:"disable",kind:"value"}},mW={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"-t":{name:"transport",kind:"value"},"--transport":{name:"transport",kind:"value"},"--type":{name:"transport",kind:"value"},"-e":{name:"env",kind:"list"},"--env":{name:"env",kind:"list"},"-H":{name:"header",kind:"list"},"--header":{name:"header",kind:"list"},"--timeout":{name:"timeout",kind:"value"},"--trust":{name:"trust",kind:"flag"},"--description":{name:"description",kind:"value"},"--include-tools":{name:"include-tools",kind:"value"},"--includeTools":{name:"include-tools",kind:"value"},"--exclude-tools":{name:"exclude-tools",kind:"value"},"--excludeTools":{name:"exclude-tools",kind:"value"}};function mO(e){let t=new Map;for(let n of e.replace(/^\?/,"").split("&")){if(!n)continue;let e=n.indexOf("="),r=e<0?n:n.slice(0,e),i=e<0?"":n.slice(e+1);t.set(mF(r),mF(i))}return t}function mF(e){try{return decodeURIComponent(e)}catch{return e}}function mD(e){let t=e.trim();for(let e=0;e<4;e++)try{return h3(t)}catch{let e=mF(t);if(e===t)break;t=e.trim()}}function mB(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function mH(e){let t=e.get("config");if(!t)return mB("config");let n=t.trim().startsWith("{")?t:function(e){let t=e.trim().replace(/ /g,"+").replace(/-/g,"+").replace(/_/g,"/").replace(/=+$/,"");if(/^[A-Za-z0-9+/]+$/.test(t)&&t.length%4!=1){t+="=".repeat((4-t.length%4)%4);try{let e=atob(t),n=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}}(t),r=void 0===n?void 0:mD(n);return f5(r)?{entries:[ms(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:mB("config")}function m_(e,t,n,r){return f5(e)?{entries:[ms(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:ma(r)})],notes:[]}:mB("config")}function mU(e){return{error:{code:"by-name-link",params:{name:e}}}}function mq(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function mK(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&amp;/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[mZ(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return mB("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return mH(mO(t.search));return mB("cursor");case"vscode":case"vscode-insiders":case"code-oss":{let e=r.slice(r.indexOf(":")+1).replace(/^\/+/,""),t=/^mcp\/by-name\/([^?#]+)/.exec(e);if(t)return mU(mF(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return mU(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return m_(mD(mq(r)),"vscode-install-link");return mB(i)}case"vsweb+mcp":return m_(mD(mq(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return m_(mD(mq(r)),"copilot-app-install-link");return mB(i);case"ws":case"wss":return{entries:[{note:{code:"websocket-transport",params:{url:r}}}],notes:[]};case"http":case"https":return function(e,t,n){let r=e.hostname.toLowerCase().replace(/^www\./,""),i=e.pathname;if(("cursor.com"===r||"lmstudio.ai"===r)&&/^\/(?:[a-z]{2}(?:-[A-Za-z]{2,4})?\/)?install-mcp\/?$/.test(i))return mH(mO(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=mO(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return mK(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?m_(mD(e),"vscode-install-link",t.get("name")||void 0,mD(t.get("inputs")??"[]")):mB("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return m_(mD(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=mO(e.search).get("open");return t?mK(t,n+1):mB("open")}if(/\.(?:svg|png)$/i.test(i)&&("cursor.com"===r||"img.shields.io"===r||r.endsWith("githubusercontent.com")))return{error:{code:"badge-image"}};if("github.com"===r){let e=i.split("/").filter(Boolean);return"mcp"===e[0]&&e.length>=2?{error:{code:"github-mcp-page",params:{name:e.slice(1).join("/")}}}:"mcp"!==e[0]&&e.length>=2?{error:{code:"github-repo-link",params:{repository:`${e[0]}/${e[1]}`}}}:{error:{code:"github-page"}}}return{entries:[mZ(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let mV=new Set(["localhost","127.0.0.1","[::1]"]);function mZ(e,t){let n=fT(t)||void 0;if(void 0!==mt(t))return{note:mn(n,t)};let r=new fx("url",!1);return r.transport="http",fk(r,t,!1),e?.protocol!=="http:"||mV.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let mJ=/[\u200B-\u200D\u2060\uFEFF]/g,mY=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,mG={"unterminated-quote":"shell-unterminated-quote","shell-operator":"shell-operator","command-substitution":"shell-command-substitution","multiple-commands":"shell-multiple-commands","shell-parameter":"shell-parameter","unsupported-expansion":"shell-expansion"};function mX(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>fp(e.path))))}function mQ(e){var t;let n,r,i,s,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(n=e.replace(mJ,"").replace(/\u00A0/g," ").trim(),(r=/```[^\n]*\n([\s\S]*?)(?:```|$)/.exec(n))?n=r[1].trim():/^`[^`\n]+`$/.test(n)&&(n=n.slice(1,-1).trim()),(i=n.startsWith("[")?/\]\(([^()\s]+)\)\s*$/.exec(n):null)&&(n=i[1]),/^<\S+>$/.test(n)&&(n=n.slice(1,-1)),n);if(!o)return{ok:!1,notes:[{code:"empty-input"}]};if(o.startsWith("{")||o.startsWith("[")||/^"[^"\n]+"\s*:/.test(o))s=function(e,t){let n;try{n=h3(e)}catch(t){try{n=h3(`{${e.replace(/,\s*$/,"")}}`)}catch{return{error:{code:"invalid-json",params:{detail:t instanceof Error?t.message:String(t)}}}}}return function(e,t){let n=[],r=(e,t)=>Object.entries(e).map(e=>{let[n,r]=e;return ms(n,r,t)});if(Array.isArray(e)){let r=e.filter(f7);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>ms(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!f5(e))return{error:{code:"no-servers-found"}};let i=f5(e.server)&&(Array.isArray(e.server.remotes)||Array.isArray(e.server.packages))?e.server:Array.isArray(e.remotes)||Array.isArray(e.packages)?e:void 0;if(i)return{entries:function(e){let t="string"==typeof e.name?e.name:"",n=t?f$(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(f5):[],i=r.filter(e=>"string"==typeof e.type&&"http"===me(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:mn(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:mr(n)}}]}return i.map(e=>{let r=new fx("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=md(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(f5):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,md(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[mc(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(f5(e.mcpServers))return"boolean"!=typeof e.autoEnableCodemode||t||n.push({code:"looks-like-pi-config"}),{entries:r(e.mcpServers,{source:"mcp-servers-json",flavor:"mcp-servers",rawPi:t}),notes:n};if(f5(e.servers)){let t=ma(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(f5(e.mcp)){let t=e.mcp;if(f5(t.servers)){let e=ma(t.inputs);return{entries:r(t.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:e}),notes:n}}return{entries:r(t,{source:"opencode-json",flavor:"opencode",rawPi:!1}),notes:n}}if(f5(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return f5(r)&&("extension"===r.source||!f7(r))?{note:{code:"zed-extension-server",params:{server:n}}}:ms(n,f5(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(f7(e))return{entries:[ms(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(f5)&&s.some(f7)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(o,!0===l.rawPi);else if(mY.test(o)){if(!("error"in(s=mK(`http://${o}`))))for(let e of s.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${o}`})}else{let e;s=!/\s/.test(o)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(o)?mK(o):(e=f8(o.replace(/^(?:\$|%|>|❯|PS [^\n>]*>)[ \t]+/,"").replace(/[\u201C\u201D\u201E\u201F\u2033]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032]/g,"'").replace(/(^|\s)[\u2013\u2014](?=\S)/g,"$1--").replace(/(^|\s)[\u2013\u2014](?=\s|$)/g,"$1--"))).ok?0===e.words.length?{error:{code:"empty-input"}}:function(e){var t;let n=0,r=(t=e[0],(t?.text.split(/[\\/]/).pop()??"").replace(/\.(?:cmd|exe|ps1)$/i,"").toLowerCase());if(["npx","bunx","pnpx"].includes(r)){let t=1;for(;e[t]?.text.startsWith("-");)t++;let i=e[t]?.text.replace(/^(@?[^@]+)@.*$/,"$1");i&&mm[i]&&e[t+1]?.text==="mcp"&&(n=t,r=mm[i])}let i=e.slice(n+1);if(i[0]?.text==="mcp"&&i.length>=2){let e=i[1].text,t=i.slice(2);if("pi"===r&&"add"===e)return mv(function(e,t){if(t.some(e=>"--help"===e.text||"-h"===e.text))return{error:{code:"pi-help"}};let n=[],r=new Map,i=new Map;for(let t=0;t<e.length;t++){let s=my.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let l=s.slice(2),o=mb[l];if(!o)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===o){r.set(l,!0);continue}let a=e[++t];if(void 0===a)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===o?i.set(l,[...i.get(l)??[],a]):r.set(l,a)}let[s,...l]=n,o=r.get("url");if(!s||""===s.text||void 0===o==(0===l.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let a=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===o?mw:mj).find(e=>r.has(e)||i.has(e));if(d)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${d}`,transport:void 0===o?"stdio":"http"}}};let c=new fx("pi-mcp-add",!0);c.name=s.text,c.scopeHint=r.has("local")?"project":"global";let u=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"=",n=[];for(let r of i.get(e)??[]){let i=mp(r.parts,t);if(!i||""===i[0])return{error:{code:"cli-invalid-pair",params:{cli:"pi",option:`--${e}`,value:r.text}}};let s=n.findIndex(e=>{let[t]=e;return t===i[0]});s>=0?n[s]=i:n.push(i)}return n},p={};if(void 0!==o&&!0!==o){c.transport="http",c.url=mu(o.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,mu(n,"pi",!0)]);let t=a("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer \${${t.text}}`}]],n=c.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?c.headers[n]=e:c.headers.push(e)}let n=a("oauth-client-id"),r=a("oauth-client-secret"),i=a("oauth-callback-port"),s=a("oauth-client-name");n&&(c.oauth.clientId=mu(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=mu(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=mu(s.parts,"pi",!1)),p.url=o.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":o.text,(i||s)&&(p.oauth={...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{}})}else{c.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)c.env.push([t,mu(n,"pi",!0)]);let[t,...n]=l;c.command=mu(t.parts,"pi",!1),c.args=n.map(e=>mu(e.parts,"pi",!1));let r=a("cwd");r&&(c.cwd=mu(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=fB(h.text)??h.text);let f=a("description");void 0!==f&&(p.description=f.text,c.description=f.text);let m=fK("server",p);return m?{note:{code:"invalid-config",params:{server:s.text,...m}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return mv(function(e){let t=mk("claude",e,mT,{asArgAfter:2,variadic:mR});if("error"in t)return{error:t.error};let n=new fx("claude-mcp-add",!1),r=mM(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],h9);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};for(let[e,r]of t.seen)e.startsWith("as-arg:")&&n.note("cli-option-as-arg",{cli:"claude",option:r});if(n.scopeHint=mI(t.values.get("scope")),"http"===r){var i,s;let e;t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"claude",option:"--env",transport:"http"});let r=mE(n,t.lists.get("header"),h9,"claude");if(r)return{error:r};let l=t.values.get("client-id");l&&!0!==l&&(n.oauth.clientId=mu(l.parts,h9,!1)),t.values.has("client-secret")&&mA(n);let o=t.values.get("callback-port");o&&!0!==o&&(i=n,Number.isInteger(e=Number(s=o.text))&&e>=1&&e<=65535?i.oauth.callbackPort=e:i.note("callback-port-dropped",{value:s}))}else{for(let e of["header","client-id","client-secret","callback-port"])(t.lists.has(e)||t.values.has(e))&&n.note("cli-option-wrong-transport",{cli:"claude",option:t.seen.get(e)??`--${e}`,transport:"stdio"});let e=m$(n,t.lists.get("env"),h9,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return mv(function(e){let t=mk("claude",e,mL,{asArgAfter:1/0});if("error"in t)return{error:t.error};let[n,r,...i]=[...t.positional,...t.afterDashDash];if(!n||!r||i.length>0)return{error:{code:"cli-usage",params:{cli:"claude"}}};let s=mz(r);if("error"in s)return s;let l=ms(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in l||(l.draft.scopeHint=mI(t.values.get("scope")),t.values.has("client-secret")&&"http"===l.draft.transport&&!l.draft.oauth.clientSecret&&mA(l.draft)),l}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return mv(function(e){let t=mk("codex",e,mP,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,l=n.length>0?n:s,o=t.values.get("url");if(!i||void 0===o==(0===l.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let a=new fx("codex-mcp-add",!1);for(let e of(a.name=i.text,["config","enable","disable"]))t.values.has(e)&&a.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&a.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==o&&!0!==o){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==mt(o.text))return{note:mn(i.text,o.text)};a.transport="http",a.url=mu(o.parts,h6,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&a.headers.push(["Authorization",[{kind:"text",text:"Bearer "},{kind:"env",name:e.text,from:`\${${e.text}}`}]]);let n=t.values.get("oauth-client-id");n&&!0!==n&&(a.oauth.clientId=mu(n.parts,h6,!1))}else{for(let e of["bearer-token-env-var","oauth-client-id","oauth-resource"])if(t.values.has(e))return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:`--${e}`,transport:"stdio"}}};a.transport="stdio";let e=m$(a,r,h6,"codex");if(e)return{error:e};a.command=mu(l[0].parts,h6,!1),a.args=l.slice(1).map(e=>mu(e.parts,h6,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return mv(function(e){let t=mk("gemini",e,mW,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new fx("gemini-mcp-add",!1),r=mM(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],h7);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=mI(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=mE(n,t.lists.get("header"),h7,"gemini");if(e)return{error:e}}else{t.lists.has("header")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--header",transport:"stdio"});let e=m$(n,t.lists.get("env"),h7,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&fz(n,Number(i.text)),["trust","description"]))t.values.has(e)&&n.note("cli-option-ignored",{cli:"gemini",option:`--${e}`});let s=e=>{let n=t.values.get(e);return n&&!0!==n?n.text.split(",").map(e=>e.trim()).filter(Boolean):void 0};return mo(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(mg.has(r)&&!e.startsWith("-")&&("claude"!==r||"serve"!==e))return{error:{code:"cli-not-a-server",params:{cli:r,command:`mcp ${e}`}}}}return"pi"===r&&i[0]&&mx.has(i[0].text)?{error:{code:"cli-not-a-server",params:{cli:r,command:i[0].text}}}:["code","code-insiders","codium","cursor"].includes(r)&&e.some(e=>"--add-mcp"===e.text||e.text.startsWith("--add-mcp="))?function(e){let t=[];for(let n=0;n<e.length;n++){let r,i=e[n].text;if("--add-mcp"===i)r=e[++n];else{if(!i.startsWith("--add-mcp="))continue;r=mS(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=mz(r);if("error"in s)return s;t.push(ms(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):mv(function(e){let t=new fx("command-line",!1);t.transport="stdio";let n=0,r=()=>{for(;n<e.length;n++){let r=function(e){let[t,...n]=e.parts;if(t?.type!=="text"||"none"!==t.quote)return;let r=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(t.value);if(!r)return;let i=t.value.slice(r[0].length);return{name:r[1],value:[...i?[{...t,value:i}]:[],...n]}}(e[n]);if(!r)break;t.env.push([r.name,mu(r.value,h6,!0)])}};if(r(),e[n]?.text==="env"){if(n++,e[n]?.text.startsWith("-"))return{error:{code:"cli-unknown-option",params:{cli:"env",option:e[n].text}}};r()}let i=e[n];if(!i)return{error:{code:"no-command-or-url"}};t.command=mu(i.parts,h6,!1),t.args=e.slice(n+1).map(e=>mu(e.parts,h6,!1));let s=e.slice(n+1).map(e=>e.text),l=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>mh.test(e)):void 0;return l&&t.note("mcp-remote-bridge",{url:l}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:mG[t],params:n}:{code:mG[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let a=[...s.notes],d=[],c=[...l.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){a.push(e.note);continue}let n=function(e){let t,n=new fw(e);if("stdio"===e.transport&&e.command&&""!==fv(e.command)){let r=n.encode(["command"],e.command),i=e.args.map((e,t)=>n.encode(["args",t],e)),s={};for(let[t,r]of e.env)s[t]=n.encode(["env",t],r);t={command:r,...i.length>0?{args:i}:{},...Object.keys(s).length>0?{env:s}:{},...e.cwd?{cwd:n.encode(["cwd"],e.cwd)}:{}}}else{if("http"!==e.transport||!e.url||""===fv(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:l,clientSecret:o,callbackPort:a,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;l&&(s.clientId=n.encode(["oauth","clientId"],l)),o&&(s.clientSecret=n.encode(["oauth","clientSecret"],o)),void 0!==a&&(s.callbackPort=a),d&&(s.clientName=n.encode(["oauth","clientName"],d)),c&&(s.clientRegistration=c),u&&(s.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(s.scope=n.encode(["oauth","scope"],p)),h&&(s.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),t={url:r,...Object.keys(i).length>0?{headers:i}:{},...Object.keys(s).length>0?{oauth:s}:{}}}return void 0!==e.exposure&&(t.exposure=e.exposure),void 0!==e.toolExposure&&(t.toolExposure=e.toolExposure),!1===e.enabled&&(t.enabled=!1),void 0!==e.timeout&&(t.timeout=e.timeout),void 0!==e.description&&(t.description=e.description),{server:{name:e.name??"",...void 0!==e.originalName?{originalName:e.originalName}:{},config:t,fields:[...n.fields.values()],notes:e.notes,source:e.source,rawPi:e.rawPi,...e.scopeHint?{scopeHint:e.scopeHint}:{}}}}(e.draft);if("note"in n){a.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return fT(e.url);let t=e.args??[],n=t.some(e=>/^mcp-remote(?:@|$)/.test(e))?t.find(e=>/^https?:\/\//i.test(e)):void 0;return n&&fT(n)||function(e,t){let n=e.split(/[\\/]/).pop()?.replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase()??"";switch(n){case"npx":case"bunx":case"pnpx":{let e=fA(t,new Set(["-p","--package","-c","--call"]));return e?f$(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?fA(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?f$(n):""}case"uvx":case"pipx":{let e=fA("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?f$(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?fA(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?fL(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?fA(t.slice(e+1),fR):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return fI(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return f$(t[e+1].replace(/_/g,"-"));let n=fA(t,new Set(["-X","-W"]));return n?fL(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=fA("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?fL(e):""}default:return fI(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let l=(t=i,fS.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";l!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:l}}));let o=fC(l,s?[...c,...u]:u);o!==l&&(r.notes.push({code:"name-deduplicated",params:{original:l,name:o}}),l=o),!s&&c.includes(l)&&r.notes.push({code:"name-taken",params:{name:l,suggestedName:fC(l,[...c,...u])}}),r.name=l;let p=fK(l,function(e){let t=mX(e),n=JSON.parse(JSON.stringify(e.config));t.has(fp(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(fp(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:l,...p}});continue}!function(e){let t=mX(e);for(let n of m6(e.config))t.has(fp(n))||e.notes.push({code:"literal-secret",params:{field:fh(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=fo(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=fo(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(l),d.push(r)}return 0===d.length?{ok:!1,notes:a.length>0?a:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:a}}let m0=/^[A-Za-z_][A-Za-z0-9_]*$/;function m1(e,t,n){let[r,i]=t;if("command"===r||"url"===r||"cwd"===r){void 0!==n&&(e[r]=n);return}if("args"===r){e.args[i]=n??"";return}let s={...e[r]??{}};void 0===n?delete s[i]:s[i]=n,0===Object.keys(s).length?delete e[r]:e[r]=s}function m2(e){let t=mX(e);return m6(e.config).filter(e=>ff(e)&&!t.has(fp(e)))}function m4(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let m8=/^(?:bearer|basic|token)\s+/i;function m3(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],l=new Map(m2(e).map(e=>[fh(e),e])),o=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=l.get(e);r?m0.test(n)?o.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:m4(t)}}):s.push({code:"field-reference-invalid",params:{field:e,problem:"target"}})}for(let n of e.fields){let e=t[n.id];if("object"==typeof e&&null!==e){let t=e.reference,r="string"==typeof t?t.trim():"";m0.test(r)?"select"!==n.kind&&n.targets.every(e=>ff(e.path)&&void 0===e.encoding)?i.set(n.id,{reference:r}):s.push({code:"field-reference-invalid",params:{field:n.id,problem:"target"}}):s.push({code:"field-reference-invalid",params:{field:n.id,problem:m4(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):s.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?s.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(s.length>0)return{ok:!1,notes:s};let a=new Set,d=new Set;for(let t of e.fields)for(let e of t.targets){let n=i.get(t.id);"password"===t.kind&&void 0!==n&&"text"in n&&a.add(fh(e.path));let s=fp(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){m1(r,e.path,void 0);continue}let l="";for(let t of e.parts){var c,u,p,h;l+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===l,h=e.encoding,"reference"in c?`\${${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):ff(u)?fs(c.text,{atStart:p}):c.text)}m1(r,e.path,l)}for(let[e,t]of o){let n=function(e,t){let[n,r]=t,i=e[n];return void 0===r||"object"!=typeof i||null===i?void 0===r?i:void 0:i[r]}(r,e),i="headers"===e[0]&&"string"==typeof n?n.match(m8)?.[0]??"":"";m1(r,e,`${i}\${${t}}`)}for(let e of m6(r))a.add(fh(e));return{ok:!0,config:r,secretPaths:[...a]}}let m5=["command","args","env","cwd","url","headers","oauth"];function m6(e){let t=[];for(let n of function(e){if(!h4(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(h4(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&h8(i)&&""!==i&&(hL(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||hX(i,h_).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=h4(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&h8(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&hJ(e.url,hK).masked&&t.push({kind:"url"}),"string"==typeof e.command&&hX(e.command,hK).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&h2(e.args.filter(e=>"string"==typeof e)).masked&&t.push({kind:"args"}),t}(e))switch(n.kind){case"env":t.push(["env",n.name]);break;case"header":t.push(["headers",n.name]);break;case"oauth-client-secret":t.push(["oauth","clientSecret"]);break;case"url":t.push(["url"]);break;case"command":t.push(["command"]);break;case"args":{let n="args"in e&&Array.isArray(e.args)?e.args.map(e=>"string"==typeof e?e:""):[];h2(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>m5.indexOf(e[0])-m5.indexOf(t[0]))}let m9="PI_WEB_PASSWORD";function m7(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ge(e){return m7(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function gt(e){if(!m7(e))return[];if(!("url"in e))return ge(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=ge(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=m7(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let gn={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function gr(e,t,n){let r=mQ(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,l="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,l])}function gi(e,t){let n={...e,...t},r=gr(e.text,e.rawPi,e.server);if(void 0!==r&&r===gr(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function gs(e){return h5[e.code]??"warning"}function gl(e,t){let n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=e.params??{},s={};for(let[e,t]of Object.entries(i))s[e]="string"==typeof t?py(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=py(e.label))}"invalid-config"===e.code&&(s.problem=t("tool-exposure"===(n=String(i.problem??"no-command-or-url"))&&void 0!==i.tool?"mcp.importProblem.tool-exposure.tool":"args"===n&&void 0!==i.index?"mcp.importProblem.args.index":`mcp.importProblem.${n}`,s)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(s.transport=t(`mcp.transport.${i.transport}`));let l=t(function(e){let t=e.params??{};switch(e.code){case"field-reference-invalid":return`mcp.importNote.field-reference-invalid.${"target"===t.problem||"missing"===t.problem?t.problem:"name"}`;case"sse-transport":return void 0===t.suggestedUrl?"mcp.importNote.sse-transport":"mcp.importNote.sse-transport.suggested";case"timeout-unit-guessed":return`mcp.importNote.timeout-unit-guessed.${"milliseconds"===t.unit?"milliseconds":"seconds"}`;case"tool-filter-imported":return`mcp.importNote.tool-filter-imported.${"exclude"===t.mode?"exclude":"include"}`;default:return`mcp.importNote.${e.code}`}}(e),s);return"string"==typeof s.server?t("mcp.importNote.forServer",{server:s.server,note:l}):l}let go={empty:"mcp.importField.reason.empty",input:"mcp.importField.reason.input",variable:"mcp.importField.reason.variable",home:"mcp.importField.reason.home","workspace-basename":"mcp.importField.reason.workspace-basename","unsupported-variable":"mcp.importField.reason.unsupported-variable","client-secret":"mcp.importField.reason.client-secret","registry-header":"mcp.importField.reason.registry-header","registry-variable":"mcp.importField.reason.registry-variable"},ga={url:"mcp.add.source.url","command-line":"mcp.add.source.command-line","pi-mcp-add":"mcp.add.source.pi-mcp-add","claude-mcp-add":"mcp.add.source.claude-mcp-add","claude-mcp-add-json":"mcp.add.source.claude-mcp-add-json","codex-mcp-add":"mcp.add.source.codex-mcp-add","gemini-mcp-add":"mcp.add.source.gemini-mcp-add","vscode-add-mcp":"mcp.add.source.vscode-add-mcp","mcp-servers-json":"mcp.add.source.mcp-servers-json","vscode-json":"mcp.add.source.vscode-json","zed-json":"mcp.add.source.zed-json","opencode-json":"mcp.add.source.opencode-json","server-object":"mcp.add.source.server-object","server-map":"mcp.add.source.server-map","registry-server-json":"mcp.add.source.registry-server-json","cursor-install-link":"mcp.add.source.cursor-install-link","vscode-install-link":"mcp.add.source.vscode-install-link","visual-studio-install-link":"mcp.add.source.visual-studio-install-link","copilot-app-install-link":"mcp.add.source.copilot-app-install-link"},gd=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),gc=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),gu=[{source:"url",text:"https://mcp.example.com/mcp"},{source:"command-line",text:"npx -y @modelcontextprotocol/server-everything"},{source:"pi-mcp-add",text:"pi mcp add docs --url https://mcp.example.com/mcp"},{source:"claude-mcp-add",text:"claude mcp add --transport http docs https://mcp.example.com/mcp"},{source:"claude-mcp-add-json",text:'claude mcp add-json docs \'{"type":"http","url":"https://mcp.example.com/mcp"}\''},{source:"codex-mcp-add",text:"codex mcp add fetch -- uvx mcp-server-fetch"},{source:"gemini-mcp-add",text:"gemini mcp add --transport http docs https://mcp.example.com/mcp"},{source:"vscode-add-mcp",text:`code --add-mcp '${gc}'`},{source:"mcp-servers-json",text:'{ "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } }'},{source:"vscode-json",text:'{ "servers": { "docs": { "type": "http", "url": "https://mcp.example.com/mcp" } } }'},{source:"zed-json",text:'{ "context_servers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } }'},{source:"opencode-json",text:'{ "mcp": { "docs": { "type": "remote", "url": "https://mcp.example.com/mcp" } } }'},{source:"server-object",text:'{ "type": "http", "url": "https://mcp.example.com/mcp" }'},{source:"server-map",text:'{ "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } }'},{source:"registry-server-json",text:'{ "name": "com.example/docs", "version": "1.0.0", "remotes": [{ "type": "streamable-http", "url": "https://mcp.example.com/mcp" }] }'},{source:"cursor-install-link",text:`cursor://anysphere.cursor-deeplink/mcp/install?name=fetch&config=${btoa(gd)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(gc)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(gc)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(gc)}`}];function gp(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!(!r&&e.targets.every(e=>{let{parts:t}=e;return 1===t.length})))return[...new Set(e.targets.map(r=>{let{parts:i}=r;return i.map(r=>"string"==typeof r?py(r):r.field===e.id?n:`‹${py(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function gh(e){return"select"!==e.kind&&e.targets.every(e=>ff(e.path)&&void 0===e.encoding)}let gf=/^[A-Za-z_][A-Za-z0-9_]*$/;function gm(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];let r=t.map(e=>e.replace(/[^A-Za-z0-9]+/g,"_")).join("_").replace(/_+/g,"_").replace(/^_|_$/g,"").toUpperCase();return gf.test(r)?r:void 0}let gg=/^(?:proxy-)?authorization$/i;function gx(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return gf.test(t)?t:gm(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return gm(t,...n)??gm(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(gg.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===m9?void 0:n}function gv(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function gb(e,t){let n=e;for(let e of t)n=n.split(e).join(hN);return{text:n,masked:n!==e}}function gy(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function gw(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(pY);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function gj(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function gk(e,t,n){return{action:"add",text:e.text,values:t.values,...Object.keys(t.secretReferences).length>0?{secretReferences:{...t.secretReferences}}:{},server:t.server&&t.parsed.ok?t.parsed.servers.indexOf(t.server):0,name:t.name,scope:t.scope,rawPi:e.rawPi,...t.trustFolder?{trustFolder:!0}:{},...n&&n.length>0?{confirmHostEnv:[...n]}:{}}}function gS(e,t,n){switch(e.kind){case"trust-too-broad":return t(gN[e.breadth.kind],{path:n(e.breadth.path)});case"secret":return t(e.fixed?"mcp.add.projectBlocked.secretFixed":"mcp.add.projectBlocked.secret",{fields:e.fields.join(", ")});case"file-problem":return t("mcp.add.projectBlocked.file-problem",{path:n(e.path),reason:t(`mcp.fileProblem.${e.reason}`)});default:return t(gC[e.kind])}}let gC={"no-project":"mcp.add.projectBlocked.no-project","project-not-listed":"mcp.add.projectBlocked.project-not-listed","trust-unreadable":"mcp.add.projectBlocked.trust-unreadable","project-untrusted":"mcp.add.projectBlocked.project-untrusted","untrusted-decision":"mcp.add.projectBlocked.untrusted-decision","folder-not-fresh":"mcp.add.projectBlocked.folder-not-fresh"},gN={home:"mcp.add.projectBlocked.trust-too-broad.home",root:"mcp.add.projectBlocked.trust-too-broad.root","contains-home":"mcp.add.projectBlocked.trust-too-broad.contains-home","contains-agent-dir":"mcp.add.projectBlocked.trust-too-broad.contains-agent-dir","contains-folder":"mcp.add.projectBlocked.trust-too-broad.contains-folder","contains-project":"mcp.add.projectBlocked.trust-too-broad.contains-project","too-many-folders":"mcp.add.projectBlocked.trust-too-broad.too-many-folders"};function g$(e){return py(ey(e))}function gE(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let gI=[{href:"https://glama.ai/mcp/servers",label:"glama.ai"},{href:"https://smithery.ai/servers",label:"smithery.ai"},{href:"https://mcp.so/",label:"mcp.so"},{href:"https://registry.modelcontextprotocol.io/",label:"MCP Registry"},{href:"https://github.com/mcp",label:"github.com/mcp"}],gM=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function gT(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,e0.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},l=[...t].sort((e,t)=>s[gs(e)]-s[gs(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:l.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${gs(e)}`,children:gl(e,i,n)},`${t}\0${e.code}`))})}let gR={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function gA(e){let{data:t,cwd:n,draft:s,busy:l,controlsBusy:o,failure:a,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,e0.s)(),h=(0,i.useId)(),f=(0,i.useId)(),m=(0,i.useMemo)(()=>(function e(t,n,r){let i,s=function(e,t){let n=e=>({kind:"blocked",block:e});if(!t)return n({kind:"no-project"});let r=e.project;if(!r)return n({kind:"project-not-listed"});let i=r.trust;if(!i||void 0!==i.decisionError)return n({kind:"trust-unreadable"});if(!0===i.decision)return{kind:"write"};if(!1===i.decision)return n({kind:"untrusted-decision"});if(i.requiresTrust)return n({kind:"project-untrusted",trustable:p0(r)});let s=r.trustFolder;return s?s.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===s.reason?{kind:"trust-too-broad",breadth:s.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),l=e=>mQ(t.text,{rawPi:t.rawPi,takenNames:gj(n,e)}),o=l(t.scope??"global"),a=o.ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0,d=t.scope??(a?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(a=(o=l(d)).ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0);let c={parsed:o,name:t.name??"",scope:d,projectMode:s,..."blocked"===s.kind?{projectBlock:s.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=hc(n.mcp);if(!a)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??a.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&gh(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=m2(a).map(fh),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=m3(a,h,m),x={};if(!g.ok)for(let e of g.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let v=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=gf.test(e.reference.trim())?e:{reference:"VALUE"}:void 0!==e&&""!==e.trim()?r[n.id]=e:void 0!==n.defaultValue?r[n.id]=n.defaultValue:n.optional?r[n.id]=void 0:r[n.id]="select"===n.kind?n.options?.[0]??"x":"x"}let i=m3(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,gf.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(a,h,m),b=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,l={source:e.source,commandFields:gt(r).filter(e=>{let{value:t}=e;return fl(t)}).map(gy),variableReferences:gt(r).map(e=>({...gy(e),variables:fo(e.value)})).filter(e=>{let{variables:t}=e;return t.length>0}),...r.exposure?{exposure:r.exposure}:{},enabled:s,unfilled:!n?.ok&&e.fields.length>0};if("url"in r){let e=gb(r.url,i);return{...l,transport:"http",target:py(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let o=gb(pk(r.command,r.args??[]),i);return{...l,transport:"stdio",target:o.text,...void 0!==r.cwd?{cwd:py(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:o.masked}}(a,h,g),y=g.ok?fK(p,g.config):void 0,w="blocked"===s.kind?s.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(gv)}:gw("project",n),j=gj(n,d),k=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(fS.test(p))if(j.includes(p))i={kind:"name-taken",name:p,suggestedName:fC(p,j),...k?{path:k.path}:{}};else if(g.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:b.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of gt(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(m9):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===m9))return r}(g.config,{isCommandConfigValue:fl,getConfigValueEnvVarNames:fo}))i={kind:"web-password"};else if("project"===d&&w)i={kind:"scope",block:w};else{let e=gw(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return a.fields.find(e=>e.id===t)?.label??t},t=g.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(g.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&w?e({...t,scope:"global"},n,r):{parsed:o,server:a,name:p,scope:d,projectMode:s,...w?{projectBlock:w}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=mQ(e,{rawPi:!0});if(!t.ok)return!1;let n=mQ(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:w}=m,j=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!m.pasteSecrets.includes(String(e.params?.field))):[],k=void 0!==s.name&&s.name!==v?.name?[]:j.filter(e=>gM.has(e.code)),S=j.filter(e=>!gM.has(e.code)),C=!l&&!o&&void 0===w,N=()=>{C&&c(gk(s,m))},$=e=>d({...s,...e}),E=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),I=w&&(""!==s.text.trim()||"mcp-off"===w.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:py(e.name),path:e.path?g$(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(py).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(py).join(", ")});case"config-invalid":return gl(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return gS(e.block,t,g$)}}(w,p,v?.fields):void 0,M=y?.kind==="project-untrusted"&&y.trustable&&u,T=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(cJ,{title:p("mcp.add.title"),catalogs:gI,target:(0,r.jsxs)(cV,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:gE("global",p)},{value:"project",label:gE("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:g$(E),disabledReason:y?gS(y,p,g$):null,onChange:e=>$({scope:e}),children:[M&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),m.trustFolder&&"trust-and-write"===m.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:g$(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(gi(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?gu.map(e=>{let{source:t,text:n}=e;return{label:p(ga[t]),value:n}}):[],multiline:!0,children:[g&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(gi(s,{rawPi:e.target.checked}))}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:p("mcp.add.rawPi")}),s.rawPi&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.rawPiOn")})]})]}),!x.ok&&""!==s.text.trim()&&(0,r.jsx)(gT,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(cH,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>$({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:py(e.name)},`${t}\0${e.name}`))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cH,{label:p("config.name"),children:(0,r.jsx)("input",{id:f,className:"mcp-add-input","aria-label":p("config.name"),value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>$({name:e.target.value})})}),(0,r.jsx)(gT,{notes:k,fields:v.fields}),w?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{size:"small",onClick:()=>$({name:w.suggestedName}),children:p("mcp.add.useName",{name:py(w.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cB,{children:p("mcp.add.preview")}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(cU,{label:p("mcp.add.readAs"),children:p(ga[b.source])}),(0,r.jsx)(cU,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(cU,{label:"http"===b.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:b.target}),"stdio"===b.transport&&void 0!==b.cwd&&(0,r.jsx)(cU,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),T.length>0&&(0,r.jsx)(cU,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(gL,{names:T})}),b.commandFields.length>0&&(0,r.jsx)(cU,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:b.commandFields.map(e=>{let t=pN(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),b.variableReferences.length>0&&(0,r.jsx)(cU,{label:p("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===b.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:pI(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=pN(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:py(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[b.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),b.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(gT,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cB,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(gz,{field:e,fields:v.fields,draft:s,suggestedName:(t=m.name,(n=e.targets[0])?gx(fh(n.path),t):void 0),problem:m.fieldProblems[e.id],onDraftChange:d},e.id)})]}),m.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cB,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(gP,{label:e,draft:s,suggestedName:gx(e,m.name),stored:m.fill?.ok?(t=m.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice("headers.".length)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice("env.".length)]:void 0)&&h_(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(c2,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":l||void 0,"aria-describedby":I?h:void 0,onClick:N,children:l?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),I&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${w?.kind==="scope"?"is-warning":"is-dim"}`,children:I}),v&&!w&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),a&&(0,r.jsxs)("div",{role:"alert",className:"mcp-add-failure",children:[(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[p("mcp.add.failed")," ",function(e,t){if(e.timedOut)return t("mcp.actionTimedOut");if("trust-too-broad"===e.reason&&e.breadth)return t(gN[e.breadth.kind],{path:g$(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(gv)?"mcp.add.projectBlocked.secret":"mcp.add.projectBlocked.secretFixed",{fields:e.fields.join(", ")});if("name-taken"===e.reason&&e.name)return t("mcp.add.nameTaken",{name:py(e.name),path:e.path?g$(e.path):"mcp.json"});let n=e.reason?gR[e.reason]:void 0;return n?t(n,{error:py(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):py(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:g$(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(gT,{notes:a.notes,fields:v?.fields}),"name-taken"===a.reason&&a.suggestedName&&w?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{size:"small",onClick:()=>$({name:a.suggestedName}),children:p("mcp.add.useName",{name:py(a.suggestedName)})})}),"host-env-confirm"===a.reason&&a.names&&a.names.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.hostEnv.body",{names:a.names.map(py).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:l||o||void 0!==w,onClick:()=>c(gk(s,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function gL(e){let{names:t}=e,{t:n}=(0,e0.s)();return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:py(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function gz(e){let t,{field:n,fields:s,draft:l,suggestedName:o,problem:a,onDraftChange:d}=e,{t:c}=(0,e0.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=gh(n),f=h?l.references[n.id]:void 0,m=void 0!==f,g=py(n.label),x=l.values[n.id]??n.defaultValue??"",v=go[n.reason],b=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=m?f&&!a?gp(n,s,"${"+f+"}",!0):void 0:gp(n,s,`‹${c("mcp.add.field.slot")}›`),w=e=>d({...l,values:{...l.values,[n.id]:e}}),j=e=>{let t={...l.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...l,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(cH,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:g}),value:f,placeholder:o??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":g,value:x,...p,onChange:e=>w(e.target.value),children:[!n.options?.includes(x)&&(0,r.jsx)("option",{value:"",children:c("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:py(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":g,value:x,autoComplete:"off",placeholder:n.placeholder?py(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>w(e.target.value)})}),a&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:gl(a,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:py(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(v)}),m?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?c("mcp.add.field.storedAsVariable",{value:y}):c("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:b?c("mcp.add.field.optionalHeader",{name:py(b)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:m,onChange:e=>j(e.target.checked?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function gP(e){let{label:t,draft:n,suggestedName:s,stored:l,problem:o,onDraftChange:a}=e,{t:d}=(0,e0.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=py(t),f=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,a({...n,secretReferences:r})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)("span",{className:"mcp-config-lines",children:(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:h})," ",d("mcp.add.secret.holds")]})}),(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:p,onChange:e=>f(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(cH,{label:d("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("mcp.add.field.variableName",{field:h}),value:u,placeholder:s??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...o?{"aria-invalid":!0,"aria-describedby":c}:{},onChange:e=>f(e.target.value)})}),o&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:gl(o,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==l?d("mcp.add.secret.storedAs",{value:py(l)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let gW=new Set(["done","failed","cancelled","expired"]);function gO(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!gW.has(t))}let gF={"mcp-off":"mcp.signIn.blocked.mcp-off","project-untrusted":"mcp.signIn.blocked.project-untrusted","trust-unreadable":"mcp.signIn.blocked.trust-unreadable",invalid:"mcp.signIn.blocked.invalid","web-password":"mcp.test.blocked.web-password"},gD={"mcp-off":"mcp.signIn.blocked.mcp-off","project-untrusted":"mcp.signIn.blocked.project-untrusted","trust-unreadable":"mcp.signIn.blocked.trust-unreadable","server-invalid":"mcp.signIn.blocked.invalid","web-password":"mcp.test.blocked.web-password","entry-not-object":"mcp.signIn.refused.file","server-missing":"mcp.signIn.refused.file",unparsable:"mcp.signIn.refused.file","invalid-shape":"mcp.signIn.refused.file","link-dangling":"mcp.signIn.refused.file","link-outside":"mcp.signIn.refused.file","not-a-file":"mcp.signIn.refused.file","too-large":"mcp.signIn.refused.file","too-many-servers":"mcp.signIn.refused.file","invalid-request":"mcp.signIn.refused.invalid-request"},gB={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},gH={"connect-failed":"mcp.signIn.failed.connect-failed","queue-timed-out":"mcp.signIn.failed.queue-timed-out","sign-in-failed":"mcp.signIn.failed.sign-in-failed",internal:"mcp.signIn.failed.internal"};function g_(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,gW.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function gU(e){return"sign-in-unknown"===e.reason}async function gq(e,t,n,r){var i;let s,l;try{s=await n(e,{...t,cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{l=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=l)&&"object"==typeof i&&"string"==typeof i.flowId&&"string"==typeof i.phase&&"string"==typeof i.name&&("global"===i.scope||"project"===i.scope)&&"number"==typeof i.expiresInMs?{ok:!0,data:l}:{ok:!1,error:p9(l,s.status)}}function gK(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},l=t.method??"GET";return p7(r=>gq(e,t,n,r),()=>({ok:!1,error:{error:`${l} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function gV(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function gZ(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"mcp.signIn.requestTimedOut";if(e.timedOut)return t(n);let r=e.reason?gD[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function gJ(e){let{server:t,run:n,block:s,signOutBlock:l,controlsBusy:o,signingOut:a,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,e0.s)(),f=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=gO(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?eI(document,v.current):e&&!b&&eI(document,x.current)},[b]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(cU,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:py(t.authProvider)}):h("mcp.signIn.header")});let w=n?.flow,j=n?.starting===!0,k=void 0!==w&&(w.scope!==t.scope||w.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=j||a||void 0!==s,N=o||j||void 0!==l,$=w?.phase==="finishing";return(0,r.jsx)(cU,{label:h("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:h(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),w&&b&&k&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:py(w.name)})}),w&&b&&("authorize"===w.phase?(0,r.jsx)(gY,{flow:w,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,w.flowId,e)},w.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(gB[w.phase]??"mcp.signIn.phase.connecting")})),w&&b&&$&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),w&&!b&&!n?.gone&&(0,r.jsx)(gG,{flow:w,shared:k}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:h("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.requestFailed")," ",gZ(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",gZ(n.cancelError,h,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.signOutFailed")," ",gZ(n.signOutError,h,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h(gF[s])}),!s&&l&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(gF[l])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&w?(0,r.jsx)(c2,{ref:v,size:"small",disabled:n?.cancelling===!0||$,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":$?g:void 0,onClick:()=>p(t,w.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(c2,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":j||void 0,"aria-describedby":s?f:void 0,onClick:()=>d(t),children:h(j?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(c2,{size:"small",disabled:N,"aria-busy":a||void 0,"aria-describedby":l?s?f:m:void 0,onClick:()=>c(t),children:h(a?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!b&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!l&&!b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function gY(e){let{flow:t,pasting:n,pasteError:s,onPaste:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&eI(document,c.current)},[n]);let p=function(e){if(void 0!==e)try{let t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol?t.href:void 0}catch{return}}(t.authorizationUrl);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(uo,{message:o("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:py(p)})]}):(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.authorizationUrl??"")})]}),value:a,placeholder:o("mcp.signIn.paste.placeholder"),inputLabel:o("mcp.signIn.paste.label"),submitLabel:o(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:c,onValueChange:d,onSubmit:()=>l(a)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.signIn.paste.refused")," ",gZ(s,o,"mcp.signIn.paste.timedOut"),"redirect-denied"===s.reason&&s.error&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.redirect",{url:py(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.wait")})]})}function gG(e){let{flow:t,shared:n}=e,{t:i}=(0,e0.s)(),s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];switch(e.phase){case"done":{if(t)return e.alreadySignedIn?"mcp.signIn.shared.already":"mcp.signIn.shared.done";if(e.alreadySignedIn)return"mcp.signIn.done.already";let n=e.result;if(n&&"needs-auth"===n.state)return"mcp.signIn.done.needsAuthAfter";if(n&&"failed"===n.state)return"mcp.signIn.done.failedAfter";if(!n)return"mcp.signIn.done.notConnected";return e.refreshed?"mcp.signIn.done.refreshed":"mcp.signIn.done.signedIn"}case"failed":if(t&&"connect-failed"===e.failure)return"mcp.signIn.shared.connect-failed";return gH[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let l=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"done"===e.phase?!t&&e.result&&"connected"!==e.result.state?"warning":"on":"failed"===e.phase?"error":"expired"===e.phase?"warning":"off"}(t,n);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{role:"status",className:"error"===l?"mcp-config-line is-error":"warning"===l?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:py(t.name)})}),t.error&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.error)})]})]})}function gX(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function gQ(e){return py(ey(e))}function g0(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:gQ(r.path)}):t(n)}function g1(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function g2(e,t){return e.timedOut?t("mcp.actionTimedOut"):g1(e,t)}function g4(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function g8(e){let{cwd:t,onClose:n,embedded:s=!1,trust:l,onTrustProject:o,onProjectTrustChanged:a}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>ci("mcp",t)),[m,g]=(0,i.useState)({saving:!1,error:null}),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[$,E]=(0,i.useState)({}),I=(0,i.useRef)(0),M=(0,i.useRef)(null),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,z]=(0,i.useState)({}),P=(0,i.useRef)(L);P.current=L;let[W,O]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(gn),_=(0,i.useRef)(B);_.current=B;let[U,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(null),Z=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let Y=(0,i.useCallback)(async()=>{let e=++I.current;M.current?.abort();let n=new AbortController;M.current=n,p(!0);let r=await hi(t,void 0,n.signal);if(e===I.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>pQ(pG(r.data,!!t),e))}},[t]),G=u_(l);(0,i.useEffect)(()=>(Y(),()=>{I.current+=1,M.current?.abort()}),[Y,G]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"preference"});let n=await ho(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&c(e=>{var t,r;let i;return"loaded"===e.state?{...e,data:(t=e.data,r=n.preference,i={...t.codemode,preference:r},delete i.preferenceError,{...t,codemode:i})}:e}),Y())},[Y]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"mode"});let n=await ha(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.mode;if(!n)return e;let r={settingsPath:n.settingsPath,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,mode:r}}}(e.data,n.mode)}:e),Y())},[Y]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await hd(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.inlineBudget;if(!n)return e;let r={settingsPath:n.settingsPath,default:n.default,max:n.max,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,inlineBudget:r}}}(e.data,n.inlineBudget)}:e),Y())},[Y]);(0,i.useEffect)(()=>{let e=A.current;return Z.current=!0,()=>{Z.current=!1,T.current?.abort(),T.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=pR(e);if(A.current.has(n))return;let r={};A.current.set(n,r),E(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await hC({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),E(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let s=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...s,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...s,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],l,e.configKey)}));let o=J.current,a="loaded"===o.state?o.data.servers.find(e=>pR(e)===n):void 0;(l.ok?a?.configKey===l.data.configKey:void 0===l.error.reason||l.error.timedOut)||Y()},[t,Y]),en=(0,i.useCallback)((e,n)=>{I.current+=1,M.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>pQ(pG(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=pR(e),r=P.current[n];if(r?.starting||gO(r))return;z(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return gK("/api/mcp/sign-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e.scope,name:e.name,...t?{cwd:t}:{}})},n,r,i,{abortAtDeadline:!1})}({scope:e.scope,name:e.name},s);Z.current&&(z(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?g_({},e.data,t):{error:e.error}}(l)})),l.ok||void 0===l.error.reason||l.error.timedOut||Y())},[t,Y]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=pR(e);z(e=>e[r]?.flow?.flowId===t?{...e,[r]:{...e[r],pasting:!0,pasteError:void 0}}:e);let i=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return gK(gV(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);Z.current&&z(e=>{let n=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,pasting:!1,version:(e.version??0)+1};return n.ok?{...g_(i,n.data,r),pasteError:void 0}:gU(n.error)?{...i,gone:!0}:{...i,pasteError:n.error}}(e[r],t,i);return void 0===n||n===e[r]?e:{...e,[r]:n}})},[]),es=(0,i.useCallback)(async(e,t)=>{let n=pR(e);z(e=>e[n]?.flow?.flowId===t?{...e,[n]:{...e[n],cancelling:!0}}:e);let r=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return gK(gV(e),{method:"DELETE"},t,n,r)}(t);Z.current&&z(e=>{let i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,cancelling:!1,cancelError:void 0,version:(e.version??0)+1};return n.ok?g_(i,n.data,r):gU(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),el=Object.entries(L).flatMap(e=>{let[t,n]=e;return gO(n)&&n.flow?[`${t}\u0001${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!el)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of el.split("\x02")){let[n,r]=t.split("\x01"),i=P.current[n]?.version??0,s=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return gK(gV(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;z(e=>{let t=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now(),i=arguments.length>4?arguments[4]:void 0;return e?.flow&&e.flow.flowId===t&&(void 0===i||(e.version??0)===i)?n.ok?g_(e,n.data,r):gU(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}O(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[el,W]);let eo=(0,i.useRef)(L);(0,i.useEffect)(()=>{let e=eo.current;eo.current=L,Object.keys(L).some(t=>{var n,r;return n=e[t],r=L[t],gO(n)&&!gO(r)})&&Y()},[L,Y]);let ea=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let s=J.current,l="loaded"===s.state&&s.data.project?t:null,o=await hg(e,l,void 0,i.signal);if(R.current===i)return R.current=null,v(null),o.ok?en(o.data,r?.(o.data)):Y(),o},[en,t,Y]),ed=(0,i.useCallback)(async(e,t)=>{let n=pR(e),r=g4();y(null),j(null);let i=await ea({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ec=(0,i.useCallback)(async(e,t)=>{let n=pR(e),r=g4();y(null),j(null);let i=await ea({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),eu=(0,i.useCallback)(async(e,t)=>{let n=pR(e),r=g4();y(null),j(null);let i=await ea({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ep=(0,i.useCallback)(async e=>{let t=pR(e),n=g4();y(null),j(null);let r=await ea({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[ea]),eh=(0,i.useCallback)(async()=>{if(!k)return;let e=g4();y(null),j(null),S({...k,undoing:!0,error:void 0});let t=await ea({action:"undo",token:k.token},"undo",e=>e.restored?pR(e.restored):void 0);t&&(S(e=>e?.token!==k.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[ea,k]),ef=(0,i.useCallback)(async e=>{let t=pR(e),n=g4();y(null),j(null),z(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await ea({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(z(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();E(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[ea]),em=(0,i.useCallback)(async e=>{let n=g4(),r=_.current;y(null),j(null),q(null);let i=await ea(e,"add",e=>e.added?pR(e.added):void 0);if(!i)return;let s=_.current!==r;if(!i.ok){s||q(i.error),i.error.trust&&t&&a?.(t,i.error.trust),N({control:n});return}let{added:l,trust:o,trustedFolder:d}=i.data;if(D(!1),s||H(gn),N({control:null,toSelectedRow:!0}),!l)return;V({...l,key:pR(l),...d&&t?{trustedFolder:t}:{}}),o&&t&&a?.(t,o);let c=i.data.servers.find(e=>pR(e)===pR(l));c&&!hv(c,i.data)&&et(c)},[t,a,ea,et]),eg=k?.token,ex=k?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:uH(t,n,e=>e.enabled).filter(n?hf:hh),keptOff:n?t.filter(e=>!e.enabled&&hh(e)&&!hf(e)).length:0},s=g4();if(y(null),j(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let l=await ea({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!l)return;if(N({control:s}),!l.ok)return void j({scope:e,keptOff:i,failures:[],total:r.length,error:l.error});let o=l.data.results??[],a=o.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));j(a.length>0||i>0?{scope:e,keptOff:i,failures:a,total:o.length}:null)},[ea]);return(0,i.useEffect)(()=>{h&&cs("mcp",h,t)},[t,h]),(0,r.jsx)(g3,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:m,busy:x,actionError:b,groupStatus:w,undo:k,focusBack:C,tests:$,signIns:L,adding:F,addDraft:B,addFailure:U,added:K,onAddOpen:()=>{D(!0),V(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),q(null)},onAddSubmit:e=>void em(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void ef(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{f(e),y(null),D(!1),V(t=>t?.key===e?t:null)},onRefresh:()=>void Y(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ed(e,t),onServerSwitchInProject:(e,t)=>void ec(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:o,onClose:n})}function g3(e){var t,n,s,l;let o,a,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:f,codemodeSave:m={saving:!1,error:null},busy:g=null,actionError:x=null,groupStatus:v=null,undo:b=null,focusBack:y=null,tests:w={},signIns:j={},adding:k=!1,addDraft:S=gn,addFailure:C=null,added:N=null,onAddOpen:$=()=>{},onAddDraftChange:E=()=>{},onAddSubmit:I=()=>{},onSelect:M,onRefresh:T,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:z=()=>{},onServerSwitchInProject:P=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:q=()=>{},onTrustProject:K,onClose:V}=e,{t:Z}=(0,e0.s)(),J=(0,i.useId)(),Y=(0,i.useId)(),G="loaded"===u.state?(t=u.data,o=!1,a=t.servers.map(e=>{var t;let n=w[pR(e)]?.response;if(!n||n.configKey!==e.configKey||e.status&&("test"===(t=e.status).origin?t.testedAt:t.closedAt??t.updatedAt)>=n.result.testedAt)return e;o=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),o?{...t,servers:a}:t):void 0,X=G?pG(G,!!c):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:pA(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>pR(e)===p),en=N?ee.find(e=>pR(e)===N.key):void 0,er=G?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(G.mcp):void 0,ei=er?void 0:G?.hostInactive,es=G?.files.find(e=>"project"===e.scope),el=G?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(G.project,es):void 0,eo=K&&p0(G?.project)?K:void 0,ea=el?.kind==="untrusted"&&void 0!==eo,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(ea);(0,i.useEffect)(()=>{let e=eu.current;eu.current=ea,e&&!ea&&eI(document,ed.current??ec.current)},[ea]);let ep=(0,i.useRef)(null),eh=b?.token,ef=(0,i.useRef)(eh);(0,i.useEffect)(()=>{let e=ef.current;ef.current=eh,void 0!==eh&&eh!==e?eI(document,ep.current):void 0!==e&&void 0===eh&&eI(document,ed.current??ec.current)},[eh]);let em=G?[...G.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],eg=pX(ee),ex=G?.files.find(e=>"global"===e.scope),ev=G?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&pA(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(G):void 0,eb=G?(n=ee.length,s=G.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(pY))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ew=null!==g||h||m.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ew&&ej.current!==y)if(ej.current=y,y.toSelectedRow)eI(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&eI(e,t.isConnected&&!t.disabled?t:n)}},[y,ew]);let ek=e=>G?hu(e,G):void 0,eS=!!G&&hc(G.mcp),eC=X.find(e=>"project"===e.scope)?.servers??[],eN=ek("project"),e$=el?.kind==="untrusted"?[g0(el,Z),eN&&"mcp-off"!==eN&&eC.length>0?Z(hp[eN]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(c$,{embedded:f,title:Z("settings.mcp"),subtitle:c?ey(c):void 0,closeLabel:Z("i18n.close"),onClose:V,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(cY,{id:J,children:[g0(er,Z),eS&&(0,r.jsxs)(r.Fragment,{children:[" ",Z(hp["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(G.mcp.detail)})]})]}),ei&&(0,r.jsx)(cY,{children:Z("mcp.hostInactive",{path:gQ(ei.cwd),owner:gQ(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(cY,{children:Z("mcp.projectNotListed",{reason:g1(u.projectError,Z)})}),el?.kind==="untrusted"&&(0,r.jsx)(cG,{id:Y,message:e$,trustLabel:Z("mcp.trust.trustButton"),onTrust:eo}),el?.kind==="inherited"&&(0,r.jsx)(cY,{children:g0(el,Z)}),b&&(0,r.jsxs)(cY,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(c2,{ref:ep,size:"small",onClick:D,disabled:b.undoing||ew,children:b.undoing?Z("mcp.undoing"):Z("mcp.undo")}),children:[Z("mcp.removed",{name:py(b.name),path:gQ(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",Z("mcp.undoFailed")," ",g2(b.error,Z)]})]}),N&&G&&en&&(0,r.jsx)(g5,{added:N,cwd:c,server:en,testing:w[N.key]?.running===!0,signIn:j[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?hv(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:Z("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[Z("mcp.loadFailed")," ",g1(u.error,Z)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(g6,{codemode:G.codemode,active:!k&&p===pT,rowRef:ed,onSelect:M})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(g9,{group:e,context:Q,selected:k?null:p,selectedRowRef:ed,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&el?.kind==="untrusted"?Y:void 0,busy:g,controlsBusy:ew,status:v?.scope===e.scope?v:null,onSelect:M,onGroupSwitch:O},e.scope)})]}):null}),G&&(0,r.jsx)(c8,{ref:ec,active:k,onClick:$,children:Z("mcp.add.action")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:G&&Q&&ev&&eb?k?(0,r.jsx)(gA,{data:G,cwd:c,draft:S,busy:"add"===g,controlsBusy:ew,failure:C,onDraftChange:E,onSubmit:I,onTrustProject:eo}):p===pT?(0,r.jsx)(xc,{codemode:G.codemode,autoEnable:ev,save:m,serverBusy:null!==g,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(xt,{server:et,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ev,block:ek(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!pA(t.project))return;let n=t.files.find(e=>"project"===e.scope);if(!n||n.problems.some(e=>"auto-enable-codemode-invalid"!==e.reason))return;let r=t.servers.find(t=>"project"===t.scope&&t.name===e.name);return r?r.override?{kind:"override",key:pR(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,G),inProjectBlock:ek("project"),savedWhileOff:!G.mcp.available&&!eS,busy:g,controlsBusy:ew,actionError:x?.key===pR(et)?x.failure:null,test:(l=w[pR(et)],l&&void 0!==l.configKey&&l.configKey!==et.configKey?{running:l.running,...l.response?{response:l.response}:{}}:l),testBlock:hv(et,G),signIn:j[pR(et)],signInBlock:hv(et,G),signOutBlock:(d=hu(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:z,onSwitchInProject:P,onShowServer:e=>{M(e),requestAnimationFrame(()=>eI(document,ed.current??ec.current))},onExposureChange:W,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:q},pR(et)):(0,r.jsx)(cX,{children:"mcp.empty"===eb?Z(eb,{globalPath:gQ(ex?.path??"~/.pi/agent/mcp.json")}):Z(eb)}):null})})]}),(0,r.jsxs)(c0,{status:em.length>0?(0,r.jsx)(c1,{tone:em.some(e=>{let{problem:t}=e;return pY(t)})?"error":"warning",summary:1===em.length?Z("mcp.footer.fileProblem"):Z("mcp.footer.fileProblems",{count:em.length}),details:em.map(e=>{let{file:t,problem:n}=e,i=pM(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:gQ(t.path)})," ",Z(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(c1,{summary:eg.total>0?Z("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!f&&(0,r.jsx)(c2,{onClick:V,children:Z("i18n.close")}),(0,r.jsx)(c2,{variant:"secondary",onClick:T,disabled:ew,children:Z("i18n.refresh")})]})]})}function g5(e){let{added:t,cwd:n,server:i,testing:s,signIn:l,signingOut:o,signInBlock:a,onSignIn:d}=e,{t:c}=(0,e0.s)(),u=py(t.name),p="project"===t.scope&&n?py(ew(t.path,n)):gQ(t.path),h=i.status,f=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=l?.starting===!0||gO(l);return(0,r.jsxs)(cY,{action:!f||m||o||a?void 0:(0,r.jsx)(c2,{size:"small",variant:"primary",onClick:()=>d(i),children:c("mcp.signIn.button")}),children:[void 0===t.trustedFolder?c("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?c("mcp.add.addedTrustedHere",{name:u,path:p}):c("mcp.add.addedTrusted",{name:u,path:p,folder:gQ(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function g6(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:l}=(0,e0.s)(),o=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=l(p3[o]);return(0,r.jsxs)(cL,{ref:n?i:void 0,active:n,"aria-label":l("mcp.codemode.rowLabel",{state:a}),onClick:()=>s(pT),children:[(0,r.jsx)(c3,{...pH(p5(o))}),(0,r.jsx)(cz,{className:"is-grow",children:l("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${p5(o)}`,children:a})]})}function g9(e){var t;let n,i,{group:s,context:l,selected:o,selectedRowRef:a,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,e0.s)(),{enabled:x,total:v}=pX(s.servers),b=(t=s.servers).some(e=>e.enabled&&hh(e))&&t.every(e=>e.enabled||!hf(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(pY)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),w=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${g("mcp.actionFailed")} ${g2(h.error,g)}`:h.failures.length>0?[g("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${py(t)}: ${g2(n,g)}`})].join("\n"):void 0,{...n?{note:n}:{},...i?{error:i}:{}}):void 0;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{aside:v>0?(0,r.jsx)(cR,{enabled:x,total:v,checked:b,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:gX(s.scope,g)}),onChange:e=>m(s.scope,s.servers,e)}):void 0,children:gX(s.scope,g)}),w&&(0,r.jsx)(cA,{note:w.note,error:w.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),s.servers.map(e=>{let t=pR(e),n=pz(e,l),i=pB(n),s=pD[n],d=py(e.name);return(0,r.jsxs)(cL,{ref:o===t?a:void 0,active:o===t,"aria-label":g("mcp.rowLabel",{name:d,state:g(pO(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(c3,{...pH(i)}),(0,r.jsx)(cz,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(s)})]},t)})]})}function g7(e){let{fields:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=pN(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function xe(e){let{names:t}=e;return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:py(e)},e))})}function xt(e){let{server:t,context:n,codemode:s,toolSearchDisabled:l,autoEnable:o,block:a,inProject:d,inProjectBlock:c,savedWhileOff:u,busy:p,controlsBusy:h,actionError:f,test:m,testBlock:g,signIn:x,signInBlock:v,signOutBlock:b,onSwitch:y,onSwitchInProject:w,onShowServer:j,onExposureChange:k,onRemove:S,onTest:C,onSignIn:N,onSignOut:$,onSignInPaste:E,onSignInCancel:I}=e,{t:M}=(0,e0.s)(),T=(0,i.useId)(),R=(0,i.useId)(),A=pz(t,n),L=pS(t),z=t.status,P=z?.origin==="test"&&"connected"===z.state&&z.toolCount>0?z:void 0,W=void 0===t.invalidError,O="http"===t.transport||void 0===t.transport&&void 0!==t.url,F=!O&&("stdio"===t.transport||void 0!==t.command),D=t.exposure?function(e,t,n){if("codemode"===e){var r;return r=t.codemode,"unavailable"===r.sandbox.state?{key:"mcp.exposure.sandboxUnavailable"}:r.builtinDisabled?{key:"mcp.exposure.builtinDisabled"}:n.value||"always"===p1(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:l},o):void 0,B=(0,i.useId)(),H=(0,i.useId)(),_=pR(t),U=py(t.name),q=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,V=a?M(`mcp.reason.${a}`):K?M("mcp.reason.entry-not-object"):q?M("mcp.reason.web-password"):u?M("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(cP,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cW,{children:[(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:t.scope,children:gX(t.scope,M)}),(0,r.jsx)(cD,{children:U})]}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(xa,{server:t,test:m,testBlock:g,describedBy:R,onTest:C}),(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:h||void 0!==a,"aria-describedby":a?T:void 0,onClick:()=>S(t),children:p===`remove:${_}`?M("i18n.removing"):M("i18n.remove")}),(0,r.jsx)(c4,{checked:t.enabled,disabled:h||void 0!==a||K||q,loading:p===`switch:${_}`,describedBy:V?T:void 0,label:M(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:U}),onChange:e=>y(t,e)})]})]}),V&&(0,r.jsx)("div",{id:T,className:"config-detail-heading-note",children:V})]}),f&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[M("mcp.actionFailed")," ",g2(f,M)]}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(xd,{server:t,state:A,test:m,testBlock:g,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(cU,{label:M("mcp.detail.description"),tone:"plain",children:py(t.description)}),void 0!==L?(0,r.jsx)(cU,{label:O?M("mcp.detail.url"):M("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:L}):t.transport&&(0,r.jsx)(cU,{label:M("mcp.detail.transport"),children:M(`mcp.transport.${t.transport}`)}),F&&void 0!==t.cwd&&(0,r.jsx)(cU,{label:M("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:py(t.cwd)}),F&&t.envNames.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.env"),children:(0,r.jsx)(xe,{names:t.envNames})}),O&&t.headerNames.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.headers"),children:(0,r.jsx)(xe,{names:t.headerNames})}),W&&t.commandFields.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:M("mcp.server.commandFields")}),(0,r.jsx)(g7,{fields:t.commandFields})]})}),W&&t.variableReferences.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:M(p$(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:pI(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=pN(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:M("mcp.server.variableIn",{variable:t,field:M(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),O&&W&&(0,r.jsx)(gJ,{server:t,run:x,block:v,signOutBlock:b,controlsBusy:h,signingOut:p===`sign-out:${_}`,onSignIn:N,onSignOut:$,onPaste:E,onCancel:I}),(t.exposure||P)&&(0,r.jsx)(cU,{label:M("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":M("mcp.exposure.label",{name:U}),"aria-describedby":[B,a?T:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&k(t,n)},children:pZ.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?M("mcp.exposure.optionDefault",{label:M(pJ[e])}):M(pJ[e])},e))}),p===`exposure:${_}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:M("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:M(pV[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:M("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),D&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(D,M)})]}),P&&(0,r.jsx)(xo,{status:P,serverExposure:t.exposure})]})}),d&&(0,r.jsx)(cU,{label:M("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===d.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:d.applies?M("mcp.inProject.overridden",{keys:d.keys.join(", ")}):M("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(c2,{size:"small",onClick:()=>j(d.key),children:M("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(c2,{size:"small",disabled:h||void 0!==c||q,"aria-describedby":[H,c||q?T:null].filter(Boolean).join(" "),onClick:()=>w(t,!t.enabled),children:p===`in-project:${_}`?M("i18n.saving"):M(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:H,className:"mcp-config-line is-dim",children:M("mcp.inProject.saved")})]})})}),(0,r.jsx)(cU,{label:M("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:gQ(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[pC(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:M("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:M("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:M("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:g0(pE(t.override.keys),M)}),t.shadowedByProject&&"replaced"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:M("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:M("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:M("mcp.server.masked")})]})]})}function xn(e){let{error:t,stderr:n}=e,{t:i}=(0,e0.s)();return(0,r.jsxs)(r.Fragment,{children:[t&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t)})]}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.stderr")}),(0,r.jsx)("pre",{className:"mcp-test-output",children:n.split(/\r?\n/).map(py).join("\n")})]})]})}function xr(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(xl,{status:t,showState:n}):(0,r.jsx)(xs,{status:t,showState:n,entryCwd:i})}function xi(e){let{view:t}=e,{t:n}=(0,e0.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function xs(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:l}=(0,e0.s)(),o=p_(t.testedAt,l),a=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(xi,{view:t.timedOut?{key:hy.timedOut,tone:"error"}:{key:hy[t.state],tone:pB(t.state)}}),s((t.afterSignIn?hj:hw)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:hk(t.durationMs),time:o})]}),(0,r.jsx)(xn,{error:t.error,stderr:t.stderr}),a&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:py(a.title??a.name),version:py(a.version)})}),t.resources&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.resources")}),void 0!==t.cwd&&t.cwd!==i&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.ranIn",{path:gQ(t.cwd)})}),void 0!==t.queuedMs&&t.queuedMs>=500&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.queued",{seconds:hk(t.queuedMs)})})]})}function xl(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,e0.s)(),l=p_(t.updatedAt,s),o=void 0===t.closedAt?void 0:p_(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(xi,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:pU[t.state],tone:pK[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":pq[t.state],{path:gQ(t.cwd),time:l,...void 0===o?{}:{closedTime:o}})]}),void 0!==t.conflict&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.session.conflictOwner")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:gQ(t.conflict)})]}),(0,r.jsx)(xn,{error:t.error,stderr:t.stderr})]})}function xo(e){let{status:t,serverExposure:n}=e,{t:i}=(0,e0.s)(),s=t.toolCount-t.tools.length;return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("ul",{className:"mcp-test-tools",children:t.tools.map((e,t)=>(0,r.jsxs)("li",{className:"mcp-test-tool",children:[(0,r.jsxs)("span",{className:"mcp-config-chips",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:py(e.name)}),e.readOnly&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i("mcp.test.readOnly")}),e.exposure!==(n??"codemode")&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i(pJ[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:py(e.description)})]},`${t}\0${e.name}`))}),s>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.moreTools",{count:s})})]})}function xa(e){let{server:t,test:n,testBlock:s,describedBy:l,onTest:o}=e,{t:a}=(0,e0.s)(),d=(0,i.useRef)(null),c=n?.running===!0,u=(0,i.useRef)(c);return(0,i.useEffect)(()=>{let e=u.current;u.current=c,e&&!c&&eI(document,d.current)},[c]),(0,r.jsx)(c2,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?l:void 0,onClick:()=>o(t),children:a(c?"mcp.test.testing":"mcp.test.button")})}function xd(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:l}=e,{t:o}=(0,e0.s)(),a=t.status,d=pF[n],c="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(cU,{label:o("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${pB(n)}`,children:o(pO(n,a))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===c?l:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===c?l:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.webPassword")," ",(0,r.jsx)(g7,{fields:[t.webPasswordField]})]}),a?(0,r.jsx)(xr,{status:a,showState:pL(a)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.never")}),d&&(0,r.jsx)("span",{className:"mcp-config-line",children:o(d)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:o("mcp.test.queueTimedOut")}),i?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?hb[e.reason]:void 0;return n?t(n):g1(e,t)}(i.error,o)]}),s&&!c&&(0,r.jsx)("span",{id:l,className:"mcp-config-line is-dim",children:o(hx[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.serial")})]})})}function xc(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:l,onModeChange:o,onInlineBudgetSave:a}=e,{t:d}=(0,e0.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},f=function(e,t){if("automatic"===p1(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),m="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,g=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:p2[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(cP,{children:[(0,r.jsx)(cW,{children:(0,r.jsx)(cO,{children:(0,r.jsx)(cD,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(cU,{label:d("mcp.codemode.mode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[u?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cK,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(p3.automatic),disabled:p},{value:"always",label:d(p3.always),disabled:p||void 0!==m}],disabledReason:m?g0(m,d):null,onChange:e=>{e!==u&&l(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(xu,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(x,d)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(f,d)})]})}),t.mode?(0,r.jsx)(xp,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:o}):void 0!==t.modeError&&(0,r.jsx)(cU,{label:d("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(xh,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(cU,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.inlineBudgetError)})]})}),(0,r.jsx)(cU,{label:d("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===c.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(cU,{label:d("mcp.codemode.builtin"),tone:"error",children:g0(g,d)})]})]})}function xu(e){let{error:t}=e,{t:n}=(0,e0.s)();return t.timedOut?(0,r.jsx)(r.Fragment,{children:n("mcp.codemode.saveTimedOut")}):t.reason&&"internal"!==t.reason?(0,r.jsx)(r.Fragment,{children:n(`mcp.reason.${t.reason}`)}):(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.error)})}function xp(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:l}=e,{t:o}=(0,e0.s)(),a="mode"===i.target,d=function(e){let t=e.mode;if(!t)return[];let n=[];void 0!==t.invalid&&n.push({key:"mcp.codemode.toolMode.invalid",params:{path:t.settingsPath,value:t.invalid}});let r=t.projectOverride;return r&&n.push({key:p8[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===p1(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(cU,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(cK,{value:t.value,label:o("mcp.codemode.toolMode"),options:[{value:"on",label:o("mcp.codemode.toolMode.on"),disabled:s},{value:"only",label:o("mcp.codemode.toolMode.only"),disabled:s}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&l(e)},children:a&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:o("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:o(p4[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(e,o)},e.key)),a&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(xu,{error:i.error})]})]})})}function xh(e){let t,n,{budget:s,save:l,waiting:o,onSave:a}=e,{t:d}=(0,e0.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,f]=(0,i.useState)(p);(0,i.useEffect)(()=>{f(p)},[p]);let m=function(e,t){let n=e.trim();if(""===n)return{ok:!0,value:null};if(!/^\d+$/.test(n))return{ok:!1};let r=Number(n);return r<=t?{ok:!0,value:r}:{ok:!1}}(h,s.max),g=!!m.ok&&(null===m.value?void 0!==s.value||void 0!==s.invalid:m.value!==s.value),x="inlineBudget"===l.target,v=x&&l.saving,b=(0,i.useRef)(v);(0,i.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&eI(document,c.current)},[v]);let y=(t=[],void 0!==s.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:s.settingsPath,value:s.invalid,default:String(s.default)}}),(n=s.projectOverride)&&t.push(void 0!==n.value?{key:"mcp.codemode.inlineBudget.projectOverride",params:{path:n.settingsPath,value:String(n.value)}}:{key:"mcp.codemode.inlineBudget.projectOverrideDefault",params:{path:n.settingsPath,default:String(s.default)}}),t);return(0,r.jsx)(cU,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),m.ok&&g&&!o&&a(m.value)},children:[(0,r.jsx)("input",{ref:c,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":d("mcp.codemode.inlineBudget"),"aria-describedby":u,"aria-invalid":!m.ok||void 0,value:h,placeholder:String(s.default),readOnly:o,autoComplete:"off",spellCheck:!1,onChange:e=>f(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(c2,{type:"submit",size:"small",disabled:!g||o,children:d("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!m.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:d("mcp.codemode.inlineBudget.invalidDraft",{max:String(s.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.description",{default:String(s.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(e,d)},e.key)),x&&l.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(xu,{error:l.error})]})]})})}let xf=[{kind:"ui",label:"settings.uiFontFamily",placeholder:"settings.uiFontPlaceholder",reset:"settings.resetUiFont",weightLabel:"settings.uiFontWeight"},{kind:"mono",label:"settings.monoFontFamily",placeholder:"settings.monoFontPlaceholder",reset:"settings.resetMonoFont",weightLabel:"settings.monoFontWeight"}];function xm(){let{t:e}=(0,e0.s)(),t=oL();return(0,r.jsx)("div",{className:"settings-font-rows",children:xf.map(n=>{let{kind:i,label:s,placeholder:l,reset:o,weightLabel:a}=n,d=t[`${i}Weight`],c=of.findIndex(e=>e.value===d);return(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,r.jsx)("label",{htmlFor:`settings-font-${i}`,children:e(s)}),(0,r.jsx)("input",{id:`settings-font-${i}`,className:`settings-font-input${"mono"===i?" is-mono":""}`,type:"text",value:t[i],placeholder:e(l),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(a)}: ${d}`,children:e(of[c].label)}),(0,r.jsx)(c2,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(o),"aria-label":e(o),disabled:!t[i]&&400===d,onClick:()=>t.resetFontPreference(i),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:`settings-font-${i}-weight`,type:"range",min:of[0].value,max:of[of.length-1].value,step:100,value:d,"aria-label":e(a),"aria-valuetext":`${d} ${e(of[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function xg(e){let{section:t,size:n=16,strokeWidth:i=1.8}=e,s={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"skills"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m12 2-10 5 10 5 10-5-10-5Z"}),(0,r.jsx)("path",{d:"m2 12 10 5 10-5M2 17l10 5 10-5"})]}):"agents"===t?(0,r.jsxs)("svg",{...s,className:"settings-section-icon is-agent",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"archives"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]}):"mcp"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"7",rx:"2"}),(0,r.jsx)("rect",{x:"3",y:"14",width:"18",height:"7",rx:"2"}),(0,r.jsx)("path",{d:"M7 6.5h.01M7 17.5h.01M11 6.5h6M11 17.5h6"})]}):(0,r.jsx)("svg",{...s,children:(0,r.jsx)("path",{d:"M9 7V2M15 7V2M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0ZM12 19v3"})})}function xx(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:l}=e,{locale:o,setLocale:a,supportedLocales:d,t:c}=(0,e0.s)(),{preference:u,setThemePreference:p}=i5(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=oh(),x=l9(),v=eQ(),[b,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(!1),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[$,E]=(0,i.useState)(null),[I,M]=(0,i.useState)(!1),[T,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)("");(0,i.useEffect)(()=>{N(sL()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>O(e?.enabled===!0)).catch(()=>{})},[]);let _=async()=>{D(!0),H("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{H(c("auth.logoutFailed"))}finally{D(!1)}};(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||y(n)}).catch(t=>{e||S(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||E(!0===n.enabled)}).catch(t=>{e||R(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let U=async e=>{M(!0),R(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);E(!0===i.enabled),t&&n()}catch(e){R(e instanceof Error?e.message:String(e))}finally{M(!1)}},q=async e=>{j(!0),S(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i),t&&(await aI(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{j(!1)}},K=async()=>{if(!A){L(!0),P(null);try{if(!("Notification"in window))throw Error("unsupported or not permitted");let e="default"===Notification.permission?await Notification.requestPermission():Notification.permission;if("granted"!==e||!await uB(o))throw Error("unsupported or not permitted");P({kind:"ok",message:c("settings.pushRegistered")})}catch(e){P({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{L(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("settings.appearance"),className:"settings-theme-options",children:i_.map(e=>{let t=u===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option","data-system":"auto"===e.id||void 0,"data-wide":"contrast-light"===e.id||"contrast-dark"===e.id||"zenburn"===e.id||void 0,children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),"auto"===e.id?(0,r.jsxs)("span",{className:"settings-theme-swatch settings-theme-system","aria-hidden":"true",children:[(0,r.jsx)("span",{"data-theme":"light",className:"settings-theme-chip"}),(0,r.jsx)("span",{"data-theme":"dark",className:"settings-theme-chip"}),(0,r.jsx)("span",{className:"settings-theme-system-name",children:c(e.label)})]}):(0,r.jsx)("span",{className:"settings-theme-swatch","aria-hidden":"true",children:(0,r.jsx)("span",{"data-theme":e.id,className:"settings-theme-fill",children:(0,r.jsx)("span",{className:"settings-theme-name",children:c(e.label)})})}),(0,r.jsx)("span",{className:"sr-only",children:c(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:c("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(xm,{}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:c("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[m,"px"]}),(0,r.jsx)(c2,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:14===m,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:m,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:c("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(c2,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>f(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>f(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.thinkingExpandedDefault")}),(0,r.jsx)(c4,{checked:C,label:c("settings.thinkingExpandedDefault"),onChange:e=>{!function(e){try{window.localStorage.setItem(sR,String(e))}catch{return}window.dispatchEvent(new Event(sA))}(e),N(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(c4,{checked:s,label:c("settings.quoteSelection"),onChange:l})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:c("settings.enterSendMode")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"enter",checked:"enter"===x,onChange:()=>l6("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeEnter")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"ctrlEnter",checked:"ctrlEnter"===x,onChange:()=>l6("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeCtrlEnter")})]})]})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.cacheMissNotices")}),(0,r.jsx)(c4,{checked:!0===$,loading:null===$&&!T||I,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void U(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),T&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:T})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.sidebar")}),(0,r.jsx)("div",{className:"settings-chat-options",children:(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.filesPlacement"),"aria-describedby":"settings-files-placement-description",children:[(0,r.jsx)("span",{children:c("settings.filesPlacement")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"below",checked:"below"===v,onChange:()=>eX("below"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementBelow")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"tab",checked:"tab"===v,onChange:()=>eX("tab"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementTab")})]})]})]})}),(0,r.jsx)("p",{id:"settings-files-placement-description",className:"settings-general-description",children:c("settings.filesPlacementDescription")})]}),b?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.usePowerShell")}),(0,r.jsx)(c4,{checked:b.powerShellEnabled,loading:w,label:c("settings.usePowerShell"),onChange:e=>void q(e)})]}),k&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:k})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:A,onClick:()=>void K(),children:A?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),z&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===z.kind?{color:"var(--accent)"}:void 0,children:z.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("common.language"),className:"settings-language-options",children:d.map(e=>{let t=o===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>a(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),W&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(c2,{variant:"secondary",disabled:F,onClick:()=>void _(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),F?c("auth.loggingOut"):c("auth.logOut")]}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]})]})}let xv={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function xb(e){let{cwd:t,sessionId:n,initialSection:s,onClose:l,onSessionReloaded:o,quoteSelectionEnabled:a,onQuoteSelectionChange:d,projectTrust:c,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h,locale:f}=(0,e0.s)(),[m,g]=(0,i.useState)(s),[x,v]=(0,i.useState)(()=>new Set([m])),b=[{id:"general",label:h("settings.general")},{id:"models",label:h("common.models")},{id:"archives",label:xv[f]??xv.en},{id:"skills",label:h("common.skills")},{id:"agents",label:h("common.agents")},{id:"plugins",label:h("common.plugins")},{id:"mcp",label:h("settings.mcp")}].map(e=>({...e,requiresProject:d7(e.id)})),y=d7(m);(0,i.useEffect)(()=>cr(s),[s]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eE(e)||(e.preventDefault(),l())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[l]);let w=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>(function(e,t){let{restoreTextEntry:n=!0}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.activeElement,i=!!(r&&t&&t.contains(r)),s=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!s||!s.isConnected||!n&&function(e){if(e.isContentEditable)return!0;let t=e.tagName?.toUpperCase();return"TEXTAREA"===t||"INPUT"===t&&!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes((e.type??"text").toLowerCase())}(s))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof s.focus&&s.focus({preventScroll:!0})}})(document,w.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!t&&y&&(g("general"),v(e=>new Set(e).add("general")),cr("general"))},[t,y]);let j=e=>{v(t=>new Set(t).add(e)),g(e),cr(e)},k=(e,t)=>x.has(e)?(0,r.jsx)("div",{hidden:m!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:w,role:"dialog","aria-modal":"true","aria-label":h("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&l()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:h("settings.title")}),(0,r.jsx)("select",{"aria-label":h("settings.title"),value:m,onChange:e=>j(e.target.value),className:"settings-mobile-section-picker",children:b.map(e=>(0,r.jsx)("option",{value:e.id,disabled:e.requiresProject&&!t,children:e.label},e.id))}),(0,r.jsx)("nav",{"aria-label":h("settings.title"),className:"settings-section-tabs",children:b.map(e=>{let n=m===e.id,i=e.requiresProject&&!t;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?h("settings.projectRequired"):e.label,"aria-current":n?"page":void 0,onClick:()=>j(e.id),children:[(0,r.jsx)(xg,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:l,title:h("i18n.close"),"aria-label":h("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[k("general",(0,r.jsx)(xx,{sessionId:n,onSessionReloaded:o,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),k("models",(0,r.jsx)(uF,{embedded:!0,cwd:t,onClose:l})),k("archives",(0,r.jsx)(pg,{embedded:!0,onClose:l})),t&&k("skills",(0,r.jsx)(uY,{embedded:!0,cwd:t,trust:c,onClose:l},t)),t&&k("agents",(0,r.jsx)(u7,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:l,onReloaded:o},t)),t&&k("plugins",(0,r.jsx)(pp,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:l,onReloaded:o},t)),k("mcp",(0,r.jsx)(g8,{embedded:!0,cwd:t,trust:c,onTrustProject:u,onProjectTrustChanged:p,onClose:l},t??""))]})]})})}let xy="project-trust-mcp-status";function xw(e){let{cwd:t,busy:n,error:s,onCancel:l,onConfirm:o,onStatus:a}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(a);return(0,i.useEffect)(()=>{u.current=a},[a]),(0,i.useEffect)(()=>{let e=!0,n=!1;c({state:"loading"});let r=new AbortController,i=window.setTimeout(()=>{n=!0,r.abort()},1e4);return fetch(`/api/project-trust?cwd=${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"}).then(async t=>{let n=await t.json();if(!e)return;let r=function(e,t,n){let r=Array.isArray(n.mcpServers)?{mcpServers:n.mcpServers,...n.mcpFile?{mcpFile:n.mcpFile}:{},...void 0!==n.mcpError?{mcpError:n.mcpError}:{}}:void 0;if(e&&!n.error&&r&&"boolean"==typeof n.requiresTrust){let e;return{state:"loaded",listing:r,status:(e={requiresTrust:n.requiresTrust,trusted:n.trusted,decision:n.decision,inherited:n.inherited},void 0!==n.decisionPath&&(e.decisionPath=n.decisionPath),void 0!==n.decisionError&&(e.decisionError=n.decisionError),e)}}return"trust-unreadable"===n.reason&&r?{state:"loaded",listing:r,statusError:n.error??`HTTP ${t}`}:{state:"failed",error:n.error??`HTTP ${t}`,reason:n.reason}}(t.ok,t.status,n);c(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&c(n?{state:"failed",timedOut:!0}:{state:"failed",error:t instanceof Error?t.message:String(t)})}).finally(()=>window.clearTimeout(i)),()=>{e=!1,window.clearTimeout(i),r.abort()}},[t]),(0,r.jsx)(xj,{cwd:t,busy:n,error:s,listing:d,onCancel:l,onConfirm:o})}function xj(e){let{cwd:t,busy:n,error:s,listing:l,onCancel:o,onConfirm:a}=e,{t:d}=(0,e0.s)(),c="loading"===l.state,u="loaded"===l.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(l.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),f=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current=n,f.current=o},[n,o]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||f.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eE(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",i,!0),s=()=>e.removeEventListener("keydown",i,!0),()=>{s(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:d("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:d("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:py(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===l.state&&void 0!==l.statusError&&(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:d("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:py(l.statusError)})]}),(0,r.jsx)(xS,{listing:l})]})]}),s&&(0,r.jsx)(xk,{error:s}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:o,disabled:n,children:d(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?xy:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function xk(e){let{error:t}=e,{t:n}=(0,e0.s)(),i=void 0!==t.reason&&"internal"!==t.reason;return(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[n(i?`mcp.reason.${t.reason}`:"trust.trustFailed"),!i&&(0,r.jsx)("code",{className:"project-trust-error-detail",children:py(t.error)})]})}function xS(e){let{listing:t}=e,{t:n}=(0,e0.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:xy,role:"status",className:"project-trust-mcp-status",children:n("trust.mcp.loading")});if("failed"===t.state||void 0!==t.listing.mcpError||!t.listing.mcpFile){let e;e="failed"===t.state?t.reason&&"internal"!==t.reason?n(`mcp.reason.${t.reason}`):t.error:t.listing.mcpError;let i="failed"===t.state&&t.timedOut;return(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(i?"trust.mcp.timedOut":"trust.mcp.loadFailed")}),e&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:py(e)})]})}let{mcpFile:i,mcpServers:s}=t.listing;return i.exists||0!==i.problems.length?(0,r.jsxs)("section",{className:"project-trust-mcp","aria-labelledby":"project-trust-mcp-title",children:[(0,r.jsx)("div",{id:"project-trust-mcp-title",className:"project-trust-mcp-title",children:n("trust.mcp.title")}),s.length>0&&(0,r.jsx)("p",{className:"project-trust-mcp-intro",children:n("trust.mcp.intro")}),(0,r.jsx)(xC,{file:i}),0===s.length&&0===i.problems.length&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.none")}),s.some(e=>!e.validated)&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.unchecked")}),s.length>0&&(0,r.jsx)("ul",{className:"project-trust-mcp-list",children:s.map(e=>(0,r.jsx)(xE,{server:e},e.name))})]}):null}function xC(e){let{file:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=pM(e,t.realPath);return(0,r.jsxs)("div",{className:"project-trust-mcp-problem",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(`mcp.fileProblem.${e.reason}`)}),i&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:i})]},e.reason)})})}function xN(e){let{fields:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=pN(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function x$(e){let{server:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)(r.Fragment,{children:pI(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=pN(i);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n("mcp.server.variableIn",{variable:t,field:n(s.key,s.params)})},`${t}\0${i.kind}\0${i.name??""}`)})})}function xE(e){let t,{server:n}=e,{t:i}=(0,e0.s)(),s=pS(n),l=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:py(n.name)}),n.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:i(`mcp.transport.${n.transport}`)})]}),void 0!==s&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:s}),void 0!==n.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("trust.mcp.cwd",{path:py(n.cwd)})}),pC(n)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:py(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(xN,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),l&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(xN,{fields:n.commandFields})]}),l&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(p$(n))," ",(0,r.jsx)(x$,{server:n})]}),n.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.replacesGlobal")}),n.override&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i((t=pE(n.override.keys)).key,t.params)}),n.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:i("mcp.server.masked")})]})}function xI(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function xM(e){let t=e,n=t.branchPreview,r=xI(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&xI(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function xT(e){if(e.length>1)return!0;let t=[...e];for(;t.length>0;){let e=t.pop();if(e.children.length>1)return!0;for(let n of e.children)t.push(n)}return!1}function xR(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:l,onSelect:o}=e,{node:a,skipped:d,branchPreview:c,labelEntry:u}=xM(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),f=c?.text??function(e){if("message"===e.type&&xI(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(u),m=c?c.role??null:xI(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:o?"pointer":"default"},onClick:o?()=>o(a.entry.id):void 0,children:[l.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),d>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",d]}),(0,r.jsx)("span",{style:{fontSize:11,color:p?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:p?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:f})]}),a.children.map((e,t)=>(0,r.jsx)(xR,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...l,!s],onSelect:o},e.entry.id))]})}function xA(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:l,containerRef:o,open:a,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,e0.s)(),[m,g]=(0,i.useState)(!1),x=void 0!==a?a:m,v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!l)return;let e=o?.current??v.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,l,o]);let w=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),j=(0,i.useCallback)(e=>{s(e)},[s]),k=h?void 0:j,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:f("i18n.branchesLockedWhileRunning")}),C=c?xT(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=xM(e[0]).node;return t.children.length>1?t.children:[]}(t),$=!C&&N.length>0,E=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:$?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return l?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>d?d():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":x,children:[E,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:$?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(xR,{node:e,activePathIds:w,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:k},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[E,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),I]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:$?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(xR,{node:e,activePathIds:w,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:k},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??f("i18n.noBranches")})})]})}function xL(e){let{loading:t,prompt:n,translate:i}=e;return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":i("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:n?(0,r.jsx)("div",{className:"system-prompt-text",children:n}):(0,r.jsx)("div",{className:"system-prompt-empty",children:i(""===n?"system.empty":t?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
11
+ ${r=null===a.number?a.marker:`${String(Number(a.number)+1).padStart(a.number.length,"0")}${a.delimiter}`,`${a.indent}${r}${a.spacing}${a.task?"[ ] ":""}`}`}}(e.value,e.selectionStart,e.selectionEnd);n&&(t.preventDefault(),e.setSelectionRange(n.start,n.end),document.execCommand(n.text?"insertText":"delete",!1,n.text))};return e.addEventListener("beforeinput",t),()=>e.removeEventListener("beforeinput",t)},[]),(0,i.useEffect)(()=>()=>{tu.current.forEach(o5)},[]);let tb=(0,i.useCallback)(async e=>{if(ev.length||!e.startsWith("/")||!J)return!1;if(eq.current)return!0;eq.current=!0,eU(!0);try{var t,n;let r=await J(e);if(!r.handled)return!1;return r.error||(t=tc.current,n=tu.current.length,0!==n||t.trim()!==e)||tx(),!0}finally{eq.current=!1,eU(!1)}},[ev.length,tx,J]),ty=(0,i.useCallback)(async()=>{var e;let t=ec.trim();(t||ev.length)&&(X?.(),(!m||oG(e=t)||l0(e))&&await tb(t)||m||(tx(),u(t,ev.length?ev:void 0)))},[ec,ev,m,tb,u,tx,X]),tj=!er&&ec.startsWith("/")&&!/\s/.test(ec.slice(1))?ec.slice(1).toLowerCase():null,tk=(()=>{var e;let t,n;return null===tj?[]:(e=[...m?oY.filter(e=>e.availableWhileStreaming):oY,...K??[]],((n=(t=e.map(e=>{let t,n;return{command:e,rank:(t=e.name.toLowerCase(),(n="skill"===e.source&&t.startsWith("skill:")?t.slice(6):t)===tj||t===tj?0:n.startsWith(tj)||t.startsWith(tj)?1:t.includes(tj)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return o1(t,ei).toLowerCase().includes(tj)})).sort((e,t)=>e.rank-t.rank||o0[e.command.source]-o0[t.command.source]||oB.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:tC,groups:tN}=(n=0,{commands:(s=oX.map(e=>{let t=tk.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!o2(e,e1)),...t.filter(e=>o2(e,e1))]:t;return{source:e,items:r.map(e=>({command:e,index:n++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:s}),tE=1===tk.length?ei(tj?"chat.match":"chat.command"):ei(tj?"chat.matches":"chat.commands",{count:tk.length}),tI=!!ec.trim()||ev.length>0,tM=er||ea&&m,tT=ev.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(g,b)&&!eW;(0,i.useEffect)(()=>{0===ev.length&&eO(!1)},[ev.length]);let tR=(0,i.useCallback)((e,t)=>{if(!et)return void eM(null);let n=t??e.length;eM(tL(e.slice(0,n)))},[et]),tA=eI?.query??null,tW=i.useMemo(()=>null!==tA&&eK&&eK.cwd===et?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:tP(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:tP(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||tz(e.entry.path)-tz(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eK.entries,tA):[],[tA,eK,et]),tO=!!(tA&&eK?.truncated&&eK.cwd===et);(0,i.useEffect)(()=>{if(!tO||!et||!tA)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(et)}&q=${encodeURIComponent(tA)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>eG({cwd:et,query:tA,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tO,tA,et]);let tF=tO&&null!==eY&&eY.cwd===et&&eY.query===tA,tD=tF?eY.matches:tW,tB=null===eI?null:`${eI.start}:${+!!eI.quoted}:${eI.query}`;(0,i.useEffect)(()=>{if(null===tB){eR(!1),eP(0);return}eR(!0),eP(0)},[tB]);let tH=null!==eI;(0,i.useEffect)(()=>{if(!tH||!et)return;let e=to.current;e&&e.cwd===et&&Date.now()-e.fetchedAt<1e4||ta.current===et||(ta.current=et,eJ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(et)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eV({cwd:et,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>tz(e.path)-tz(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),to.current={cwd:et,fetchedAt:Date.now()}}).catch(()=>{to.current=null}).finally(()=>{ta.current=null,eJ(!1)}))},[tH,et]);let t_=(0,i.useCallback)(e=>{if(!eI)return;let t=e2.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eI.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eI.quoted),s=eI.start+i.cursorOffset;oU(t,eI.start,r,i.text,i.cursorOffset),eM(tL(t.value.slice(0,s)))},[eI]);(0,i.useEffect)(()=>{ez>=tD.length&&eP(Math.max(0,tD.length-1))},[tD.length,ez]),(0,i.useEffect)(()=>{ts.current.length=tD.length},[tD.length]),(0,i.useEffect)(()=>{eT&&ts.current[ez]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ez,eT]),(0,i.useEffect)(()=>{eB>=U.length&&eH(Math.max(0,U.length-1))},[U.length,eB]),(0,i.useEffect)(()=>{tl.current.length=U.length},[U.length]),(0,i.useEffect)(()=>{eF&&tl.current[eB]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eB,eF]);let tU=(0,i.useCallback)(e=>{eu(e),eD(!1),eH(0),eM(null),requestAnimationFrame(()=>{let t=e2.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),oq(t))})},[]),tq=(0,i.useCallback)(e=>{let t=`/${e.name} `;eu(t),eS(!1),eN(0),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),oq(e))})},[]),tK=(0,i.useCallback)(e=>{let t=ec.trim();if(!t&&!ev.length)return;X?.();let n=ev.length?ev:void 0,r=()=>{if(t.startsWith("/")&&Q){tx(),Q(t,"steer"===e?"steer":"followUp",n);return}tx(),"steer"===e&&h?h(t,n):"followup"===e&&f&&f(t,n)};!ev.length&&J&&oG(t)?tb(t):!ev.length&&J&&l0(t)?tb(t).then(e=>{e||r()},()=>r()):r()},[ec,ev,J,Q,h,f,tx,X,tb]),tV=(0,i.useCallback)(e=>{let t=tC.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eC-1);if("right"===e)return Math.min(t,eC+1);let n=tr.current[eC];if(!n)return"down"===e?Math.min(t,eC+1):Math.max(0,eC-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,l=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eC)continue;let t=tr.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-s;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<o&&(l=n,o=d)}return l>=0?l:"down"===e?Math.min(t,eC+1):Math.max(0,eC-1)},[tC.length,eC]),tZ=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ea||"ctrlEnter"===ed?n&&(e.ctrlKey||e.metaKey):n,i=ea?r:n,s=Date.now()-e7.current<100,l=e9.current||t.isComposing||229===t.keyCode;if(i&&(l||s)){s&&e.preventDefault();return}if(eF&&!l){if("ArrowDown"===e.key){e.preventDefault(),eH(e=>Math.min(Math.max(0,U.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eH(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eD(!1);return}if(("Tab"===e.key||i)&&U[eB]){e.preventDefault(),tU(U[eB]);return}}if(ek&&null!==tj){if("ArrowDown"===e.key){e.preventDefault(),eN(tV("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eN(tV("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eN(tV("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eN(tV("left"));return}if("Escape"===e.key){e.preventDefault(),eS(!1);return}let t=tC[eC];if("Tab"===e.key&&t){e.preventDefault(),tq(t);return}if(i&&t){e.preventDefault(),r&&function(e,t,n){if("builtin"===t.source)return"builtin"===t.source&&e.trim()===`/${t.name}`&&(!n||!0===t.availableWhileStreaming);return lQ(t)&&l0(e)}(ec,t,m)?(eS(!1),ty()):tq(t);return}}if(eT&&null!==eI&&!l){if("ArrowDown"===e.key){e.preventDefault(),eP(e=>oH(e,tD.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eP(e=>oH(e,tD.length,-1));return}if("Escape"===e.key){e.preventDefault(),eR(!1);return}if(("Tab"===e.key||i)&&tD[ez]){e.preventDefault(),t_(tD[ez]);return}}if("ArrowUp"===e.key&&!l&&!m&&U.length>0&&0===ec.trim().length){e.preventDefault(),eS(!1),eR(!1),eH(U.length-1),eD(!0);return}if("Escape"===e.key&&!l&&m&&p){e.preventDefault(),p();return}r&&(e.preventDefault(),m&&(h||f)?tK(e.altKey&&f||!h?"followup":"steer"):ty())},[ea,ed,m,h,f,p,ek,tj,tC,eC,tq,tK,ty,tV,eT,eI,tD,ez,t_,eF,U,eB,tU,ec]),tJ=(0,i.useCallback)(()=>{let e=e2.current;e&&oq(e)},[]),tY=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!er&&t.length){e.preventDefault(),th(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:l,occurrence:o}of t){if(!s||!l)continue;let t=0;for(let n=0;n<=o&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let a=s.replace(/([\\[\]])/g,"\\$1"),d=l.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let l=e.currentTarget,o=l.selectionStart,a=l.value.slice(0,o)+s+l.value.slice(l.selectionEnd);e.preventDefault(),tc.current=a,eu(a),eD(!1),tR(a,o+s.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(o+s.length,o+s.length)})},[er,th,tR]);(0,i.useEffect)(()=>{if(null===tj){eS(!1),eN(0),tt.current=!1;return}eS(!0),eN(0),!tt.current&&Z&&(tt.current=!0,Promise.resolve(Z()).catch(()=>{tt.current=!1}))},[tj,Z]),(0,i.useEffect)(()=>{if(!ek||!et)return;let e=!1;return eQ({cwd:et,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(et)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;eQ({cwd:et,values:n})}).catch(()=>{e||eQ({cwd:et,values:{}})}),()=>{e=!0}},[ek,et]),(0,i.useEffect)(()=>{eC>=tC.length&&eN(Math.max(0,tC.length-1))},[tC.length,eC]),(0,i.useEffect)(()=>{tr.current.length=tC.length},[tC.length]),(0,i.useEffect)(()=>{ek&&tr.current[eC]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eC,ek]),(0,i.useLayoutEffect)(()=>{if(!ek||null===tj)return void eE(null);let e=tn.current;if(e)return oK(e,e=>{eE(t=>t===e?t:e)})},[ek,tj]),(0,i.useLayoutEffect)(()=>{if(!eT||null===eI)return void eL(null);let e=ti.current;if(e)return oK(e,e=>{eL(t=>t===e?t:e)})},[eT,eI]);let tG=b&&b.length>0?b.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(v??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),tX=R?Math.max(0,R.tokensBefore-R.estimatedTokensAfter):0,tQ=R?`${R.reason&&"manual"!==R.reason?`${R.reason[0].toUpperCase()}${R.reason.slice(1)} `:ei("chat.compacted")} ${oJ(R.tokensBefore)} -> ${oJ(R.estimatedTokensAfter)} tokens (${ei("chat.tokensSaved",{saved:oJ(tX)})})`:null,t0=z&&"auto"!==z?z:null,t1="auto"!==(l=t0??"auto")&&F?F[l]??l:l,t2=Object.entries(oD).find(e=>{let[,t]=e;return t===(A??"configured")})?.[0]??"configured",t4="chat-only"===t2?ei("chat.chatOnly"):t2;(0,i.useEffect)(()=>{let e=e=>{e4.current&&!e4.current.contains(e.target)&&eh(!1),e8.current&&!e8.current.contains(e.target)&&em(!1),e3.current&&!e3.current.contains(e.target)&&ex(!1),!e5.current||e5.current.contains(e.target)||e2.current?.contains(e.target)||eD(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eh(!1)},[m]);let t8=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t8.current=performance.now()}},[m]);let t3=e=>{var t,n;return t=e.detail,n=performance.now()-t8.current,t>0&&n<600};return(0,i.useEffect)(()=>{ea||ex(!1)},[ea]),(0,r.jsxs)("fieldset",{disabled:e_,"aria-busy":e_,className:er?void 0:"chat-input-shell",style:{...er?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:er?0:"0 16px 8px",paddingRight:er?0:ea?16:52,opacity:e_?.5:1,transition:"opacity 0.15s"},children:[!er&&(0,r.jsx)("input",{ref:e6,type:"file",accept:en?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tf}),(0,r.jsxs)("div",{style:{...er?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(o7,{cwd:w}),(0,r.jsx)(ae,{error:y}),(0,r.jsx)(at,{warnings:j}),tT&&(o=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(o9,{tone:"warning",title:ei("chat.imageNotSupportedTitle"),body:ei("chat.imageNotSupportedBody",{model:o?.name||g?.modelId||""}),onClose:()=>eO(!0)})),(_?.steering.length??0)+(_?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:72,marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ei("chat.queued",{count:(_?.steering.length??0)+(_?.followUp.length??0)})}),q&&(0,r.jsxs)("button",{onClick:q,title:ei("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),ei("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[_?.steering.map((e,t)=>(0,r.jsx)(o6,{kind:"steer",text:e},`steer-${t}`)),_?.followUp.map((e,t)=>(0,r.jsx)(o6,{kind:"follow-up",text:e},`followup-${t}`))]})]}),H&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),ei("chat.retrying",{attempt:H.attempt,max:H.maxAttempts}),H.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",H.errorMessage]})]}),tQ&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),tQ]}),M&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,marginBottom:8,padding:T?"3px 3px 3px 10px":"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,padding:T?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:M}),T&&(0,r.jsx)(tw,{onClick:T,title:ei("chat.dismissCompactError")})]}),ev.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ev.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(iF,{src:e.previewUrl,children:(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tm(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eF&&U.length>0&&(0,r.jsxs)("div",{ref:e5,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:ei("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:U.map((e,t)=>{let n=t===eB;return(0,r.jsxs)("button",{ref:e=>{tl.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tU(e)},onMouseEnter:()=>eH(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),ek&&null!==tj&&(0,r.jsxs)("div",{ref:tn,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e$?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${e$}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:V?ei("chat.loadingCommands"):ei("chat.slashCommands",{label:tE})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:V||0!==tk.length?tN.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:ei(oQ[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(e=>{let{command:t,index:n}=e,i=n===eC,s=o2(t,e1);return(0,r.jsxs)("button",{ref:e=>{tr.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tq(t)},onMouseEnter:()=>eN(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${i?"var(--accent)":"var(--border)"}`,borderRadius:7,background:i?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:i?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",t.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ei("chat.dormant")})]}),t.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:o1(t,ei)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ei("chat.noCommands")})})]}),eT&&null!==eI&&(a=eZ&&(!eK||eK.cwd!==et),d=1===tD.length?ei("chat.match"):ei("chat.matches",{count:tD.length}),c=eK?.truncated&&!tF?eI.query?ei("chat.searchingAll"):ei("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:ti,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eA?"min(48vh, 400px)":`min(48vh, 400px, ${eA}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:a?ei("chat.loadingFiles"):ei("chat.files",{label:d,hint:c})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ei("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tD.length?tD.map((e,t)=>{let n=t===ez,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{ts.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eP(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(tS,{size:14}):t$(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tO&&!tF?ei("chat.searching"):ei("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:tM?"column":"row",gap:8,alignItems:tM?"stretch":"center",background:"var(--bg)",border:er?"none":`1px solid ${ew?"var(--tool-bg)":m&&(h||f)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!er,padding:er?0:ea?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:er?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:e2,className:"chat-input-textarea","aria-label":er?ei("chat.quoteQuestion"):void 0,value:ec,onChange:e=>{tc.current=e.target.value,eu(e.target.value),eD(!1),tR(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tR(t.value,t.selectionStart)},onKeyDown:tZ,onCompositionStart:()=>{e9.current=!0},onCompositionEnd:e=>{e9.current=!1,e7.current=Date.now();let t=e.currentTarget;tR(t.value,t.selectionStart)},onInput:tJ,onPaste:tY,placeholder:I?ei("chat.compactingPlaceholder"):m&&(h||f)?ei("chat.steerPlaceholder"):m?ei("chat.agentPlaceholder"):ei("chat.messagePlaceholder"),rows:1,style:{flex:tM?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.6,fontFamily:"inherit",minHeight:er?96:24,maxHeight:200,overflow:"auto"}}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[h&&(0,r.jsxs)("button",{onClick:()=>tK("steer"),disabled:!tI,title:ei("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tI?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tI?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tI?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),ei("chat.steer")]}),f&&(0,r.jsxs)("button",{onClick:()=>tK("followup"),disabled:!tI,title:`${ei("chat.followUpHint")} (${ea?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":ea?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tI?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tI?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tI?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),ei("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:ty,disabled:!ec.trim()&&!ev.length,title:ei("chat.send"),"aria-label":ei("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ea?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ec.trim()||ev.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ec.trim()||ev.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ec.trim()||ev.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ec.trim()||ev.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),!ea&&ei("chat.send")]})]})]}),ew&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ej?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ei("chat.shell")," \xb7 ",ej?ei("chat.outputLocal"):ei("chat.outputModel")]}),!er&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ea?4:8,display:ea?"grid":"flex",gridTemplateColumns:ea?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ea?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>e6.current?.click(),title:ei("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ev.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ev.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ev.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(tG.length>0||g||y)&&k&&(0,r.jsx)(oW,{options:tG,value:g,onChange:k,onReselect:k,disabled:m,busy:S,isAutoSelection:x,defaultValue:C,onSetDefault:N})]}),!ea&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e3,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ea?0:"auto"},children:[ea&&(0,r.jsx)("button",{type:"button",title:eg?void 0:ei("chat.moreControls"),"aria-label":ei("chat.moreControls"),"aria-expanded":eg,"aria-hidden":eg||void 0,tabIndex:eg?-1:void 0,onClick:()=>{ex(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:32,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eg?"default":"pointer",fontSize:12,fontWeight:500,visibility:eg?"hidden":"visible",pointerEvents:eg?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eg||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eg||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:ei("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ea?eg?"flex":"none":"flex",alignItems:"center",gap:ea?1:2,...ea?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[W&&(0,r.jsxs)("div",{ref:e8,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>em(e=>!e),title:m?ei("chat.currentReasoning",{level:t1}):ei("chat.changeReasoning",{level:t1}),"aria-label":ei("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:ef?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=ef?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ea?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:oV.filter(e=>!O||"auto"===e||O.includes(e)).map(e=>{let t="auto"===e?P:!P&&t0===e,n=ei(oZ[e]),i="auto"!==e&&F?F[e]:void 0,s=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)(oP,{active:t,onSelect:()=>{if(em(!1),"auto"===e){P||W("auto");return}(!t||P)&&W(e)},gutter:!!B,star:B&&"auto"!==e?{isDefault:D===e,saveLabel:ei("chat.saveDefaultThinking"),defaultLabel:ei("chat.defaultThinking"),onSave:()=>{em(!1),B(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,l&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!m&&L&&(0,r.jsxs)("div",{ref:e4,style:{position:ea?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t3(e)||eh(e=>!e)},disabled:m,title:ei("chat.changeToolPreset")+`: ${t4}`,"aria-label":ei("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:ep?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:m?"not-allowed":"pointer",fontSize:12,opacity:m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ep?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("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"})}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t4})]}),ep&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ea?"calc(100vw - 16px)":void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:oF.map(e=>{let t,n=oD[e],i=(A??"configured")===n;return t="configured"===e?ei("chat.configuredTools"):"chat-only"===e?ei("chat.chatOnly"):"read-only"===e?ei("chat.readOnlyTools",{count:4}):"default"===e?ei("chat.builtInTools",{count:4}):ei("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eh(!1),i||L(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),(!m||I)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:I?E:e=>{t3(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ea?"0 6px":"8px 12px",width:ea?"auto":void 0,height:32,background:I?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:I?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=I?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=I?"#ef4444":"var(--text-muted)"},title:I?ei("chat.stopCompaction"):ei("chat.compactContext"),"aria-label":I?ei("chat.stopCompaction"):ei("chat.compactContext"),children:I?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ea||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ei("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:p,title:ei("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),ei("chat.stop")]}),void 0!==G&&(0,r.jsx)("button",{onClick:G,title:Y?ei("chat.disableSound"):ei("chat.enableSound"),"aria-label":Y?ei("chat.disableSound"):ei("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:Y?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:Y?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=Y?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=Y?"1":"0.55"},children:Y?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ea&&eg&&(0,r.jsx)("button",{type:"button",title:ei("chat.collapseControls"),"aria-label":ei("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eh(!1),em(!1),ex(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]})]})]})})),ar="pi-web:minimap-preview-locked";function ai(){try{return window.localStorage}catch{return null}}function as(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ai();if(!e)return!1;try{return"true"===e.getItem(ar)}catch{return!1}}var al=n(88576),ao=n.n(al);function aa(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:ao().heading,"data-level":t,"data-preview-heading-index":i??void 0,disabled:null===i||!s,onClick:e=>{e.stopPropagation(),null!==i&&s?.(i)},children:n})}let ad=[...iE??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],ac=[[r8.A,{throwOnError:!1,strict:!1}]];function au(e){let t=e?.properties,n=t?.dataPreviewHeadingIndex??t?.["data-preview-heading-index"];return"number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):null}let ap=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,l=(0,i.useMemo)(()=>ih(t),[t]);return t?(0,r.jsx)("div",{className:ao().outline,children:(0,r.jsx)(rY.oz,{remarkPlugins:ad,rehypePlugins:ac,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(aa,{level:1,headingIndex:au(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(aa,{level:2,headingIndex:au(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(aa,{level:3,headingIndex:au(i),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,r.jsx)("button",{type:"button",className:ao().paragraph,onClick:s,children:t})},blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})}},children:l})}):null}),ah=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:l,onRevealHistory:o,turnsBefore:a}=e,{t:d}=(0,e0.s)(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(600),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(as),[j,k]=(0,i.useState)(null),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),N=(0,i.useRef)([]),$=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),E=(0,i.useRef)(null),I=(0,i.useRef)(new Map),M=(0,i.useRef)(null),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(t);A.current=t;let L=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-12-48);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*s)/n})),gap:s,fillsHeight:i<=50}})(p,g),[p,g]),{nodes:z,gap:P}=L;$.current=L;let W=(0,i.useCallback)(e=>{T.current={index:e,until:Date.now()+1600},m(e)},[]),O=(0,i.useCallback)((e,t)=>{let n=T.current;if(n&&Date.now()<n.until)return void m(n.index);T.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void m(null);let i=e.scrollTop+.3*e.clientHeight;m(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),F=(0,i.useCallback)(()=>{let e=s.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=N.current;u(t>20),O(e,n)},[s,O]),D=(0,i.useRef)(null),B=(0,i.useCallback)(()=>{D.current||(D.current=setTimeout(()=>{D.current=null;let e=s.current,t=C.current;if(!e||!t)return;let r=l.current,i=e.getBoundingClientRect(),o=[],a=0,d=null,c=n();for(let t of c?[...A.current,c]:A.current){let n=rj(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[a];if(a++,n){d=null;let n=s?.getBoundingClientRect();d={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null,toolCount:0},o.push(d);continue}if(!d)continue;d.toolCount+="assistant"===t.role&&Array.isArray(t.content)?t.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let l=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=rE(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);l&&d.assistantPreviews.push({markdown:l,element:s})}let p=o.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));x(t.clientHeight),N.current=p,h(p),u(e.scrollHeight-e.clientHeight>20),O(e,p);let f=R.current,m=f?p[f.nodeIndex]:null;if(f&&m){let t=void 0===f.assistantIndex?null:m.targetTurn.assistantPreviews[f.assistantIndex],n=m.targetTurn.scrollTop;if("assistant"===f.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===f.target){let r=void 0===f.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(f.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;R.current=null,W(m.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,W,l,s,O]);(0,i.useEffect)(()=>{let e=s.current;if(e)return e.addEventListener("scroll",F,{passive:!0}),()=>e.removeEventListener("scroll",F)},[s,F]),(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=()=>{B(),F()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),D.current&&(clearTimeout(D.current),D.current=null)}},[B,s,F]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{B(),F()},50);return()=>clearTimeout(e)},[t.length,B,F]);let H=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(W(e.index),null===e.targetTurn.scrollTop){R.current={nodeIndex:e.index,target:"user"},o();return}let r=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:r,behavior:t})},[W,o,s]),_=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;let r=e.targetTurn.assistantPreviews[t]?.element;if(!r){R.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},o();return}let i=n.getBoundingClientRect(),l=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;W(e.index),n.scrollTo({top:Math.max(0,l),behavior:"smooth"})},[W,o,s]),U=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=$.current,i=C.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),l=t[0].topRatio*i,o=n>0?Math.round((s-l)/n):0,a=Math.max(0,Math.min(t.length-1,o)),d=t[a];if(!r&&Math.abs(s-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),q=(0,i.useCallback)((e,t,n)=>{let r=s.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){R.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},o();return}let l=i.querySelectorAll("h1, h2, h3").item(n);if(!l)return;let a=r.getBoundingClientRect(),d=l.getBoundingClientRect().top-a.top+r.scrollTop-.3*r.clientHeight;W(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[W,o,s]),K=(0,i.useCallback)(()=>{M.current&&(clearTimeout(M.current),M.current=null)},[]),V=(0,i.useCallback)(()=>{y||(K(),b(!0))},[K,y]),Z=(0,i.useCallback)(()=>{let e=!y;w(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ai();if(t)try{t.setItem(ar,String(e))}catch{}}(e),e&&(K(),b(!1),k(null))},[K,y]),J=(0,i.useCallback)(()=>{K(),M.current=setTimeout(()=>{M.current=null,b(!1),k(null)},250)},[K]);(0,i.useEffect)(()=>()=>K(),[K]);let Y=(0,i.useCallback)(e=>{if(!c)return;S.current=!0,V();let t=e.currentTarget.getBoundingClientRect();k(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=U(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&H(r,n)};n(e.clientY,"smooth");let r=e=>{S.current&&n(e.clientY,"auto")},i=()=>{S.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[U,H,V,c]),G=null===j?null:U(j),X=G?.index??null;if((0,i.useEffect)(()=>{if(!v||null===X)return;let e=E.current,t=I.current.get(X);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[p,v,X]),!c)return null;let Q=Math.max(1,(z.length>0?z[z.length-1].topRatio*g:12)-12);return(0,r.jsxs)("div",{ref:C,onMouseDown:Y,onMouseEnter:V,onMouseLeave:J,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();k((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[a>0&&(0,r.jsx)("div",{"data-minimap-earlier":"",style:{position:"absolute",left:"50%",top:0,height:12,width:1,background:"repeating-linear-gradient(to bottom, var(--text-dim) 0 2px, transparent 2px 4px)",transform:"translateX(-50%)",zIndex:0}}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:Q,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),z.map(e=>{let t=v&&G?.index===e.index,n=f===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,P),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),(0,r.jsx)("button",{type:"button",className:ao().lock,"data-minimap-lock":y?"on":"off","aria-pressed":y,title:d(y?"chatMinimap.unlockPreview":"chatMinimap.lockPreview"),"aria-label":d("chatMinimap.lockPreview"),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Z()},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),y?(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,r.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})}),v&&p.length>0&&(0,r.jsxs)("div",{ref:E,className:ao().preview,"data-minimap-preview-box":"",onMouseEnter:V,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[a>0&&(0,r.jsx)("button",{type:"button",className:ao().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:d("chatMinimap.earlierTurns",{count:a})}),p.map(e=>{var t;let n=X===e.index;return(0,r.jsxs)("div",{ref:t=>{t?I.current.set(e.index,t):I.current.delete(e.index)},className:ao().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:ao().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(a+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:ao().toolBadge,role:"img",title:d("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":d("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,r.jsxs)("div",{className:ao().content,children:[(0,r.jsx)("button",{type:"button",className:ao().user,"data-minimap-preview-user":e.index,onClick:()=>{H(e,"smooth")},children:(0,r.jsx)("span",{className:ao().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:ao().assistant,children:[(0,r.jsx)("button",{type:"button",className:ao().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>_(e,n),"aria-label":d("chatMinimap.locateAssistant"),title:d("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(ap,{markdown:t.markdown,onAnswerClick:()=>_(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]})});var af=n(42790);function am(e){let{text:t}=e,n=(0,i.useMemo)(()=>new af.v().ansi_to_html(t).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="'),[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function ag(e){let t,n,s,{widgets:l,children:o}=e,{t:a}=(0,e0.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>l.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[f,m]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(l.map(e=>[e.key,[...e.lines]])),n=(e=c.current,e?Array.from(t,t=>{let[n,r]=t,i=e.get(n);return i&&i.length===r.length?r.some((e,t)=>e!==i[t])?n:null:i?n:null}).filter(e=>null!==e):[]);for(let[e,n]of(c.current=t,u.current))t.has(e)||(clearTimeout(n),u.current.delete(e));for(let e of(m(e=>{let r=new Set(Array.from(e).filter(e=>t.has(e)));for(let e of n)r.add(e);return r.size===e.size&&Array.from(r).every(t=>e.has(t))?e:r}),n)){let t=u.current.get(e);t&&clearTimeout(t),u.current.set(e,setTimeout(()=>{u.current.delete(e),m(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[l]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===l.length)return null;let g=l.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=l.indexOf(g),n=`${d}-trigger-${t}`,s=`${d}-panel-${t}`,(0,r.jsxs)("section",{id:s,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(am,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":a("chat.extensionWidgets"),children:l.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,s=f.has(e.key),l=a(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=a("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${d}-trigger-${t}`,u=`${d}-panel-${t}`,p=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${s?" is-updating":""}`,"aria-controls":u,"aria-expanded":i,"aria-label":`${o}: ${e.key}, ${l}`,title:`${e.key} - ${o} - ${i?a("i18n.collapse"):a("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${s?" is-updating":""}`,"aria-label":`${o}: ${e.key}, ${l}`,title:`${e.key} - ${o}`,children:p},e.key)})}),o]})]})}let ax="command:";function av(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,l=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.key.localeCompare(t.key))){let e=n.text.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim(),r=function(e){if(!e.startsWith(ax))return null;let t=e.slice(ax.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=rf(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else rf(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===l.length&&0===n.length)return null;let o=l.some(e=>"command"===e.kind),a=l.map(e=>"text"===e.kind?rf(e.text):e.label).join(" "),d=l.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,r.jsx)("span",{className:"extension-status-text",children:l.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(am,{text:e.text})},t):(0,r.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!i||s,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>i?.(e.command),children:e.label},t))})}):null;return(0,r.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${l.length>0?" has-status":""}${o?" has-commands":""}`,children:n.length>0?(0,r.jsx)(ag,{widgets:n,children:d}):d})}function ab(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function ay(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function aw(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function aj(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function ak(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ak(e)||"toolCall"!==e.type)return null;let n={type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=ak(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ak(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}function aC(e){if(!e||"object"!=typeof e)return null;let{reason:t,cwd:n}=e;return"cwd-missing"===t&&"string"==typeof n&&n?n:null}class aN extends Error{constructor(e,t,n,r,i){super(e),this.status=t,this.code=n,this.accepted=r,this.missingCwd=i,this.name="AgentCommandError"}}function a$(e){return e instanceof aN&&"prompt_rejected"===e.code&&!1===e.accepted}function aE(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function aI(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new aN(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,aC(r)??void 0);return r.data}function aM(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let aT=new WeakMap;function aR(e){let t,n=aT.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return aT.set(e,t),t}function aA(e){let t=aM().get(e);return t?Date.now()-t.savedAt>6e5?(aM().delete(e),null):(aM().delete(e),aM().set(e,t),t):null}function aL(e){if(!e.sessionId||!e.revision)return!1;let t=aM();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(aR(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=aM();for(;e.size>8;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}let t=0;for(let n of e.values())t+=aR(n);for(;t>0x2000000&&e.size>0;){let n=e.keys().next().value;if(void 0===n)break;let r=e.get(n);e.delete(n),r&&(t-=aR(r))}}(),aM().has(n.sessionId))}function az(e){aM().delete(e)}var aP=n(14755);let aW="pi-tool-preset";function aO(){try{return window.localStorage}catch{return null}}function aF(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0)}function aD(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,aF(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),aF(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function aB(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function aH(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(aB).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let a_=(e,t)=>`live:${e??""}:${t}`;class aU extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class aq{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.opens=0,this.retries=0,this.lastError=null,this.lastClose=null}close(e){let t=null!==this.lastError&&!(this.lastClose&&this.lastClose.at>=this.lastError.at);(this.current||this.retry||t)&&(this.lastClose={reason:e??null,at:Date.now()}),this.stopRetrying(),this.current&&this.discard(this.current,new aU("closed"))}snapshot(){let e=this.current,t=this.retry;return{sessionId:e?.sessionId??t?.sessionId??null,state:e?e.attempt.ready?"connected":"connecting":t?"retrying":"idle",readyState:e?e.source.readyState:null,openedAt:e?.openedAt??null,connectedAt:e?.connectedAt??null,lastSeenAt:e?.lastSeenAt??null,lastHeartbeatAt:e?.lastHeartbeatAt??null,events:e?.events??0,opens:this.opens,retries:this.retries,retryDueAt:t?.dueAt??null,watchdogArmed:!!(e&&null!==e.watchdog),staleAfterMs:this.options.staleAfterMs??null,lastError:this.lastError?{...this.lastError}:null,lastClose:this.lastClose?{...this.lastClose}:null}}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof aU?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new aU("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new aU("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new aU("closed")));try{t=this.options.createSource(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw this.lastError={reason:"error",message:e,at:Date.now()},new aU("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(d,new aU("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a=Date.now(),d={sessionId:e,source:t,attempt:o,watchdog:null,openedAt:a,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=e=>{let t;if(this.current===d){d.lastSeenAt=Date.now();try{t=JSON.parse(e.data)}catch{return}if("heartbeat"===t.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===t.type){d.connectedAt??=d.lastSeenAt,o.ready=!0,o.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===d.watchdog&&(d.watchdog=setInterval(()=>{Date.now()-(d.lastSeenAt??a)>e&&this.fail(d,new aU("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(d,new aU("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(t)}},t.onerror=()=>{this.fail(d,new aU("closed"),"error")},d}fail(e,t,n){this.current===e&&(this.lastError={reason:n,message:"startup_error"===n?t.message:null,at:Date.now()},this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){null!==e.watchdog&&clearInterval(e.watchdog),e.watchdog=null,e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.retries+=1,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t,dueAt:Date.now()+this.options.reconnectDelayMs}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function aK(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function aV(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let aZ=()=>"hidden"===document.visibilityState,aJ=()=>!1;function aY(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function aG(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}function aX(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aQ(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let a0={isStreaming:!1,streamingMessage:null};function a1(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function a2(){let e=a0,t=new Set;return{getState:()=>e,dispatch(n){let r=function(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=aS(t.message,{includeStreamingRawInput:!0});return"assistant"===n.role?{isStreaming:!0,streamingMessage:n}:e}case"delta":var n=t.event;switch(n.type){case"text_start":return a1(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return a1(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return a1(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return a1(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return a1(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return a1(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return a1(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return a1(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id||e.toolCallId,toolName:n.toolName||e.toolName,rawInput:(e.rawInput??"")+n.delta}:null);case"toolcall_end":return a1(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return a0;default:return e}}(e,n);if(r!==e)for(let n of(e=r,t))n()},subscribe:e=>(t.add(e),()=>{t.delete(e)})}}function a4(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function a8(e,t){return e.reduce((e,n)=>"user"===n.role&&aH(n)===t?e+1:e,0)}function a3(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function a5(e){return e&&"auto"!==e?e:null}let a6=new Map,a9=[2e3,5e3,1e4];function a7(e){return new Promise(t=>setTimeout(t,e))}function de(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function dt(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:de(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:de(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=de(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function dn(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function dr(e,t){let[n,r]=(0,i.useState)(()=>t(e.getState()));return(0,i.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let di=e=>e.isStreaming,ds=e=>!!e.streamingMessage?.content.length,dl=e=>e.streamingMessage,da=null,dd=null;function dc(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>dd);if((0,i.useEffect)(()=>{if(dd)return;let e=!1;return(da??=fetch("/api/app-update").then(async e=>{if(!e.ok)return null;let t=await e.json();return t.updateAvailable&&t.latestVersion&&t.releaseUrl?t:null}).then(e=>(dd=e,e)).catch(()=>(da=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let l=t(n.latestVersion);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"new-session-meta-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("a",{className:"new-session-update",href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:l,"aria-label":l,children:["v",n.latestVersion,(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})]})}function du(e){let t,{messageCount:n,toolCallCount:s,durationMs:l,cacheMisses:o,defaultExpanded:a=!1,reveal:d=!1,children:c,t:u}=e,[p,h]=(0,i.useState)(a);(0,i.useLayoutEffect)(()=>{d&&h(!0)},[d]);let f=[`${n} ${u(1===n?"chat.message":"chat.messages")}`];s>0&&f.push(`${s} ${u(1===s?"chat.toolCall":"chat.toolCalls")}`),void 0!==l&&f.push(u("chat.turnDuration",{time:rZ(l)}));let m=o&&!(p||d)?(t={count:o.count,tokens:sY(o.missedTokens),cost:sX(u,o.missedCost)},u(1===o.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":p||d,"aria-label":[u("chat.processDetails"),...f,...m?[m]:[]].join(" \xb7 "),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:u(p?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:p?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:sG},children:` \xb7 ${m}`})]})]}),(p||d)&&(0,r.jsx)("div",{style:{marginTop:8},children:c})]})}function dp(e){var t;let s,{session:o,searchTarget:a,onSearchTargetHandled:d,initialScrollPosition:c,onScrollPositionChange:u,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,newSessionContextBar:m,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:v,onToolEnd:b,onAttentionNeeded:y,onSessionCreated:w,onSessionForked:j,modelsRefreshKey:k,chatInputRef:S,onBranchDataChange:C,onSystemPromptChange:N,onSystemToolsChange:$,onSystemInfoLoaderChange:E,onDebugSnapshotReaderChange:I,onSessionStatsChange:M,onSessionStatsPanelOpen:T,onOpenSettings:R,onContextUsageChange:A,onOpenFile:L,onFilesUploaded:z,onOpenSubagent:P,onAskInNewChat:W,quoteSelectionEnabled:O=!1,initialPrompt:F,onInitialPromptConsumed:D,soundEnabled:B=!0,onSoundToggle:H,playDoneSound:_=()=>{},unlockAudio:U,holdAudio:q}=e,{t:K}=(0,e0.s)(),V=te(),Z=o?.relation?.kind!=="subagent",J=(0,i.useRef)(_);J.current=_;let Y=(0,i.useRef)(B);Y.current=B;let G=(0,i.useRef)(!1),X=(0,i.useCallback)(e=>{Z&&Y.current&&!e.aborted&&!e.subagentsActive&&J.current(),v?.(e)},[Z,v]),Q=(0,i.useRef)(a?null:c??null),[ee,et]=(0,i.useState)(()=>{let e=Q.current;return e&&!e.atBottom?e:null}),[en,er]=(0,i.useState)(!1),{loading:ei,error:es,messages:el,activeToolResults:eo,entryIds:ea,messageKeys:ed,historyCursor:ec,hasEarlierMessages:eu,earlierTurnCount:ep,streamingStore:eh,agentRunning:ef,bashRunning:em,pendingBash:eg,modelNames:ex,modelList:ev,modelError:eb,missingCwd:ey,modelScopeWarnings:ew,modelThinkingLevels:ej,modelThinkingLevelMaps:ek,toolPreset:eS,thinkingLevel:eC,retryInfo:eN,contextUsage:e$,forkingEntryId:eE,isCompacting:eI,compactError:eR,compactResult:eA,displayModel:eL,modelSwitching:eP,sessionStats:eW,slashCommands:eO,slashCommandsLoading:eF,queuedMessages:eD,notices:eB,extensionDialog:eH,waitingExtensionDialogCount:e_,extensionCustomUi:eU,waitingExtensionCustomUiCount:eq,extensionStatuses:eK,extensionWidgets:eV,respondToExtensionUi:eZ,sendExtensionCustomInput:eJ,setNoticePaused:eY,addNotice:eG,isAutoModelSelection:eX,isAutoThinkingSelection:eQ,defaultModel:e1,savedDefaultThinkingLevel:e2,agentPhase:e4,isNew:e8,editEntryId:e3,showScrollToBottom:e5,sessionIdRef:e6,scrollContainerRef:e9,lastUserMsgRef:e7,promptAnchorActive:tt,handleSend:tn,handleAbort:tr,handleFork:ts,handleEditContent:tl,cancelEdit:to,handleModelChange:ta,handleCompact:td,handleSteer:tu,handleFollowUp:tp,handlePromptWithStreamingBehavior:th,handleAbortCompaction:tf,dismissCompactError:tm,handleRecallQueue:tg,handleBuiltinSlashCommand:tx,handleToolPresetChange:tv,handleThinkingLevelChange:tb,handleSetDefaultModel:ty,handleSetDefaultThinkingLevel:tw,loadSlashCommands:tj,scrollUserMsgToTop:tk,loadContext:tS,activeLeafId:tC,scrollToBottom:tN,scrollToMessage:t$}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:s,onAgentEnd:l,onToolEnd:o,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:p,onSystemPromptChange:h,onSystemToolsChange:f,onSystemInfoLoaderChange:m,onSessionStatsPanelOpen:g,onOpenSettings:x,onDebugSnapshotReaderChange:v}=e,b=null===t&&null!==r,y=b?e.initialNewSessionChoices??null:null,[w,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(!b),[C,N]=(0,i.useState)(null),[$,E]=(0,i.useState)(null),[I,M]=(0,i.useState)([]),[T,R]=(0,i.useState)(new Map),[A,L]=(0,i.useState)([]),[z,P]=(0,i.useState)(()=>new Map),[W,O]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(0),[_]=(0,i.useState)(a2),U=_.dispatch,[q,K]=(0,i.useState)(!1),[V,Z]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(null),[G,X]=(0,i.useState)({}),[Q,ee]=(0,i.useState)([]),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(null),[es,el]=(0,i.useState)(null),[eo,ea]=(0,i.useState)([]),[ed,ec]=(0,i.useState)({}),[eu,ep]=(0,i.useState)({}),[eh,ef]=(0,i.useState)(()=>y?.model??null),[em,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(aP.Q8),[eb,ey]=(0,i.useState)(()=>y?.thinkingLevel??null),[ew,ej]=(0,i.useState)(null),[ek,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[e$,eE]=(0,i.useState)(null),[eI,eR]=(0,i.useState)(null),[eA,eL]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(null),eO=(0,i.useRef)(0),eF=(0,i.useRef)(0),[eD,eB]=(0,i.useState)(null),[eH,e_]=(0,i.useState)(null),[eU,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(null),[eZ,eJ]=(0,i.useState)(null),[eY,eG]=(0,i.useState)(!1),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(!0),[e2,e4]=(0,i.useState)(null),[e8,e3]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)([]),[ti,ts]=(0,i.useState)(!1),[tl,to]=(0,i.useReducer)(dt,{visible:[],pending:[]}),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)([]),[tp,th]=(0,i.useState)([]),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)([]),[tv,tb]=(0,i.useState)({steering:[],followUp:[]}),ty=(0,i.useRef)(null),tw=(0,i.useRef)(null),tj=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tS=(0,i.useRef)(!1),[tC,tN]=(0,i.useState)(0),t$=(0,i.useRef)(null),tE=(0,i.useRef)(()=>{}),tI=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tM=(0,i.useRef)({count:0,lastAt:null}),tT=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tR=(0,i.useRef)(null),tA=(0,i.useRef)(null),tL=(0,i.useRef)(!1),tz=(0,i.useRef)(0),tP=(0,i.useRef)(t?.id??null),tW=(0,i.useRef)(t?.id??null),tO=(0,i.useRef)(!1),tF=(0,i.useRef)(!1),tD=(0,i.useRef)(!1),tB=(0,i.useRef)(!1),tH=(0,i.useRef)(-1),t_=(0,i.useRef)(!1),tU=(0,i.useRef)(0),tq=(0,i.useRef)(null),tK=(0,i.useRef)(!!e.deferInitialScroll),tV=(0,i.useRef)(null),tZ=(0,i.useRef)(!1),tJ=(0,i.useRef)(!0),tY=(0,i.useRef)(0),tG=(0,i.useRef)(null),tX=(0,i.useRef)(void 0),tQ=(0,i.useRef)(void 0),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)([]),t4=(0,i.useRef)(null),t8=(0,i.useRef)(0),t3=(0,i.useRef)(!1),t5=(0,i.useRef)(y?.model??null),t6=(0,i.useRef)(y?.thinkingLevel??null),t9=(0,i.useRef)({}),t7=(0,i.useRef)(null),ne=(0,i.useRef)(0),nt=(0,i.useRef)(null),nn=(0,i.useRef)(null),nr=(0,i.useRef)(null),ni=(0,i.useRef)(0),ns=(0,i.useRef)(null),nl=(0,i.useCallback)(()=>{nn.current=ne.current,nr.current?.runId===ne.current&&(nr.current=null)},[]),no=(0,i.useRef)(!1),na=(0,i.useRef)(new Map),nd=(0,i.useRef)(!0),nc=(0,i.useRef)(new Map),nu=(0,i.useRef)(null),np=(0,i.useRef)([]),nh=(0,i.useRef)([]),nf=(0,i.useRef)(null),nm=(0,i.useRef)(null),ng=(0,i.useRef)(!1),nx=(0,i.useRef)(0);tW.current=t?.id??null,nu.current=w,np.current=I,nh.current=A,nf.current=$,nm.current=W,ng.current=F,nx.current=B,tL.current=eX,tz.current=tc.length+tp.length;let nv=(0,i.useCallback)(e=>nd.current&&tP.current===e&&(tF.current||tk.current||tW.current===e&&!tS.current),[]);ty.current||(ty.current=new aq({createSource:e=>ez("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(eT())}`),e),onEvent:e=>tq.current?.(e),shouldMaintain:nv,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nb=e.setToolPreset??ev,ny=t?.id;(0,i.useLayoutEffect)(()=>{(ny||b&&!tP.current)&&nb(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:aO();if(!e)return aP.Q8;try{let t=e.getItem(aW);return(0,aP.sn)(t)?t:aP.Q8}catch{return aP.Q8}}())},[ny,b,nb]);let nw=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{b&&nw?.({model:eh,thinkingLevel:eb})},[b,eh,eb,nw]);let nj=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=t0.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),tY.current=t.scrollTop)},[]),nk=eU??eK??w?.context.model??eZ??null,nS=b?eh??em:nk??(w?.context.messages.length===0?em:null),nC=a5(w?.context.thinkingLevel&&"off"!==w.context.thinkingLevel?w.context.thinkingLevel:null),nN=b?eb??ew:eC??e$??nC??(w?.context.messages.length===0?ew:null),n$=t?.id??s??void 0,nE=(0,i.useCallback)(e=>{eV(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eE(a5(e.thinkingLevel))},[]),nI=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=na.current.get(t);if(!e)break;t=e}return t},[]),nM=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),l=nI(r);if(!nd.current&&!t3.current&&r===s)return;let o=e.chatInputRef?.current;o?o.restoreSubmission(t,i,l):l&&lK(l,t,i)},[s,e.chatInputRef,nI]),[nT,nR]=(0,i.useState)(()=>{let e=t?.id;return e&&!lB(e)&&a6.delete(e),e&&a6.get(e)||null}),nA=(0,i.useCallback)(e=>{t?.id&&(e?a6.set(t.id,e):a6.delete(t.id),nR(e))},[t?.id]),nL=(0,i.useCallback)((n,r)=>{t?.id&&(e.chatInputRef?.current?.replaceMessage(n),nA(r))},[e.chatInputRef,t?.id,nA]),nz=(0,i.useCallback)(()=>nA(null),[nA]),nP=(0,i.useMemo)(()=>{let e=w?.totalActiveMs,n=eP&&eP.sessionId===w?.sessionId?eP.value:void 0,r=void 0===e&&void 0===n?void 0:Math.max(e??0,n??0);if(ta)return{...ta,totalActiveMs:r,...eA?{contextUsage:eA}:{}};let i=w?.stats,s=function(e,t,n){let r=aD(n);if(!e)return r;let i=aD(t),s=(e,t)=>Math.max(0,e-t),l={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return l.total=l.input+l.output+l.cacheRead+l.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:l,cost:e.cost+s(r.cost,i.cost)}}(i,w?.context.messages??[],I);return 0!==s.tokens.total||0!==I.length||i?{sessionFile:w?.filePath||void 0,sessionId:tP.current??t?.id??"",sessionName:t?.name,...s,totalActiveMs:r,...eA?{contextUsage:eA}:{}}:null},[I,ta,eA,eP,w?.sessionId,w?.context.messages,w?.filePath,w?.totalActiveMs,w?.stats,t?.id,t?.name]),nW=(0,i.useCallback)((e,t,n,r)=>{nd.current&&tP.current===t&&ne.current===n&&!(r<=eF.current)&&(eF.current=r,e?.contextUsage!==void 0&&eL(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eW({sessionId:t,value:e.totalActiveMs}))},[]),nO=(0,i.useCallback)(async e=>{let t=ne.current,n=++eO.current;try{let r=await fetch(aE(e));if(!r.ok)return;let i=await r.json();nW(i.state,e,t,n)}catch{}},[nW]),nF=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=r?.force?`force:${e}`:e,s=r?.force?void 0:nc.current.get(i);if(s)return await s;let l=(async()=>{let i=!1,s=++ni.current;try{t&&S(!0);let l=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&l.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${l}`);if(404===o.status)return t&&(j(null),E(null),M([]),L([]),O(null),D(!1),H(0),N(null)),az(e),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let a=await o.json();if(tP.current!==e)return null;(ns.current?.seq??0)<s&&(ns.current={sid:e,seq:s,messages:a.context.messages,entryIds:a.context.entryIds??[]});let d=aA(e),c=!!(a.snapshotRevision&&d?.revision===a.snapshotRevision&&d.entryIds.length>=(a.context.entryIds??[]).length),u=c?np.current:a.context.messages;if(j(c?{...a,context:{...a.context,messages:np.current,entryIds:nh.current,oldestEntryId:nm.current,hasMore:ng.current,turnsBefore:nx.current}}:a),E(a.leafId),c)aL({sessionId:e,revision:a.snapshotRevision,messages:np.current,entryIds:nh.current,leafId:a.leafId,oldestEntryId:nm.current,hasMore:ng.current,turnsBefore:nx.current,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:nh.current});else{let e={messages:np.current,entryIds:nh.current},t={messages:u,entryIds:a.context.entryIds??[]};P(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],l=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===l&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var o,a;let d=t.entryIds[l+n];if(void 0===d||(o=e.messages[i+n],a=t.messages[l+n],o.role!==a.role||("user"===o.role?aH(o)!==aH(a):"custom"===o.role?o.customType!==a.customType:o.timestamp!==a.timestamp)))break;r.set(d,a_(s,n))}return r})({...e,aliases:n},t)),M(t.messages),L(t.entryIds),O(a.context.oldestEntryId),D(a.context.hasMore),H(a.context.turnsBefore??0)}if(tO.current=void 0!==a.toolNames,nb(void 0!==a.toolNames?(0,aP.YO)(a.toolNames):aP.Q8),eq(e=>no.current?e:null),eN(null),N(null),"summary"===a.treeFormat&&a.snapshotRevision&&aL({sessionId:e,revision:a.snapshotRevision,messages:u,entryIds:a.context.entryIds??[],leafId:a.leafId,oldestEntryId:a.context.oldestEntryId,hasMore:a.context.hasMore,turnsBefore:a.context.turnsBefore??0,summaryTree:a.tree,thinkingLevel:a.context.thinkingLevel,model:a.context.model,stats:a.stats,totalActiveMs:a.totalActiveMs,loadedEntryIds:a.context.entryIds??[]}),a.wrapperRebuilt&&(ty.current?.close("rebuilt"),ty.current?.maintain(e)),!n&&a.context.thinkingLevel&&"off"!==a.context.thinkingLevel&&eE(a5(a.context.thinkingLevel)),i=!0,t&&S(!1),!n)return null;try{let t=ne.current,n=++eO.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tP.current!==e)return null;let s=i.state;return nE(s),s?(nW(s,e,t,n),void 0!==s.systemPrompt&&eB(s.systemPrompt??null),void 0!==s.extensionStatuses&&tm(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tx(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tb(a3(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&e1(s.autoCompactionEnabled??!0)):i.running||tb({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return N(String(e)),"error"}finally{t&&!i&&S(!1)}})();return r?.force||nc.current.set(i,l),l.finally(()=>{nc.current.get(i)===l&&nc.current.delete(i)}),await l},[nW,nb,nE]),nD=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,l=await fetch(s,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let o=await l.json();if(tP.current!==e||r?.signal?.aborted||!nd.current)return;return O(o.context.oldestEntryId),D(o.context.hasMore),H(o.context.turnsBefore??0),j(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...o.context.messages,...t.context.messages],entryIds:[...o.context.entryIds,...t.context.entryIds],oldestEntryId:o.context.oldestEntryId,hasMore:o.context.hasMore,turnsBefore:o.context.turnsBefore}:o.context;return{...t,context:r}}),n?(M(e=>[...o.context.messages,...e]),L(e=>[...o.context.entryIds,...e])):(M(o.context.messages),L(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),nB=(0,i.useCallback)(async e=>{try{let t=await aI(e,{type:"get_tools"});if(!t||!nd.current||tP.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nb(tO.current?r(t):aP.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,nb]),nH=(0,i.useCallback)(function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"(no messages)",i=tP.current;if(b&&r&&i&&!t3.current&&(t3.current=!0,s)){if(s!==i){na.current.set(s,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(s,i):lV(s,i)}d?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},s)}},[b,r,s,d,e.chatInputRef]),n_=(0,i.useCallback)(async()=>{if(tP.current||!b||!r)return tP.current;if(t1.current)return t1.current;let e=(async()=>{let e=t5.current,t=t6.current;e&&eJ(e);let n=(0,aP.xG)(ex);tO.current=void 0!==n;let i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok){let e=await i.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${i.status}`,n=aC(e);throw n?new aN(t,i.status,void 0,void 0,n):Error(t)}let s=await i.json(),l=s.sessionId;return tP.current=l,s.model&&t5.current===e&&(eJ(s.model),e||eg(s.model)),s.thinkingLevel&&t6.current===t&&(eE(a5(s.thinkingLevel)),t||ej(a5(s.thinkingLevel))),l})();t1.current=e;try{return await e}finally{t1.current=null}},[b,r,ex]),nU=(0,i.useCallback)(async()=>{let e=tP.current??await n_();if(!e)return;let[t]=await Promise.all([aI(e,{type:"get_state"}),nB(e)]);nd.current&&tP.current===e&&(nE(t),eB(t.systemPrompt??""))},[n_,nB,nE]),nq=(0,i.useCallback)(e=>{t2.current=e,tr(e)},[]),nK=(0,i.useCallback)(()=>{t8.current+=1,t4.current=null,nq([])},[nq]),nV=(0,i.useCallback)(()=>{let e=++t8.current,t=(async()=>{let t=tP.current??await n_();if(!t)return t8.current===e&&nq([]),[];ts(!0);try{let n=await aI(t,{type:"get_commands"}),r=n?.commands??[];return t8.current===e&&nq(r),r}catch(t){return console.error("Failed to load slash commands:",t),t8.current===e&&nq([]),null}finally{t8.current!==e&&t4.current||ts(!1)}})();t4.current=t;let n=()=>{t4.current===t&&(t4.current=null)};return t.then(n,n),t},[n_,nq]),nZ=(0,i.useCallback)(async()=>await nV()??[],[nV]),nJ=(0,i.useCallback)(async()=>{let e=t4.current,t=t2.current;return!e&&t.length>0?t:await (e??nV()).catch(()=>null)??(t.length>0?t:null)},[nV]),nY=(0,i.useCallback)(()=>{tj.current+=1,tk.current=!1,tA.current=null,tw.current&&(clearTimeout(tw.current),tw.current=null)},[]),nG=(0,i.useCallback)(e=>{ty.current?.close(e)},[]),nX=(0,i.useCallback)(e=>ty.current.ensureConnected(e),[]),nQ=(0,i.useCallback)(e=>{ty.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return nd.current=!0,tS.current=!1,nQ(e),()=>{tP.current===e&&ty.current?.close("deselected")}},[nQ,t?.id]);let n0=(0,i.useCallback)(e=>{let t=t$.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,l=Date.now();tI.current.inFlightSince=l,tI.current.requests+=1;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store",signal:n.signal});return t=r.status,s=r.ok?await r.json():null}catch(e){return n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),t$.current===i&&(t$.current=null);try{let e=tI.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-l),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),t$.current=i,i.promise},[]),n1=!q&&!V&&!eX&&0===tc.length&&0===tp.length;(0,i.useEffect)(()=>{let e=t?.id;if(!e||!n1)return;let n=!1,r=null,i=()=>!n&&"hidden"===document.visibilityState&&!tS.current&&tP.current===e&&tW.current===e&&!tF.current&&!t_.current,s=async()=>{if(r=null,tR.current=null,!i())return;let t=await n0(e);if(i()){if(!("unanswered"===t||t&&!aK(t)))return void l();tS.current=!0,tM.current={count:tM.current.count+1,lastAt:Date.now()},nG("released")}},l=()=>{null===r&&(r=setTimeout(()=>void s(),3e4),tR.current=Date.now()+3e4)},o=()=>{"hidden"===document.visibilityState?l():r&&(clearTimeout(r),r=null,tR.current=null)};return"hidden"===document.visibilityState&&l(),document.addEventListener("visibilitychange",o),()=>{n=!0,r&&clearTimeout(r),tR.current=null,document.removeEventListener("visibilitychange",o)}},[nG,n1,tC,n0,t?.id]);let n2=(0,i.useCallback)(async(e,t)=>{let n=tP.current;if(tu(t=>aj(t,e.id)),n)try{await aI(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),n4=(0,i.useCallback)(async(e,t)=>{let n=tP.current;if(n)try{await aI(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),n8=(0,i.useCallback)(e=>{let t=e.message.trim();t&&to({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),n3=(0,i.useRef)(e.t);n3.current=e.t;let n5=(0,i.useCallback)((e,t)=>n3.current(e,t),[]),n6=(0,i.useCallback)(()=>{n8({type:"warning",message:n5("chat.sendUnconfirmed")})},[n8,n5]),n9=(0,i.useCallback)(e=>{nd.current&&M(t=>a4(t,e.bubble));let t=aA(e.sid);t?.messages.includes(e.bubble)&&aL({...t,messages:a4(t.messages,e.bubble)})},[]),n7=(0,i.useCallback)((e,t,n)=>{let r=nr.current;if(!r||r.runId!==t||r.sid!==e)return;nr.current=null;let i=ns.current,s=i?.sid===e&&i.seq>n?i:null,l=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&l>=0&&a8(s.messages.slice(l),r.key)>r.sameTextAfterSend||(nM(r.message,r.images,r.draftKey),s&&n9(r),n8(s&&!r.command&&l===s.entryIds.length?{type:"error",message:n5("chat.sendNotReceived")}:{type:"warning",message:n5("chat.sendUnconfirmed")}))},[n8,n9,nM,n5]),re=(0,i.useCallback)(()=>{let e=nr.current;if(nr.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});lK(e.parkedDraftKey,e.message,t)}else nM(e.message,e.images,e.draftKey);n9(e)}},[n9,nM]),rt=(0,i.useRef)(re);rt.current=re;let rn=(0,i.useCallback)(t=>{switch(ay(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":tu(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":n8({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tm(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tx(e=>(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"aboveEditor";if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},s=e.findIndex(e=>e.key===t);return -1===s?[...e,i]:e.map((e,t)=>t===s?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":th(e=>{let n;return t.closed?aj(e,t.id):-1===(n=e.findIndex(e=>e.id===t.id))?[...e,t]:e[n]===t?e:e.map((e,r)=>r===n?t:e)})}},[n8,a,e.chatInputRef]),rr=(0,i.useCallback)(()=>{let e=tF.current;return tF.current=!1,K(!1),e6(null),eR(null),R(new Map),U({type:"end"}),e},[U]),ri=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return tH.current!==e&&(tH.current=e,l?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[l]),rs=(0,i.useCallback)(e=>{if(tW.current===e)return void nY();nY(),tk.current=!0;let t=tj.current,n=async()=>{if(t===tj.current&&tP.current===e&&tk.current)try{let r=await fetch(aE(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tj.current||tP.current!==e||!tk.current)return;let s=i.state;if(nE(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tk.current=!1,tw.current=null,tA.current=null,tD.current=!!s?.isStreaming,tB.current=!!s?.isPromptRunning,tF.current=!0,K(!0),e6(e=>ab(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){eQ(!0),tw.current=setTimeout(()=>void n(),600),tA.current=Date.now()+600;return}tk.current=!1,tw.current=null,tA.current=null,nG("grace_end")}catch{if(t!==tj.current||tP.current!==e||!tk.current)return;tw.current=setTimeout(()=>void n(),600),tA.current=Date.now()+600}};tw.current=setTimeout(()=>void n(),3e4),tA.current=Date.now()+3e4},[nY,nG,nE]),rl=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tP.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ne.current;if(ne.current!==t)return;let n=ni.current;try{e&&await nF(e)}finally{if(ne.current!==t)return;e&&n7(e,t,n);let r=tB.current,i=tD.current;tB.current=!1,tD.current=!1,nt.current=null;let s=rr();r?ri(t):i&&s&&l?.({aborted:!1}),e&&rs(e)}},[nF,ri,l,rs,rr,n7]),ro=(0,i.useCallback)(async(e,t)=>{await a7(800);let n=Date.now();for(;tF.current&&Date.now()-n<2e4;){if(void 0!==t&&ne.current!==t)return;try{let n=await fetch(aE(e));if(n.ok){let r=await n.json(),i=r.state;if(nE(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rl(e,t)}}catch{}await a7(600)}},[rl,nE]),ra=(0,i.useCallback)(async e=>{let t=tU.current+1;for(tU.current=t;t_.current&&tU.current===t&&tP.current===e;){await a7(1e3);try{let n=await fetch(aE(e));if(!n.ok)continue;let r=await n.json();if(nE(r.state),r.state?.isBashRunning)continue;if(await nF(e),tU.current!==t||tP.current!==e)return;t_.current=!1,Z(!1),Y(null);return}catch{}}},[nF,nE]),rd=(0,i.useCallback)(async e=>{if(!tF.current||tP.current!==e)return;let t=ne.current,n=++eO.current;try{let r=await fetch(aE(e));if(!r.ok)return;let i=await r.json();if(tP.current!==e||ne.current!==t)return;let s=i.state;if(nW(s,e,t,n),nE(s),eQ(s?.isCompacting??!1),e1(s?.autoCompactionEnabled??!0),tb(a3(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tD.current=!!s.isStreaming,tB.current=!!s.isPromptRunning;return}if(!tF.current)return;s&&(void 0!==s.extensionStatuses&&tm(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tx(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nd.current&&tP.current===e&&t.state?.systemPrompt!==void 0&&eB(t.state.systemPrompt??null)}).catch(()=>{})),await rl(e,t)}catch{}},[nW,rl,nE]);(0,i.useEffect)(()=>{if(!q)return;let e=()=>{let e=tP.current;e&&rd(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[q,rd]),(0,i.useEffect)(()=>{tF.current=q},[q]),tq.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":if(U({type:"end"}),Array.isArray(e.pendingExtensionUiIds)){let t=new Set(e.pendingExtensionUiIds);tu(e=>aw(e,t)),th(e=>aw(e,t))}!0===e.isStreaming&&(nY(),tD.current=!0,tF.current=!0,K(!0),e6({kind:"waiting_model"})),tP.current&&nO(tP.current);break;case"agent_start":nl(),nY(),tD.current=!0,tF.current=!0,K(!0),e6({kind:"waiting_model"}),eR(null),U({type:"start"});break;case"agent_end":if(!tF.current)break;if(e6(null),eR(null),U({type:"end"}),tP.current){let e=tP.current,t=ne.current,n=++eO.current;nF(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nd.current&&tP.current===e&&ne.current===t&&(nE(r.state),nW(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eB(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tm(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tx(r.state.extensionWidgets??[]),tb(a3(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let t=tD.current;if(tD.current=!1,!t||tB.current)break;let n=tP.current,r=rr();eQ(!1),n&&(nF(n),rs(n)),r&&l?.({aborted:!0===e.aborted,...!0===e.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{nl();let t=ne.current,n=tB.current;tB.current=!1,nt.current=null;let r=ri(t,!0===e.aborted,!0===e.subagentsActive);if(!n&&!r)break;let i=tP.current;i&&nF(i),!tD.current&&(rr(),i&&rs(i))}break;case"prompt_error":n8({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":n8({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tF.current||aG(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(U({type:"snapshot",message:t}),t.content.length>0&&e6(null)):t&&e6(null)}else{let t=e.assistantMessageEvent;t&&(U({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&e6(null))}!tZ.current&&tJ.current&&null===tG.current&&(tG.current=requestAnimationFrame(()=>{tG.current=null,tJ.current&&nj("auto")}));break;case"message_end":{if(!tF.current||aG(e))break;let t=e.message;if(t&&"user"===t.role){let e=aS(t),n=aH(e),r=nt.current;nt.current=null,r&&nl(),M(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&aH(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let n=Array.isArray(e.transcriptNotices)?e.transcriptNotices:void 0;if(M(e=>{var r;return[...e,(r=aS(t),n&&0!==n.length?{...r,[sZ]:[...n]}:r)]}),"assistant"===t.role){let e=tP.current;e&&nO(e)}}U({type:"end"}),e6({kind:"waiting_model"});break}case"tool_execution_start":{if(aY(e))break;let t=e.toolCallId,n=e.toolName;e6(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(aY(e))break;let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n||n===sP)&&Array.isArray(i)&&R(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===sP?function(e){if(!sO(e))return null;let{calls:t}=sD(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args.length>120?`${n.args.slice(0,117)}...`:n.args;return r?`${n.name} ${r}`:n.name}(e.partialResult):function(e){if(!aX(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>aX(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);e6(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),l={id:t,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),l]}});break}case"tool_execution_end":{if(aY(e))break;let t=e.toolCallId;o?.(e.toolName),R(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),e6(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":nl(),tb({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eR({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eR(null);break;case"auto_compaction_start":case"compaction_start":eQ(!0),e4(null),e3(null);break;case"auto_compaction_end":case"compaction_end":eQ(!1),e.errorMessage?(e4(e.errorMessage),e3(null)):!e.aborted&&(e3(dn(e.result,e.reason??"auto")),tP.current&&nF(tP.current));break;case"extension_ui_request":rn(e);break;case"extension_ui_closed":tu(t=>aj(t,e.id))}},[n8,nW,nY,U,rn,nF,nl,ri,l,o,nO,rs,nj,rr,nE]);let rc=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tF.current||t_.current)return void nM(e,n,n$);if(nT&&(nA(null),!await tQ.current?.(nT))){nA(nT),nM(e,n,n$);return}let s=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await tX.current?.(r,t):void nM(e,n,n$)}let l=ne.current+1;nY(),tB.current=!0;let o=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:o?.length?[...e.trim()?[{type:"text",text:e}]:[],...o]:e,timestamp:Date.now()},d=aH(a),c=nh.current,u=c.at(-1)??null,p=a8(np.current.slice(c.length),d);M(e=>[...e,a]),nt.current=d,ne.current=l,tF.current=!0,K(!0),e6(s?{kind:"running_command"}:{kind:"waiting_model"}),U({type:"start"}),tZ.current=!0,e7(!0);let h=()=>{M(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nt.current=null},f=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),m=null,g=!1;try{if(b&&r){let t=tP.current??await t1.current,n=t??await n_();if(!n)throw Error("Unable to create a session for the prompt");m=n,eh&&(eJ(eh),t&&await aI(n,{type:"set_model",provider:eh.provider,modelId:eh.modelId})),nd.current&&await nX(n).catch(e=>{if(nd.current)throw e}),g=!0;let r=await aI(n,{type:"prompt",message:e,...f?.length?{images:f}:{}});r?.queued&&h(),nH(1,e)}else if(t){m=t.id,await nX(t.id),g=!0;let n=await aI(t.id,{type:"prompt",message:e,...f?.length?{images:f}:{}});n?.queued&&h()}else throw Error("No active session for the prompt");el(null),s&&m&&ro(m,l)}catch(t){if(console.error("Failed to send message:",t),!(!g||a$(t))&&m){nn.current!==l&&(nr.current={runId:l,sid:m,message:e,images:n,draftKey:n$,parkedDraftKey:b&&r?lO(r):null,lastEntryIdAtSend:u,sameTextAfterSend:p,bubble:a,key:d,command:s},nd.current||re()),ro(m,l);return}if(tB.current=!1,M(e=>a4(e,a)),t instanceof aN&&t.missingCwd?el(t.missingCwd):n8({type:"error",message:t instanceof Error?t.message:String(t)}),nM(e,n,n$),nt.current=null,m)return void rd(m);tF.current=!1,nG("send_failed"),K(!1),e6(null),U({type:"end"})}},[b,r,eh,t,n_,nX,nH,ro,n8,re,nY,nG,n$,U,rd,nM,nT,nA]);tX.current=(0,i.useCallback)(async(e,n)=>{if(tF.current||t_.current)return;let r=`${n?"!!":"!"}${e}`;t_.current=!0,Y({command:e,excludeFromContext:n}),Z(!0);try{let i=tP.current??t?.id??await n_();if(!i)throw Error("Unable to create a session for the shell command");await aI(i,{type:"bash",command:e,excludeFromContext:n}),await nF(i),nH(1,r)}catch(e){console.error("Failed to execute shell command:",e),n8({type:"error",message:e instanceof Error?e.message:String(e)}),nM(r,void 0,n$)}finally{t_.current=!1,Y(null),Z(!1)}},[n8,n$,n_,nF,nH,nM,t]);let ru=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nM(n,t.images,n$):n&&e.chatInputRef?.current?.prependText(n)},[n$,e.chatInputRef,nM]),rp=(0,i.useCallback)(async()=>{let e=tP.current;if(e){if(t_.current){try{await aI(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{ru(await aI(e,{type:"abort"}))}catch(e){console.error("Failed to abort:",e)}}},[ru]),rh=(0,i.useCallback)(async e=>{if(t_.current)return;let t=tP.current;if(t){e_(e);try{let{cancelled:n,newSessionId:r}=await aI(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e),n8({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e_(null)}}},[n8,c]),rf=(0,i.useCallback)(async e=>{if(t_.current)return!1;let t=tP.current;if(!t)return!1;try{let n=await aI(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tP.current!==t)return!1;return await nF(t),tP.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[nF]);tQ.current=rf;let rm=(0,i.useCallback)(async e=>{if(t_.current||tF.current||eX)return;E(e);let t=tP.current;t&&(await nD(t,e),e&&aI(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[eX,nD]),rg=(0,i.useCallback)(async(e,t)=>{if(b){let n={provider:e,modelId:t};t5.current=n,ef(n),eJ(n),null===t6.current&&ej(a5(t9.current[`${e}/${t}`])??t7.current);let r=tP.current??await t1.current;if(!r)return;try{await aI(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tP.current;if(n&&!no.current){no.current=!0,eq({provider:e,modelId:t}),eG(!0);try{let r=await aI(n,{type:"set_model",provider:e,modelId:t});eV({provider:r.provider,modelId:r.id}),no.current=!1,await nF(n)}catch(e){console.error("Failed to set model:",e),no.current=!1,eq(eU),n8({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nF(n,!1,!0)}finally{no.current=!1,eG(!1)}}},[n8,eU,b,nF,ef]),rx=(0,i.useCallback)(async e=>{let t=tP.current;if(!t||eX)return!0;eQ(!0),e4(null),e3(null);try{let n=await aI(t,{type:"compact",...e?{customInstructions:e}:{}});return e3(dn(n,"manual")),await nF(t,!0)&&nH(),!0}catch(e){return e4(e instanceof Error?e.message:String(e)),e3(null),!1}finally{eQ(!1)}},[eX,nF,nH]),rv=(0,i.useCallback)(()=>e4(null),[]),rb=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",s=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models",l=null;try{let t=await fetch(s,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error),l=aC(n)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(ei(l),en(l?null:t instanceof Error?t.message:String(t))),t}ei(null),X(n.models),en(n.modelError??null),ea(n.modelScopeWarnings??[]),ec(n.thinkingLevels??{}),ep(n.thinkingLevelMaps??{});let o=n.modelList??[];ee(o);let a=n.defaultModel?o.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(eg(a?{provider:a.provider,modelId:a.id}:null),t9.current=n.thinkingLevelPins??{},t7.current=a5(n.defaultThinkingLevel),eS(a5(n.savedDefaultThinkingLevel)),b&&!tP.current){let e=t5.current,t=e&&(0===o.length||o.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!t&&(t5.current=null,ef(null));let r=t?e:a&&{provider:a.provider,modelId:a.id},i=r&&n.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===t6.current&&ej(a5(i)??t7.current)}},[b,r,t?.cwd]),ry=(0,i.useCallback)(async e=>{let n=r??t?.cwd,i=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n?{cwd:n}:{},...e})});if(i.ok)return;let s="";try{let e=await i.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(s=e.error)}catch{}throw Error(s||`HTTP ${i.status}`)},[r,t?.cwd]),rw=(0,i.useCallback)(()=>{rb().catch(()=>{})},[rb]),rj=(0,i.useCallback)(async(e,t)=>{try{await ry({provider:e,modelId:t})}catch(e){n8({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}n8({type:"success",message:`Default model: ${e}/${t}`}),eg({provider:e,modelId:t}),(nS?.provider!==e||nS?.modelId!==t)&&await rg(e,t),rw()},[n8,nS,rg,rw,ry]),rk=(0,i.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),l=tP.current??await n_(),o=e=>(e.handled&&(e.error?n8({type:"error",message:e.error}):e.action||n8({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!l||eX)return o({handled:!0,error:"No active session to compact"});return rx(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),o({handled:!0,action:"compact"});case"auto-compact":{if(!l)return o({handled:!0,error:"No active session"});let e=await aI(l,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await aI(l,{type:"set_auto_compaction",enabled:t}),e1(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!l)return o({handled:!0,error:"No active session to reload"});return await aI(l,{type:"reload"}),await Promise.all([nF(l,!1,!0),nB(l),nZ(),rb()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!l)return o({handled:!0,error:"No active session to name"});if(!s)return o({handled:!0,error:"Usage: /name <name>"});return await aI(l,{type:"set_session_name",name:s}),await nF(l)&&nH(),o({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!l)return o({handled:!0,error:"No active session"});let e=await aI(l,{type:"get_session_stats"});return e&&td(e),g?.(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!x)return{handled:!1};let e=await nJ();if(!e||!(e.some(lQ)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return x("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!l)return o({handled:!0,error:"No active session"});let e=await aI(l,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!l)return o({handled:!0,error:"No active session to clone"});if(tF.current||t_.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=await aI(l,{type:"clone",leafId:$});if(e?.cancelled||!e?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=o({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return o({handled:!0,error:e instanceof Error?e.message:String(e)})}},[$,n8,n_,rx,eX,rb,nF,nZ,nB,nH,x,c,g,e.chatInputRef,nJ]),rS=(0,i.useCallback)(async(e,t,n)=>{let r=tP.current;if(nT)return void nM(e,n,n$);if(!r){nM(e,n,n$),n8({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await aI(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nM(e,n,n$),t instanceof aN&&t.missingCwd)return void el(t.missingCwd);a$(t)?n8({type:"error",message:t.message}):n6()}},[n8,n6,n$,nT,nM]),rC=(0,i.useCallback)(async(e,t)=>{await rS(e,"steer",t)},[rS]),rN=(0,i.useCallback)(async(e,t,n)=>{await rS(e,t,n)},[rS]),r$=(0,i.useCallback)(async(e,t)=>{await rS(e,"followUp",t)},[rS]),rE=(0,i.useCallback)(async()=>{let e=tP.current;if(e)try{await aI(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rI=(0,i.useCallback)(async()=>{let e=tP.current;if(e)try{let t=await aI(e,{type:"clear_queue"});tb({steering:[],followUp:[]}),ru(t)}catch(e){console.error("Failed to recall queued messages:",e),n8({type:"error",message:"Failed to recall queued messages"})}},[n8,ru]),rM=(0,i.useCallback)(async e=>{if("auto"===e){t6.current=null,ey(null),eN(null);return}b?(t6.current=e,ey(e)):eN(e);let t=tP.current??await t1.current;if(t)try{await aI(t,{type:"set_thinking_level",level:e}),nd.current&&tP.current===t&&(eE(e),eN(null))}catch(e){console.error("Failed to set thinking level:",e),eN(null)}},[b]),rT=(0,i.useCallback)(async e=>{try{await ry({thinkingLevel:e})}catch(e){n8({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}n8({type:"success",message:`Default reasoning level: ${e}`}),eS(e),nN!==e&&await rM(e),rw()},[n8,nN,rM,rw,ry]),rR=(0,i.useCallback)(async e=>{let t=(0,aP.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:aO();if(t)try{t.setItem(aW,e)}catch{}}(e),nb(e);let n=tP.current??await t1.current;if(!n){tO.current=void 0!==t;return}try{let e=await aI(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tO.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(nY(),nG("set_tools"),tu([]),th([]),tP.current=r,e?.recreated&&tW.current===r&&nQ(r)),nK(),tm([]),tx([]);let[i]=await Promise.all([aI(r,{type:"get_state"}),nB(r)]);nd.current&&tP.current===r&&(eB(i.systemPrompt??""),nE(i))}catch(e){console.error("Failed to set tools:",e)}},[nY,nK,nG,nB,nQ,nb,nE]),rA=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=t0.current;n&&(null!==tG.current&&(cancelAnimationFrame(tG.current),tG.current=null),tK.current=!0,tZ.current=!1,tJ.current=!1,e7(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tY.current=n.scrollTop)},[]),rL=(0,i.useCallback)(()=>{let e=t0.current,t=tV.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==tG.current&&(cancelAnimationFrame(tG.current),tG.current=null),tJ.current=!0,tY.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),rz=(0,i.useCallback)(()=>{let e=t0.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tF.current,s=tJ.current,l=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!aQ(n,r,i)||!(n<t)&&(!!(!e&&n>t&&aQ(n,r,i,s))||e)}(s,tY.current,t,n,r,i?96:8);tJ.current=l,tY.current=t;let o=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!aQ(e,t,n,r)}(t,n,r);tt(e=>e===o?e:o),!s&&l&&i?nj("auto"):l||null===tG.current||(cancelAnimationFrame(tG.current),tG.current=null)}},[nj]),rP=(0,i.useCallback)((e,t)=>{t?.running&&(nB(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tD.current=!!t.state.isStreaming,tB.current=!!t.state.isPromptRunning,tF.current=!0,K(!0),e6(e=>ab(e,t.state?.isStreaming===!0)),U({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&ro(e)),t.state?.isBashRunning&&(t_.current=!0,Z(!0),ra(e))),t?.state&&(void 0!==t.state.isCompacting&&eQ(t.state.isCompacting),void 0!==t.state.systemPrompt&&eB(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tm(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tx(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tb(a3(t.state.queuedMessages)))},[U,nB,ra,ro]);tE.current=(e,t)=>{!tS.current||(tS.current=!1,tT.current={count:tT.current.count+1,lastAt:Date.now(),lastReason:t},tN(e=>e+1),nd.current&&tP.current===e&&tW.current===e&&(nQ(e),nF(e,!1,!0).then(t=>{nd.current&&tP.current===e&&rP(e,t)})))},(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=tI.current,i=async()=>{let t=await n0(e);!n&&"hidden"===document.visibilityState&&aK(t)&&tE.current(e,"activity")};i();let s=setInterval(()=>void i(),3e4);r.renewStartedAt=Date.now();let l=()=>{"visible"===document.visibilityState&&(tE.current(e,"visible"),i())};return document.addEventListener("visibilitychange",l),()=>{n=!0,clearInterval(s),r.renewStartedAt=null,document.removeEventListener("visibilitychange",l)}},[n0,t?.id]),(0,i.useEffect)(()=>{if(nd.current=!0,eF.current=eO.current,t){tP.current=t.id;let e=aA(t.id);e&&(j({sessionId:t.id,filePath:"",totalActiveMs:e.totalActiveMs??0,tree:e.summaryTree,leafId:e.leafId,context:{messages:e.messages,entryIds:e.entryIds,oldestEntryId:e.oldestEntryId,hasMore:e.hasMore,turnsBefore:e.turnsBefore,thinkingLevel:e.thinkingLevel,model:e.model},stats:e.stats}),E(e.leafId),M(e.messages),L(e.entryIds),O(e.oldestEntryId),D(e.hasMore),H(e.turnsBefore),N(null),S(!1)),nF(t.id,!e,!0,{force:!0}).then(e=>{rP(t.id,e)})}return()=>{nd.current=!1;let e=b?s:null;e&&queueMicrotask(()=>{nd.current||t3.current||l_(e)});let t=tP.current,n=nu.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=aA(t),r=nh.current;!e||function(e,t){if(0===t.length)return!0;let n=new Set([...e.entryIds,...e.loadedEntryIds]);return t.every(e=>n.has(e))}(e,r)?aL({sessionId:t,revision:n.snapshotRevision,messages:np.current,entryIds:nh.current,leafId:nf.current,oldestEntryId:nm.current,hasMore:ng.current,turnsBefore:nx.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nh.current}):az(t)}rt.current(),null!==tG.current&&(cancelAnimationFrame(tG.current),tG.current=null),tU.current+=1,nY(),nG()}},[]),(0,i.useEffect)(()=>{h?.(eD)},[eD,h]),(0,i.useEffect)(()=>(m?.(nU),()=>m?.(null)),[nU,m]);let rW=(0,i.useCallback)(()=>{let e,t=null;try{t=ty.current?.snapshot?.()??null}catch{t=null}let n=tP.current,r=tI.current,i=tT.current;return{pageId:"string"==typeof(e=globalThis[eM])?e:null,sessionId:n,selectedSessionId:tW.current,mounted:nd.current,wantsStream:null!==n&&nv(n),connection:t,released:{active:tS.current,...tM.current},reattached:{...i},hiddenReleaseDueAt:tR.current,hiddenGraceMs:3e4,graceDueAt:tA.current,run:{agentRunning:tF.current,bashRunning:t_.current,compacting:tL.current,dialogs:tz.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nv]);(0,i.useEffect)(()=>(v?.(rW),()=>v?.(null)),[rW,v]);let rO=q||V||eX;(0,i.useEffect)(()=>{p&&p(w?.tree??[],$,rm,rO)},[w?.tree,$,rm,rO,p]),(0,i.useEffect)(()=>{let e=t0.current;if(e)return tY.current=e.scrollTop,e.addEventListener("scroll",rz,{passive:!0}),()=>{e.removeEventListener("scroll",rz)}},[I.length,k,rz]),(0,i.useEffect)(()=>{q||e7(!1)},[q]),(0,i.useLayoutEffect)(()=>{I.length>0&&(tZ.current?(tZ.current=!1,tK.current=!0,rL()):tK.current?!tF.current&&tJ.current&&nj("auto"):(tK.current=!0,nj("instant")))},[I.length,q,nj,rL]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rb(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=a9.length||(await a7(a9[t]),e.signal.aborted))return}})(),()=>e.abort()},[rb,u]),(0,i.useEffect)(()=>{if(!e8)return;let e=setTimeout(()=>e3(null),6e3);return()=>clearTimeout(e)},[e8]);let[rF,rD]=(0,i.useState)(null),rB=(0,i.useRef)(5e3),rH=(0,i.useRef)(null),r_=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tl.visible.length){r_.current=null;return}let e=tl.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{to({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tl.visible[0];if(!t||(r_.current!==t.id&&(r_.current=t.id,rB.current=5e3),tl.visible.some(e=>e.id===rF)))return;rH.current=Date.now();let n=setTimeout(()=>{to({type:"mark_oldest_exiting"})},rB.current);return()=>{clearTimeout(n),null!==rH.current&&(rB.current=Math.max(0,rB.current-(Date.now()-rH.current)),rH.current=null)}},[tl.visible,rF]),(0,i.useEffect)(()=>{td(null)},[I.length,eA?.tokens,eA?.percent,eA?.contextWindow]);let rU=nN??"auto",rq=tc[0]??null,rK=Math.max(0,tc.length-1),rV=tp[0]??null,rZ=Math.max(0,tp.length-1),rJ=(0,i.useMemo)(()=>(function(e,t,n){let r=e[e.length-1],i=[];for(let s=0;s<t;s++){let t=e[s];i.push(void 0===t?a_(r,s-e.length):n.get(t)??t)}return i})(A,I.length,z),[A,I.length,z]);return{data:w,loading:k,error:C,activeLeafId:$,messages:I,activeToolResults:T,entryIds:A,messageKeys:rJ,historyCursor:W,hasEarlierMessages:F,earlierTurnCount:B,streamingStore:_,agentRunning:q,modelNames:G,modelList:Q,modelError:et,missingCwd:es??er,modelScopeWarnings:eo,modelThinkingLevels:ed,modelThinkingLevelMaps:eu,newSessionModel:eh,toolPreset:ex,thinkingLevel:rU,retryInfo:eI,contextUsage:eA,systemPrompt:eD,forkingEntryId:eH,isCompacting:eX,compactError:e2,compactResult:e8,currentModel:nk,displayModel:nS,modelSwitching:eY,sessionStats:nP,autoCompactionEnabled:e0,slashCommands:tn,slashCommandsLoading:ti,queuedMessages:tv,notices:tl.visible,extensionDialog:rq,waitingExtensionDialogCount:rK,extensionCustomUi:rV,waitingExtensionCustomUiCount:rZ,extensionStatuses:tf,extensionWidgets:tg,respondToExtensionUi:n2,sendExtensionCustomInput:n4,isAutoModelSelection:b&&null===eh,isAutoThinkingSelection:b&&null===eb,defaultModel:em,savedDefaultThinkingLevel:ek,agentPhase:e5,isNew:b,editEntryId:nT,promptAnchorActive:e9,showScrollToBottom:te,sessionIdRef:tP,scrollContainerRef:t0,lastUserMsgRef:tV,pendingScrollToUserRef:tZ,initialScrollDoneRef:tK,handleSend:rc,handleAbort:rp,handleFork:rh,handleNavigate:rf,handleModelChange:rg,handleCompact:rx,handleSteer:rC,handleFollowUp:r$,handlePromptWithStreamingBehavior:rN,handleAbortCompaction:rE,dismissCompactError:rv,handleRecallQueue:rI,handleBuiltinSlashCommand:rk,handleEditContent:nL,cancelEdit:nT?nz:void 0,addNotice:n8,setNoticePaused:rD,handleToolPresetChange:rR,handleThinkingLevelChange:rM,handleSetDefaultModel:rj,handleSetDefaultThinkingLevel:rT,loadTools:nB,loadSlashCommands:nZ,setActiveLeafId:E,setData:j,setMessages:M,loadContext:nD,scrollToBottom:nj,scrollUserMsgToTop:rL,scrollToMessage:rA,dispatch:U,setAgentRunning:K,setForkingEntryId:e_,bashRunning:V,pendingBash:J,handleAgentEventRef:tq}}({session:o,sessionRunning:p,newSessionCwd:h,newSessionDraftKey:f,initialNewSessionChoices:g,onNewSessionChoicesChange:x,onAgentEnd:X,onToolEnd:b,onAttentionNeeded:y,onSessionCreated:w,onSessionForked:j,modelsRefreshKey:k,chatInputRef:S,onBranchDataChange:C,onSystemPromptChange:N,onSystemToolsChange:$,onSystemInfoLoaderChange:E,onSessionStatsPanelOpen:T,onOpenSettings:R,onDebugSnapshotReaderChange:I,t:K,deferInitialScroll:!!ee}),tE=dr(eh,di),tI=dr(eh,ds),tM=(0,i.useCallback)(()=>eh.getState().streamingMessage,[eh]),tT=ef||em;(0,i.useEffect)(()=>{if(ef&&q)return q()},[ef,q]);let[tR,tA]=(0,i.useState)(null),[tL,tz]=(0,i.useState)(!1),[tP,tB]=(0,i.useState)(!1),[tH,t_]=(0,i.useState)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(()=>{tA(null),tz(!1),t_(null)},[]);(0,i.useEffect)(()=>{O||tK()},[O,tK]);let tV=(0,i.useCallback)(()=>{if(!O||tL)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t1.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tA(null);let r=e.toString().trim();if(!r)return void tA(null);let i=t.getBoundingClientRect(),s=[t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement,t.startContainer.nodeType===Node.ELEMENT_NODE?t.startContainer:t.startContainer.parentElement,t.endContainer.nodeType===Node.ELEMENT_NODE?t.endContainer:t.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);tA({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:s})},[O,tL]);(0,i.useEffect)(()=>{tL&&tR&&tq.current?.insertIfEmpty(rJ(tR.text,K("chat.quoteIntro"),K("chat.quoteQuestion")))},[tL,tR,K]),(0,i.useLayoutEffect)(()=>{let e=tU.current;if(!e||!tR)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(tR.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tR.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[tR,tL,tH]),(0,i.useEffect)(()=>{if(!tR)return;let e=e=>{tL||tU.current?.contains(e.target)||tK()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tP||tK())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tR,tL,tP,tK]);let tZ=(0,i.useCallback)(()=>{tR&&(S?.current?.insertText(rJ(tR.text,K("chat.quoteIntro"),K("chat.quoteQuestion"))),tK())},[S,tR,tK,K]),tJ=(0,i.useCallback)(async e=>{let t=e6.current??o?.id;if(!tP&&e.trim()&&tR?.sourceEntryId&&t&&W){tB(!0),t_(null),U?.();try{await W(e,t,tR.sourceEntryId),tK()}catch(t){tq.current?.restoreSubmission(e),t_(t instanceof Error?t.message:String(t))}finally{tB(!1)}}},[W,tR,tP,o?.id,e6,tK,U]),tY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ei||es||!F||tY.current||(tY.current=!0,D?.(),tn(F))},[F,ei,es,tn,D]),(0,i.useEffect)(()=>{let e=!!eH&&!G.current;G.current=!!eH,Z&&e&&J.current()},[Z,eH]),(0,i.useEffect)(()=>{l=tT?tr:null},[tT,tr]);let[tG,tX]=(0,i.useState)(50),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t4=(0,i.useRef)(!1),t8=(0,i.useRef)(!1),t3=(0,i.useRef)(ee);t3.current=ee;let[t5,t6]=(0,i.useState)(null),t9=el[ea.indexOf(t5?.entryId??"")],t7=t9?.role==="assistant"?t5?.blockIndex===void 0?t9.content.find(e=>"text"===e.type):t9.content[t5.blockIndex]:void 0,ne=(0,i.useRef)({entryIds:ea,historyCursor:ec,hasEarlierMessages:eu});ne.current={entryIds:ea,historyCursor:ec,hasEarlierMessages:eu};let nt=(0,i.useRef)(null),nn=(0,i.useCallback)(async(e,t,n)=>{nt.current=t;let r=await tS(e,tC,t,n);return r||nt.current!==t||(nt.current=null),r},[tC,tS]);(0,i.useEffect)(()=>{ec!==nt.current&&(nt.current=null)},[ec]),(0,i.useLayoutEffect)(()=>{let e=o?.id,t=e9.current,n=t1.current;if(e&&u&&t&&n)return()=>{if(t3.current)return;if(aQ(t.scrollTop,t.clientHeight,t.scrollHeight))return void u(e,{atBottom:!0});let r=t.getBoundingClientRect().top,i=function(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}(Array.from(n.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),r);i&&u(e,{atBottom:!1,...i,oldestEntryId:ne.current.historyCursor})}},[ei,u,e9,o?.id]),(0,i.useEffect)(()=>{a&&et(null)},[a]),(0,i.useEffect)(()=>{let e=o?.id;if(!ee||!e||ei||a||t8.current)return;t8.current=!0;let t=new AbortController;return(async()=>{let n=ne.current;if(n.entryIds.includes(ee.anchorEntryId)){tX(e=>Math.max(e,2*n.entryIds.length)),er(!0);return}t4.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nn(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tN("instant"),et(null);return}if(tX(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ee.anchorEntryId))return void er(!0);if(n.oldestEntryId===ee.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tN("instant"),et(null))}finally{t4.current=!1}})(),()=>{t.abort(),et(null)}},[tC,nn,ei,ee,tN,a,o?.id]),(0,i.useLayoutEffect)(()=>{let e=t1.current;if(!ee||!e||a)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ee.anchorEntryId);if(t instanceof HTMLElement){t$(t,ee.anchorOffset),et(null);return}en&&(tN("instant"),et(null))},[ea,ee,en,tN,t$,a,tG]),(0,i.useEffect)(()=>{if(!a||ei)return;let e=new AbortController;return(async()=>{let t=ne.current,n=t.entryIds.includes(a.entryId);if(!n&&!tT&&t.hasEarlierMessages&&t.historyCursor&&!t4.current){t4.current=!0;let r=e9.current;r&&(t2.current=r.scrollHeight-r.scrollTop);let i=await nn(a.sessionId,t.historyCursor,{tail:200,signal:e.signal});t4.current=!1,n=!!i?.entryIds.includes(a.entryId)}e.signal.aborted||(n?(t2.current=null,tX(e=>Math.max(e,(ne.current.entryIds.length+200)*2)),t6(a)):d?.(a))})(),()=>e.abort()},[a,ei,tT,nn,d,e9]),(0,i.useLayoutEffect)(()=>{if(!t5||t5!==a)return;let e=`[data-entry-id="${CSS.escape(t5.entryId)}"]`,t=e9.current?.querySelector(t9?.role==="user"?e:`${e} [data-search-target]`);t&&(t$(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),t6(null),d?.(t5)},[t5,a,t9,e9,t$,d]),(0,i.useEffect)(()=>{let e=e9.current;if(!tQ||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t4.current)return;if(!eu){t2.current=e.scrollHeight-e.scrollTop,tX(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!ec||ec===nt.current)return;let n=o?.id??e6.current;n&&(t4.current=!0,t2.current=e.scrollHeight-e.scrollTop,nn(n,ec).finally(()=>{t4.current=!1}))},{root:e,threshold:0});return t.observe(tQ),()=>t.disconnect()},[tQ,tG,ec,eu,o,nn,e6,e9]),(0,i.useEffect)(()=>{tX(e=>Math.max(e,el.length))},[el.length]),(0,i.useEffect)(()=>{if(null==t2.current)return;let e=e9.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t2.current),t2.current=null}},[tG,e9]);let nr=eW?[eW.sessionId,eW.sessionFile??"",eW.sessionName??"",eW.userMessages,eW.assistantMessages,eW.toolCalls,eW.toolResults,eW.totalMessages,eW.tokens.input,eW.tokens.output,eW.tokens.cacheRead,eW.tokens.cacheWrite,eW.tokens.total,eW.cost??0,eW.totalActiveMs??0].join("|"):null,ni=(0,i.useRef)(eW);ni.current=eW,(0,i.useEffect)(()=>{M?.(ni.current)},[nr,M]),(0,i.useEffect)(()=>()=>{M?.(null)},[M]);let ns=e$?`${e$.percent??"null"}|${e$.contextWindow}|${e$.tokens??"null"}`:null,nl=(0,i.useRef)(e$);nl.current=e$,(0,i.useEffect)(()=>{A?.(nl.current)},[ns,A]),(0,i.useEffect)(()=>()=>{A?.(null)},[A]);let no=(0,i.useCallback)(async e=>{let t=o?.cwd??h;if(!t)return void eG({type:"warning",message:K("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await tO(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let l=s.uploaded??[],o=s.skipped??[],a=(n=[...l,...o],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>tW(e.name,!1)).join(""));for(let e of(a&&S?.current?.insertText(a),l.length>0&&(eG({type:"success",message:K("chat.dropUploaded",{count:l.length})}),z?.()),o.length>0&&eG({type:"warning",message:K("chat.dropAlreadyExists",{names:o.join(", ")})}),s.errors??[]))eG({type:"error",message:K("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){eG({type:"error",message:K("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[eG,S,h,z,o?.cwd,K]),na=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&S?.current?.addImages(t),r.length>0&&eG({type:"warning",message:K("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&no(n)},[eG,S,K,no]),nd=(0,i.useCallback)(e=>{na(e.map(e=>({kind:"file",file:e})))},[na]),{isDragOver:nc,handleDragEnter:nu,handleDragOver:np,handleDragLeave:nh,handleDrop:nf}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{tF(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),l=(0,i.useCallback)(e=>{tF(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:l,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(tD(t.dataTransfer))},[e])}}(na),nm=el.filter(e=>rj(e)||"assistant"===e.role),ng=(0,i.useMemo)(()=>{let e=new Map(eo);for(let t of el)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eo,el]),nx=(0,i.useMemo)(()=>new WeakMap,[]),nv=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=el.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(el[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[el]),nb=(t=nm.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),ny=(0,i.useCallback)(()=>{tX(e=>Math.max(e,2*el.length))},[el.length]),nw=e8&&0===el.length&&!tE&&!tT;ti(e9,!!o?.id||!nw);let nj=o?.cwd??h??void 0,nk=(0,i.useRef)(null),nS=(0,i.useRef)(0),nC=(0,i.useRef)(null),nN=(0,i.useRef)(!1),n$=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nk.current;if(!ef||!tt){n$.current=null,nS.current=0,nN.current=!1,e&&(e.style.height="");return}let t=e9.current,n=t1.current,r=e7.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let l;if(i||e9.current!==t||t1.current!==n||e7.current!==r||nk.current!==e)return;let o=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-o+t.scrollTop-16),d=e.getBoundingClientRect().top-o+t.scrollTop,c=(s=t.clientHeight,0===(l=Math.max(0,a))?0:Math.max(0,Math.ceil(l+s-Math.max(0,d)))),u=!nN.current;u&&(nN.current=!0),c!==nS.current&&(nS.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tk())};n$.current=s,s();let l="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nC.current||(nC.current=requestAnimationFrame(()=>{nC.current=null,s()}))});return l?.observe(t),l?.observe(n),l?.observe(r),()=>{i=!0,n$.current===s&&(n$.current=null),l?.disconnect(),null!==nC.current&&(cancelAnimationFrame(nC.current),nC.current=null)}},[ef,e7,el.length,tt,e9,tk]);let nE=(0,i.useCallback)(()=>{n$.current?.()},[]);(0,i.useLayoutEffect)(nE,[tE,tI,nE]);let nI=eL?ej[`${eL.provider}:${eL.modelId}`]??null:null,nM=eL?ek[`${eL.provider}:${eL.modelId}`]??null:null,nT=(0,r.jsx)(an,{ref:S,onSend:tn,onAbort:tr,onSteer:ef?tu:void 0,onFollowUp:ef?tp:void 0,onPromptWithStreamingBehavior:ef?th:void 0,isStreaming:tT,model:eL,isAutoModelSelection:eX,modelNames:ex,modelList:ev,modelError:eb,missingCwd:ey,modelScopeWarnings:ew,onModelChange:ta,modelSwitching:eP,defaultModel:e1,onSetDefaultModel:ty,onCompact:o||e8?td:void 0,onAbortCompaction:tf,isCompacting:eI,compactError:eR,onDismissCompactError:tm,compactResult:eA,toolPreset:eS,onToolPresetChange:o||e8?tv:void 0,thinkingLevel:eC,isAutoThinkingSelection:eQ,onThinkingLevelChange:o||e8?tb:void 0,availableThinkingLevels:nI,thinkingLevelMap:nM,savedDefaultThinkingLevel:e2,onSetDefaultThinkingLevel:o||e8?tw:void 0,retryInfo:eN,queuedMessages:eD,inputHistory:nv,onRecallQueue:tg,slashCommands:eO,slashCommandsLoading:eF,onLoadSlashCommands:tj,onBuiltinCommand:tx,soundEnabled:B,onSoundToggle:H,onAudioUnlock:U,draftKey:o?.id??f??void 0,cwd:o?.cwd??h,onAttachFiles:nd});return ei?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:K("chat.loadingSession")}):es?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:es}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nu,onDragOver:np,onDragLeave:nh,onDrop:nf,children:[nc&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:36*!V,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(df,{notices:eB,floating:!0,onPauseChange:eY})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eH&&(0,r.jsx)(dx,{request:eH,waitingCount:e_,onRespond:eZ},eH.id),eU&&(0,r.jsx)(dv,{request:eU,waitingCount:eq,onInput:eJ},eU.id),!nw&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:e9,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ee?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t1,onPointerUp:tV,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,s=-1;for(let e=el.length-1;e>=0;e--)if("user"===el[e].role){s=e;break}let l=-1;for(let e=el.length-1;e>=0;e--)if(rj(el[e])){l=e;break}let a=new Map,d=0;el.forEach((e,t)=>{(rj(e)||"assistant"===e.role)&&a.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??el[e];if(rw(n))return null;let l=!1===t.withNotices?[]:sJ(el[e]),d=rj(n)||"assistant"===n.role,c=a.get(e),u=t.keyPrefix??"message",p=ed[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<el.length;t++){let e=el[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tE&&e===el.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let f=(0,r.jsx)(s5,{message:n,toolResults:ng,modelNames:ex,cwd:nj,onOpenFile:L,onOpenSubagent:P,entryId:ea[e],searchBlock:ea[e]===t5?.entryId?t7:void 0,onFork:em||e8?void 0:ts,forking:eE===ea[e],onEditContent:tT?void 0:tl,onCancelEdit:to,isEditing:e3===ea[e],showTimestamp:h,prevTimestamp:e>0?el[e-1].timestamp:void 0,sessionId:o?.id??e6.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?td:void 0,isCompacting:t.recoverTruncation?eI:void 0,compactError:t.recoverTruncation?eR:void 0},`${u}-view-${p}`),m=l.length>0?(0,r.jsx)(s0,{notices:l},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":ea[e],ref:!1===t.attachRef?void 0:t=>{nb.current[c]=t,e===s&&(e7.current=t)},children:[f,m]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[f,m]},`${u}-${p}`)},u=[];for(let e=0;e<el.length;){let t,n=rj(el[e]);if(!n&&0!==e){u.push(c(e)),e+=1;continue}let i=n?e:-1,s=n?e:0,o=e+1;for(;o<el.length&&!rj(el[o]);)o+=1;let d=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&rE(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(el,i,o);if(-1===d||(tT||tE)&&o===el.length&&i===l){for(let e=s;e<o;e++)u.push(c(e));e=o;continue}n&&u.push(c(i));let p=n&&ea[i]?function(e,t,n){let r,i,s,l=rV(e[t]?.timestamp);if(void 0===l)return;let o=!1,a=0;for(let l=t+1;l<n;l++){let t=e[l];if("assistant"===t.role){var d;void 0!==i&&void 0!==s&&(a+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=rV(e.timestamp),n=rV(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);o=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(d=t).role&&("stop"===d.stopReason||"length"===d.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=rV(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=rV(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(o&&void 0!==r)return Math.max(0,r-l-a)}(el,i,o):void 0,h=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=rE(t),i=r.length>0||rC(t)||rN(t)?rK(t,r):null,s=t.content.indexOf(r[0]),l={answer:i,process:rK(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i})};return e.set(t,l),l}(nx,el[d]),f=h.answer,m=[],g=0,x=0,v=!1;for(let e=i+1;e<=d;e++){let n=el[e];if("custom"===n.role){if(rw(n))continue;v||=!!(t5&&t5.entryId===ea[e]),g+=1,m.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===d?h.process:n,s=e!==d||!f,l=rS(i);if(0===l.length){let t=s?sJ(n):[];t.length>0&&m.push((0,r.jsx)(s0,{notices:t},`process-notices-${ed[e]}`));continue}t??=a.get(e),x+=l.filter(e=>"toolCall"===e.type).length,g+=1,v||=!!(t5&&ea[e]===t5.entryId&&(!t7||l.includes(t7))),m.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===g)u.push(...m);else if(m.length>0){let e=(f?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),n=function(e){let t;for(let n of e)for(let e of sJ(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(el.slice(i+1,f?d:d+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nb.current[t]=e},children:(0,r.jsx)(du,{messageCount:g,toolCallCount:x,durationMs:p,cacheMisses:n,defaultExpanded:!e,reveal:v,t:K,children:m},e?"answered":"unanswered")},`process-group-${ed[s]}`))}if(f){let e=[];for(let t=i+1;t<=d;t++){let n=el[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t){let n=e.writtenFiles;return n&&n.length===t.length&&n.every((e,n)=>e.filePath===t[n].filePath)?n:(e.writtenFiles=t,t)}(h,function(e,t,n){let r=new Set,i=[];for(let l of e){var s;if("toolCall"!==l.type||!(rP(s=l.toolName)||rW(s))&&!rO(l.toolName))continue;let e=t?.get(l.toolCallId);if(e&&!e.isError)for(let t of rO(l.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of rF(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!rD(e)||!rD(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(rB(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=rq(rU(n.preview));if(e.length>0)return e}return rq(r_(rF(e)))}(l.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(l.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),l=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(s),a=s.startsWith("//");if(o||a)n=s;else if(s.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!l)return null;n=`${l}/${s}`}return rR(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,ng,nj));u.push(c(d,{messageOverride:f,writtenFiles:t,turnDurationMs:0===m.length?p:void 0,recoverTruncation:o===el.length&&!tE&&!r$(f)}))}for(let e=d+1;e<o;e++)u.push(c(e));e=o}let{startIndex:p}=(t=Math.min(Math.max(tG,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||eu;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t0,className:"py-3 text-center text-xs text-text-muted",children:K("chat.loadEarlier")}),u.slice(p)]})})(),tE&&tI&&(0,r.jsx)(dh,{store:eh,onCommit:nE,toolResults:ng,modelNames:ex,cwd:nj,onOpenFile:L,onOpenSubagent:P}),(ef||eI)&&!tI&&(e4||eI)&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(n)return r>0?t("chat.compactingQueued",{count:r}):t("chat.compacting");if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(e4,K,eI,(eD?.steering.length??0)+(eD?.followUp.length??0))})}),em&&!eg&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:K("chat.runningCommand")})}),eg&&(0,r.jsx)(s5,{message:{role:"bashExecution",command:eg.command,output:"",excludeFromContext:eg.excludeFromContext},sessionId:o?.id??e6.current??void 0,onOpenSubagent:P}),(0,r.jsx)("div",{ref:nk,"aria-hidden":"true"})]})})}),V||ee?null:(0,r.jsx)(ah,{messages:el,getStreamingMessage:tM,scrollContainer:e9,messageRefs:nb,onRevealHistory:ny,turnsBefore:ep})]})]}),O&&tR&&(0,tc.createPortal)((0,r.jsx)("div",{ref:tU,role:tL?"dialog":"toolbar","aria-label":K(tL?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tR.top,left:tR.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tL?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tL?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tL?(0,r.jsxs)("fieldset",{disabled:tP,"aria-busy":tP,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:K("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:K("i18n.close"),"aria-label":K("i18n.close"),disabled:tP,onClick:tK,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(an,{ref:tq,compact:!0,onSend:tJ,onAbort:tK,isStreaming:!1}),tH&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tH})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:K("chat.askInCurrent"),"aria-label":K("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tZ,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{fontSize:15},children:"@"}),(0,r.jsx)("span",{children:K("chat.askInCurrent")})]}),W&&tR.sourceEntryId&&!em&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:K("chat.askInNewChat"),"aria-label":K("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tz(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:K("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nw&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!V,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${e5&&!ee?" is-visible":""}`,title:K("chat.scrollToLatest"),"aria-label":K("chat.scrollToLatest"),onClick:()=>tN("smooth"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nw&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:V?16:52},children:(0,r.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,r.jsxs)("div",{className:"new-session-brand",children:[(0,r.jsx)(rc.default,{src:"/icons/apple-touch-icon.png",width:40,height:40,alt:"",priority:!0,className:"new-session-logo"}),(0,r.jsxs)("div",{className:"new-session-brand-text",children:[(0,r.jsx)("span",{className:"new-session-brand-name",children:"Pi Web"}),(0,r.jsxs)("span",{className:"new-session-meta",children:[(0,r.jsxs)("span",{children:["web v","0.12.8"]}),(0,r.jsx)(dc,{label:e=>K("appUpdate.releaseNotes",{version:e})}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,r.jsxs)("span",{className:"new-session-meta-pi",children:["pi v","1.4.0"]})]})]})]}),m]})}),nT,(0,r.jsx)(av,{statuses:eK,widgets:eV,onCommand:tn,commandsDisabled:tT})]}),nw&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}let dh=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d}=e,c=dr(t,dl);return((0,i.useLayoutEffect)(n,[c,n]),c)?(0,r.jsx)(s5,{message:c,toolResults:s,isStreaming:!0,modelNames:l,cwd:o,onOpenFile:a,onOpenSubagent:d}):null});function df(e){let{notices:t,floating:n=!1,onPauseChange:i}=e;return 0===t.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,s)=>{var l;let o,a,d,c="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>i?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||i?.(null)},onFocus:()=>i?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||i?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(s!==t.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:n?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c,flexShrink:0,marginTop:25.5}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"18.5px 0",minWidth:0,maxWidth:"100%",maxHeight:498,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:(l=e.message,o=[],a=(e,t)=>{if(!t)return;let n=o[o.length-1];n?.kind===e?n.text+=t:o.push({kind:e,text:t})},d=!1,l.split("\n").forEach((e,t)=>{let n=rv.test(e);t>0&&a(n&&d?"art":"text","\n"),a(n?"art":"text",e),d=n}),o).map((e,t)=>"art"===e.kind?(0,r.jsx)("span",{style:{display:"inline-block",verticalAlign:"top",maxWidth:"100%",overflowX:"auto",whiteSpace:"pre",fontFamily:"Menlo, Consolas, 'DejaVu Sans Mono', monospace",lineHeight:1,color:"var(--text)"},children:e.text},t):e.text)})]},e.id)})})}function dm(e){let{count:t}=e,{t:n}=(0,e0.s)();return t<=0?null:(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function dg(e){let{expanded:t}=e;return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t?(0,r.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,r.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function dx(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:l}=(0,e0.s)(),[o,a]=(0,i.useState)("editor"===t.method?t.prefill??"":""),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),w=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(t),j=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,i.useLayoutEffect)(()=>{if(d)return;let e=u.current,t=p.current;if(!e||!t)return;let n=!1,r=()=>{if(n)return;let r=t.querySelectorAll("pre, .markdown-table-wrap");if(0===r.length)return;t.classList.add("extension-dialog-measuring");let i=Array.from(r,e=>e.scrollWidth-e.clientWidth);t.classList.remove("extension-dialog-measuring");let s=function(e,t){let n=0;for(let e of t)e>1&&e>n&&(n=e);return 0===n?null:40*Math.ceil((e+n)/40)}(e.offsetWidth,i);null!==s&&f(e=>null!==e&&e>=s?e:s)};r();let i=new MutationObserver(r);return i.observe(t,{childList:!0,subtree:!0,characterData:!0}),document.fonts?.ready.then(r),()=>{n=!0,i.disconnect()}},[d]),(0,i.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let k=null!==j&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:l("chat.extensionExpiresIn",{seconds:j})}),S=()=>{"confirm"===t.method?s(t,{confirmed:!0}):s(t,{value:o})};return(0,r.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),s(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:l("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:t.title}),w&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:w}),(0,r.jsx)(dm,{count:n}),k,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:l("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":t.title,style:{pointerEvents:"auto",width:m?"100%":`min(${h??560}px, 100%)`,maxHeight:m?"100%":"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:1,minHeight:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)",maxHeight:"50vh",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:l("chat.extensionRequest")}),(0,r.jsx)(dm,{count:n}),k]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:l(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":l(m?"chat.extensionRestoreSize":"chat.extensionMaximize"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(dg,{expanded:m})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:l("chat.extensionCollapse"),"aria-label":l("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,r.jsx)(sk,{children:t.message}),"select"===t.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:t.options.map((e,n)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":e,ref:0===n?y:void 0,onClick:()=>s(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),s(t,{value:e}))},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(sk,{children:e})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:t.placeholder,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||S()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===t.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&S()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>s(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:l("chat.cancel")}),"confirm"===t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:l("chat.confirm")}):"select"!==t.method?(0,r.jsx)("button",{onClick:S,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:l("chat.submit")}):null]})]})})}function dv(e){let{request:t,waitingCount:n,onInput:s}=e,{t:l}=(0,e0.s)(),o=(0,i.useRef)(null),a=(0,i.useRef)(!1),[d,c]=(0,i.useState)(!1),u=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(rh,""),i=rf(e).trimEnd();if(t.test(i))continue;let s=e,l=rx(s);("│"===l||"┃"===l)&&" "===rx(s=rg(s,0))&&(s=rg(s,0));let o=function(e){let t=rm(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=o>=0?rm(s)[o]?.char:void 0;("│"===a||"┃"===a)&&(s=rg(s,o)),n.push(function(e){let t=e;for(;;){let e=rm(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===rf(n[0]).trim();)n.shift();for(;n.length>0&&""===rf(n[n.length-1]).trim();)n.pop();return n.length?n:e}(t.lines),p=u.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{d||o.current?.focus()},[d]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:d?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:d?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:l("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:l("chat.extensionPanel")}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,r.jsx)(dm,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:l("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||o.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"max-content",minWidth:"min(920px, 100%)",maxWidth:"100%",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:o,"aria-label":l("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=ry[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":rb[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(a.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&s(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&s(t,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:l("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(dm,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:l("chat.extensionCollapse"),"aria-label":l("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>s(t,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:l("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(am,{text:u.join("\n")})})]})})}let db=null,dy="";function dw(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:l,onPick:o,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,e0.s)(),[h,f]=(0,i.useState)(()=>dy),m=(0,i.useRef)(null),g=(0,i.useRef)(s),x=(0,i.useRef)(l);return x.current=l,(0,i.useEffect)(()=>{if(dy)return;let e=!1;return(db??=fetch("/api/home").then(e=>e.json()).then(e=>dy=e.home??"").catch(()=>(db=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=g.current;if(!e)return;g.current=null,x.current();let t=m.current;eI(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(n8,{handleRef:m,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:o,onUseDefaultDirectory:a,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}function dj(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function dk(e,t){return null===e||null===t||e!==t}var dS=n(73620);let dC=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function dN(e){let t=function(e){let t=dC.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,dS.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}function d$(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let dE=[",",";"," ","|"];function dI(e){let t=/\.(csv|tsv)$/i.exec(e);return t?"tsv"===t[1].toLowerCase()?" ":",":null}function dM(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.complete??!0,i=n.maxRecords??1/0,s=[],l=[],o=e.length,a=t.charCodeAt(0),d=+(65279===e.charCodeAt(0)),c=1,u=[],p=1,h=()=>{(1!==u.length||""!==u[0])&&(s.push(u),l.push(p)),u=[]};for(;d<o&&s.length<i;){let t="",n=!1;if(34===e.charCodeAt(d)){n=!0;let r=d+=1;for(;d<o;){let i=e.indexOf('"',d);if(-1===i)break;if(34===e.charCodeAt(i+1)){t+=e.slice(r,i+1),r=d=i+2;continue}t+=e.slice(r,i),d=i+1,n=!1;break}n&&(t+=e.slice(r),d=o),c+=function(e){let t=0,n=e.indexOf("\n");for(;-1!==n;)t+=1,n=e.indexOf("\n",n+1);return t}(t)}let i=d;for(;i<o;){let t=e.charCodeAt(i);if(t===a||10===t)break;i+=1}let s=i<o?e.charCodeAt(i):-1,l=s!==a&&i>d&&13===e.charCodeAt(i-1)?i-1:i;t+=e.slice(d,l),u.push(t),d=i,s===a?(d+=1)===o&&(u.push(""),r&&h()):10===s?(d+=1,c+=1,h(),p=c):r&&h()}return{records:s,lines:l}}function dT(e){let t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t),r=0;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);t>=56320&&t<=57343||(r+=t>=11904?2:1)}return r}let dR={display:"flex",height:26,boxSizing:"border-box",borderBottom:"1px solid var(--border)"},dA={position:"sticky",left:0,zIndex:1,boxSizing:"border-box",width:56,flexShrink:0,padding:"0 10px",display:"flex",alignItems:"center",justifyContent:"flex-end",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontSize:11,fontVariantNumeric:"tabular-nums",userSelect:"none"},dL={boxSizing:"border-box",flexShrink:0,padding:"0 10px",lineHeight:"25px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderRight:"1px solid var(--border)"};function dz(e){let{content:t,filePath:n,complete:s,scrollRef:l}=e,o=(0,i.useMemo)(()=>(function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=dI(t)??",",i=","===r?function(e){let t=e.slice(0,65536),n=t.length===e.length,r=",",i=0;for(let e of dE){let{records:s}=dM(t,e,{complete:n,maxRecords:20}),l=s[0]?.length??0;if(l<2)continue;let o=1e3*s.filter(e=>e.length===l).length+Math.min(l,999);o>i&&(r=e,i=o)}return r}(e):r,{records:s,lines:l}=dM(e,i,{complete:n});if(0===s.length)return{columns:[],headerLine:0,rows:[],rowLines:[]};let o=0;for(let e of s)e.length>o&&(o=e.length);let a=s[0];return{columns:a.length===o?a:[...a,...Array.from({length:o-a.length},()=>"")],headerLine:l[0],rows:s.slice(1),rowLines:l.slice(1)}})(t,n,s),[s,t,n]),a=(0,i.useMemo)(()=>{var e,t;let n;return e=o.columns,n=Math.max(1,Math.ceil((t=o.rows).length/500)),e.map((e,r)=>{let i=dT(e);for(let e=0;e<t.length;e+=n){let n=t[e][r];if(n){let e=dT(n);e>i&&(i=e)}}return Math.min(Math.max(Math.ceil(7.4*i+22),64),420)})},[o]),d=(0,i.useMemo)(()=>a.reduce((e,t)=>e+t,56),[a]),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(0);if((0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=null,n=()=>{u(e.scrollTop),h(e.clientHeight)},r=()=>{null===t&&(t=requestAnimationFrame(()=>{t=null,n()}))};n(),e.addEventListener("scroll",r,{passive:!0});let i="u"<typeof ResizeObserver?null:new ResizeObserver(n);return i?.observe(e),()=>{e.removeEventListener("scroll",r),i?.disconnect(),null!==t&&cancelAnimationFrame(t)}},[l]),0===o.columns.length)return null;let{start:f,end:m}=function(e,t,n){if(e<=0)return{start:0,end:0};let r=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(n)&&n>0?n:800,s=Math.max(0,Math.floor(r/26)-20),l=Math.min(e,Math.ceil((r+i)/26)+20);return{start:Math.min(s,l),end:l}}(o.rows.length,c-26,p),g=[];for(let e=f;e<m;e+=1){let t=o.rows[e];g.push((0,r.jsxs)("div",{role:"row","aria-rowindex":e+2,style:{...dR,position:"absolute",top:26*e,left:0,width:d},children:[(0,r.jsx)("div",{role:"rowheader",style:dA,children:o.rowLines[e]}),a.map((e,n)=>{let i=t[n]??"";return(0,r.jsx)("div",{role:"cell",style:{...dL,width:e},title:i||void 0,children:i},n)})]},e))}return(0,r.jsxs)("div",{role:"table","aria-rowcount":o.rows.length+1,"aria-colcount":o.columns.length,style:{width:d,minWidth:"100%",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:12,color:"var(--text-muted)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{role:"row","aria-rowindex":1,style:{...dR,position:"sticky",top:0,zIndex:2,width:d,background:"var(--bg-panel)",color:"var(--text)",fontWeight:600},children:[(0,r.jsx)("div",{role:"rowheader",style:dA,children:o.headerLine}),o.columns.map((e,t)=>(0,r.jsx)("div",{role:"columnheader",style:{...dL,width:a[t]},title:e||void 0,children:e},t))]}),(0,r.jsx)("div",{style:{position:"relative",height:26*o.rows.length},children:g})]})}let dP=["tags","categories","keywords","tag","category"];function dW(e){var t;let{data:n}=e;if(!n)return null;let i=Object.entries(n);if(0===i.length)return null;let s="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,l=dP.find(e=>Array.isArray(n[e])),o=l?n[l].map(d$).filter(Boolean):[],a=i.filter(e=>{let[t]=e;return t!==l&&("title"!==t||!s)});return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),o.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:o.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),a.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:a.map(e=>{let[t,n]=e;return(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:t}),(0,r.jsx)("dd",{children:function(e){let t=d$(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(n)})]},t)})})]})}let dO={source:"Source",preview:"Preview",diff:"Diff"},dF={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},dD={...iH.xJ,'pre[class*="language-"]':{...iH.xJ['pre[class*="language-"]']}};delete dD['pre[class*="language-"]'].background;let dB={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"},dH={...dB,position:"sticky",left:0,zIndex:1};function d_(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function dU(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function dq(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=dU(n.startContainer),i=dU(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(l))return null;if(s<l){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(l=Number((i=e).dataset.lineNumber))}}}return s>l?null:{startLine:s,endLine:l}}function dK(e){let{rows:t,stylesheet:n,useInlineStyles:i,wrapLines:s}=e;return t.map((e,t)=>{let l=e.children??[],o=l[0]?.properties?.className,a=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,iD.Ay)({node:d,stylesheet:n,useInlineStyles:i,key:`source-line-number-${t}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:s?"anywhere":"normal",whiteSpace:s?"pre-wrap":"pre"},children:c.map((e,r)=>(0,iD.Ay)({node:e,stylesheet:n,useInlineStyles:i,key:`source-token-${t}-${r}`}))})]},`source-line-${t}`)})}function dV(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=tI(e),s=new URLSearchParams({type:t});for(let[e,i]of(n&&s.set("sessionId",n),"watch"===t&&s.set("holder",eT()),Object.entries(r)))void 0!==i&&s.set(e,String(i));return`/api/files/${i}?${s.toString()}`}function dZ(e){let{filePath:t,sourceSessionId:n}=e,{t:i}=(0,e0.s)();return(0,r.jsx)("a",{href:dV(t,"download",n),download:tM(t),title:i("i18n.downloadFile"),"aria-label":i("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function dJ(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function dY(e){let t,{patch:n}=e,{t:i}=(0,e0.s)(),s=(t=s$(n))?t.flatMap(sE):[],l=e=>"added"===e.type||"removed"===e.type;if(!s.some(l))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:i("i18n.noChanges")});let o=new Set(s.flatMap((e,t)=>l(e)?[t]:[])),a=new Set;for(let e of o)for(let t=Math.max(0,e-3);t<=Math.min(s.length-1,e+3);t++)a.add(t);let d=a.size<=1e3?dH:dB,c=e=>"gap"!==s[e].type&&a.has(e),u=[],p=0;for(;p<s.length;)if(c(p)){let e=[];for(;p<s.length&&c(p);){let t=s[p];"gap"!==t.type&&e.push(t),p++}u.push({hidden:!1,lines:e})}else{let e=0;for(;p<s.length&&!c(p);){let t=s[p],n="gap"===t.type?t.count:1;e=null===e||null===n?null:e+n,p++}u.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...dF},children:u.map((e,t)=>{if(e.hidden)return(0,r.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:null===e.count?"⋯":`⋯ ${sI(e.count,i)}`},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:d,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function dG(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=tM(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!l)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=dj(t);dk(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=dj(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,l]);let j=dV(t,"read",s,c?{v:c}:void 0),k=null!=p?dJ(p):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"image"}),f&&(0,r.jsxs)("span",{children:[f.w," \xd7 ",f.h]}),k&&(0,r.jsx)("span",{children:k}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:j,alt:t,onLoad:e=>{let t=e.currentTarget;m({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x(o("files.imageLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function dX(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function dQ(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=tM(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!l)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=dj(t);dk(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=dj(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,l]);let j=dV(t,"read",s,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"audio"}),null!=f&&(0,r.jsx)("span",{children:dX(f)}),null!=p&&(0,r.jsx)("span",{children:dJ(p)}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:j,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x(o("files.audioLoadFailed")),style:{width:"100%"}},j)]})})]})}function d0(e){let{filePath:t,cwd:n,sourceSessionId:s,watchEnabled:l=!0}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=tM(t).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{u(0),h(null),m(null),x(null),d(!1),y.current=null},[t,s]),(0,i.useEffect)(()=>{if(d(!1),v.current&&(v.current.close(),v.current=null),!l)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);v.current=n,n.addEventListener("connected",()=>{let n;d(!0),n=++b.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==b.current)return;if(t.error)return void x(t.error);"number"==typeof t.size&&h(t.size),x(null);let r=dj(t);dk(y.current,r)&&(y.current=r,m(null),u(e=>e+1))}).catch(t=>{e&&n===b.current&&x(String(t))})}),n.addEventListener("change",e=>{b.current+=1,y.current=null;try{let t=JSON.parse(e.data);y.current=dj(t),"number"==typeof t.size&&h(t.size)}catch{}m(null),x(null),u(e=>e+1)});let r=()=>{d(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),v.current===n&&(v.current=null)}},[t,s,l]);let j=dV(t,"read",s,c?{v:c}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"video"}),null!=f&&(0,r.jsx)("span",{children:dX(f)}),null!=p&&(0,r.jsx)("span",{children:dJ(p)}),(0,r.jsxs)("span",{title:a?o("i18n.liveSync"):o("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:j,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>x(o("files.videoLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%"}},j)]})})]})}function d1(e){let{filePath:t,cwd:n,sourceSessionId:s,initialPage:l,watchEnabled:o=!0}=e,{t:a}=(0,e0.s)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(0),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),b=(0,i.useRef)(null),y=r1(t),w="pdf"===y,j=w&&l&&l>0?`#page=${l}`:"",k=w?`${dV(t,"read",s,u?{v:u}:void 0)}${j}`:dV(t,"preview",s,u?{v:u}:void 0);return(0,i.useEffect)(()=>{p(0),f(null),g(null),c(!1),b.current=null;let e=!0,n=++v.current;return fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{e&&n===v.current&&(t.error&&g(t.error),"number"==typeof t.size&&(f(t.size),!w&&t.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===v.current&&g(String(t))}),()=>{e=!1}},[t,w,s]),(0,i.useEffect)(()=>{if(c(!1),x.current&&(x.current.close(),x.current=null),!o)return;let e=!0,n=ez("file-watch",new EventSource(dV(t,"watch",s)),t);x.current=n,n.addEventListener("connected",()=>{let n;c(!0),n=++v.current,fetch(dV(t,"meta",s)).then(e=>e.json()).then(t=>{if(!e||n!==v.current)return;if(t.error)return void g(t.error);if("number"==typeof t.size&&(f(t.size),!w&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null);let r=dj(t);dk(b.current,r)&&(b.current=r,p(e=>e+1))}).catch(t=>{e&&n===v.current&&g(String(t))})}),n.addEventListener("change",e=>{v.current+=1,b.current=null;try{let t=JSON.parse(e.data);if(b.current=dj(t),"number"==typeof t.size&&(f(t.size),!w&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),p(e=>e+1)});let r=()=>{c(!1)};return n.addEventListener("error",r),n.onerror=r,()=>{e=!1,n.close(),x.current===n&&(x.current=null)}},[t,w,s,o]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===y?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:dJ(h)}),(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s}),(0,r.jsxs)("span",{title:a(d?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:d?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:d?"#4ade80":"var(--border)",display:"inline-block",boxShadow:d?"0 0 4px #4ade80":"none"}}),d?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:m?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:m}):(0,r.jsx)("iframe",{src:k,sandbox:w?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:tM(t)}),style:{width:"100%",height:"100%",border:"none",background:w?"var(--bg)":"#eef1f5"}},k)})]})}function d2(e){let t,{filePath:n,cwd:s,sourceSessionId:l,onOpenFile:o,onMentionLines:a,onAtMention:d,gitRefreshKey:c,initialDisplayMode:u,initialState:p,initialPage:h,onStateChange:f,watchEnabled:m=!0}=e,g=function(){let e=(0,i.useSyncExternalStore)(aV,aZ,aJ),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{if(!e)return void n(!1);let t=setTimeout(()=>n(!0),3e4);return()=>clearTimeout(t)},[3e4,e]),e&&t}(),x=m&&!g;return null!==(rX[r1(n)]??null)?(0,r.jsx)(dG,{filePath:n,cwd:s,sourceSessionId:l,watchEnabled:x}):r2(n)?(0,r.jsx)(dQ,{filePath:n,cwd:s,sourceSessionId:l,watchEnabled:x}):r4(n)?(0,r.jsx)(d0,{filePath:n,cwd:s,sourceSessionId:l,watchEnabled:x}):null!==("pdf"===(t=r1(n))||"docx"===t?t:null)?(0,r.jsx)(d1,{filePath:n,cwd:s,sourceSessionId:l,initialPage:h,watchEnabled:x}):(0,r.jsx)(d4,{filePath:n,cwd:s,sourceSessionId:l,onOpenFile:o,onMentionLines:a,onAtMention:d,gitRefreshKey:c,initialDisplayMode:u,initialState:p,onStateChange:f,watchEnabled:x})}function d4(e){let{filePath:t,cwd:n,sourceSessionId:s,onOpenFile:l,onMentionLines:o,onAtMention:a,gitRefreshKey:d,initialDisplayMode:c,initialState:u,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=i5(),{t:m}=(0,e0.s)(),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(!1),[j,k]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!0),[N,$]=(0,i.useState)(!1),[E,I]=(0,i.useState)(null),M=u?.displayMode??c??"source",T=u?.wrapLines??!1,R=u?.scrollTop??0,A=u?.scrollLeft??0,[L,z]=(0,i.useState)(M),[P,W]=(0,i.useState)(T),[O,F]=(0,i.useState)(!1),D=(0,i.useRef)(null),B=(0,i.useRef)(0),H=(0,i.useRef)(null),_=(0,i.useRef)(0),U=(0,i.useRef)(null),q=(0,i.useRef)(!1),K=(0,i.useRef)(void 0===u&&void 0===c),V=(0,i.useRef)(!0),Z=(0,i.useRef)({displayMode:M,wrapLines:T,scrollTop:R,scrollLeft:A}),J=(0,i.useRef)(p),[Y,G]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null);J.current=p;let ee=(0,i.useCallback)(e=>{Z.current.displayMode=e,z(e)},[]),et=(0,i.useCallback)(()=>{W(e=>{let t=!e;return Z.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Z.current={displayMode:M,wrapLines:T,scrollTop:R,scrollLeft:A},V.current=!0,q.current=!1,z(M),W(T),()=>{J.current?.({...Z.current})}),[t,s,M,T,R,A]);let en=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++B.current;return fetch(dV(e,"read",s,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==B.current?null:e.error?(I(e.error),null):(H.current=dj(e),I(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==B.current||I(String(e)),null))},[s]),er=(0,i.useCallback)(async e=>{let t=++_.current;if(w(!0),!n){b(null),w(!1),k(!0);return}try{let r=new URLSearchParams({cwd:n,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(t!==_.current)return;b(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{t===_.current&&b(null)}finally{t===_.current&&(w(!1),k(!0))}},[n]);(0,i.useEffect)(()=>{let e=!0;return C(!0),I(null),x(null),b(null),k(!1),F(!1),H.current=null,en(t).finally(()=>{e&&C(!1)}),()=>{e=!1}},[t,en,s]),(0,i.useEffect)(()=>{if(F(!1),D.current&&(D.current.close(),D.current=null),!h)return;let e=!0,n=()=>{en(t),er(t)},r=ez("file-watch",new EventSource(dV(t,"watch",s)),t);D.current=r,r.addEventListener("connected",()=>{(F(!0),null===H.current)?n():fetch(dV(t,"meta",s)).then(e=>e.json()).then(r=>{e&&(dk(H.current,dj(r))?n():er(t))}).catch(()=>{e&&n()})}),r.addEventListener("change",n);let i=()=>{F(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{e=!1,r.close(),D.current===r&&(D.current=null)}},[t,en,er,s,h]),(0,i.useEffect)(()=>{er(t)},[er,t,d]);let ei=g?.binary===!0,es=!ei&&null!==dI(t);(0,i.useEffect)(()=>{K.current&&g&&!g.binary&&(es||"markdown"===g.language&&!g.truncated||"html"===g.language&&(!g.truncated||g.size<=0xa00000))&&(K.current=!1,ee("preview"))},[g,es,ee]);let el="preview"===L&&g?.language==="html"&&g.truncated&&g.size<=0xa00000;(0,i.useEffect)(()=>{if(!el)return void Q(null);let e=new AbortController;return fetch(dV(t,"download",s),{signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);Q({text:await e.text()})}).catch(t=>{e.signal.aborted||Q({error:String(t)})}),()=>e.abort()},[el,g,t,s]);let eo=v?.supported===!0&&"string"==typeof v.patch,ea=eo&&"deleted"===v.status;(0,i.useEffect)(()=>{j&&!eo&&"diff"===L&&ee("source")},[L,j,eo,ee]),(0,i.useEffect)(()=>{"diff"===M&&eo&&!q.current&&(q.current=!0,ee("diff"))},[M,eo,ee]);let ed=(0,i.useMemo)(()=>g?.language==="markdown"?ih(g.content):"",[g]),ec=(0,i.useMemo)(()=>g?.language==="markdown"?dN(g.content):null,[g]),eu=g?.content??"",ep=(0,i.useMemo)(()=>eu.split("\n"),[eu]),eh=g?.language??"text",ef=se(!!g&&"text"!==eh),em=!ei&&"html"===eh,eg=!ei&&"markdown"===eh,ex=es||(em?!!g&&(!g.truncated||g.size<=0xa00000):eg&&!g?.truncated),ev=ea?"diff":L,eb=!!g?.truncated&&!(em&&"preview"===ev),ey=ep.length>1e3&&!("diff"===ev&&eo)&&!("preview"===ev&&ex),ew=(0,i.useMemo)(()=>(0,r.jsx)(iB.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"!==eh&&ef?eh:"plaintext",style:f?dD:iH.vs,showLineNumbers:!0,lineNumberStyle:{...dH},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...dF,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(dK,{...e,wrapLines:P}),wrapLongLines:P,children:eu}),[f,eh,ef,eu,P]),ej=(0,i.useMemo)(()=>ey?ep.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:dB,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:P?"anywhere":"normal",whiteSpace:P?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[ep,ey,P]);(0,i.useEffect)(()=>{let e=()=>{let e=U.current;G(t=>{let n=o&&"source"===L&&e?dq(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),o&&"source"===L)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,L,o]);let ek=(0,i.useCallback)(e=>{o&&e&&o(tR(t,n),e.startLine,e.endLine)},[n,t,o]);if((0,i.useEffect)(()=>{if(!o||"source"!==L)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=U.current,r=n?dq(n,window.getSelection()):null;r&&(e.preventDefault(),ek(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[L,ek,o]),(0,i.useEffect)(()=>{if(!V.current||S||E&&!ea||"diff"===M&&!j||"diff"===M&&eo&&"diff"!==L)return;let e=U.current;e&&(e.scrollTop=Z.current.scrollTop,e.scrollLeft=Z.current.scrollLeft,V.current=!1)},[g?.content,L,E,j,eo,ea,S,M]),S||"diff"===M&&y&&!g)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:m("i18n.loading")});if(E&&!ea)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:E});if(!g&&!ea)return null;let eS=tT(t),eC=ea?["diff"]:["source",...ex?["preview"]:[],...eo?["diff"]:[]],eN=ea?m("files.deleted"):ei?`${m("files.binary")} \xb7 ${dJ(g.size)}`:`${eh} \xb7 ${ep.length} lines \xb7 ${dJ(g.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:t,children:tR(t,n)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eN,children:eN}),!ea&&(0,r.jsx)("span",{title:O?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":O?m("i18n.liveSync"):m("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:O?"#4ade80":"var(--border)",boxShadow:O?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[eC.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:eC.map(e=>{let t=ev===e;return(0,r.jsx)("button",{type:"button",onClick:()=>ee(e),title:"diff"===e?m("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:dO[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(a||o)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{Y&&o?ek(Y):a?.(tR(t,n),!1)},title:Y&&o?`${m("i18n.mentionSelectedLines")} (L${Y.startLine}${Y.startLine!==Y.endLine?`-L${Y.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!a&&!o,className:"file-viewer-icon-button",children:(0,r.jsx)(d_,{})}),"source"===ev&&!ei&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:et,title:P?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-label":P?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-pressed":P,className:"file-viewer-icon-button",style:{background:P?"var(--bg-selected)":"transparent",color:P?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!ea&&(0,r.jsx)(dZ,{filePath:t,sourceSessionId:s})]})]}),eb&&g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,r.jsxs)("span",{children:[dJ(g.nextOffset)," / ",dJ(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:N,onClick:()=>{$(!0),en(t,g.nextOffset).finally(()=>$(!1))},children:N?m("i18n.loading"):m("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:U,className:"file-viewer-content",onScroll:e=>{Z.current.scrollTop=e.currentTarget.scrollTop,Z.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:eb?48:void 0},children:"diff"===ev&&eo?(0,r.jsx)(dY,{patch:v.patch}):em&&"preview"===ev&&g?.truncated&&!X?.text?(0,r.jsx)("div",{style:{padding:24,color:"var(--text-dim)",fontSize:12},children:X?.error??m("i18n.loading")}):em&&"preview"===ev?(0,r.jsx)("iframe",{srcDoc:g?.truncated?X?.text:eu,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):eg&&"preview"===ev?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ec?.data&&(0,r.jsx)(dW,{data:ec.data}),(0,r.jsx)(rY.oz,{remarkPlugins:iE,rehypePlugins:iL,urlTransform:l?ia:io,components:{code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?"mermaid"===s?(0,r.jsx)(sa,{code:l.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(sm,{code:l.replace(/\n$/,""),lang:s}):(0,r.jsx)("code",{className:t,...i,children:n})},pre(e){let{children:t}=e;return(0,r.jsx)(r.Fragment,{children:t})},a(e){let{href:t,children:i,...s}=e;delete s.node;let o=l?rA(t,eS,n??eS):null;return o&&l?(0,r.jsx)("a",{href:t,...s,onClick:e=>{rI(e)&&(e.preventDefault(),l(o,rz(t)??void 0))},children:i}):id(t)?(0,r.jsx)("a",{href:t,...s,target:"_blank",rel:"noopener noreferrer",children:i}):(0,r.jsx)("a",{href:t,...s,onClick:ic,children:i})},img(e){let{src:t,alt:i,...l}=e;delete l.node;let o="string"==typeof t?rA(t,eS,n??eS):null,a=o?dV(o,"read",s):t;return(0,r.jsx)("img",{src:a,alt:i??"",loading:"lazy",...l})}},children:ed})]}):es&&"preview"===ev?(0,r.jsx)(dz,{content:eu,filePath:t,complete:!g?.truncated,scrollRef:U}):ei?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,padding:24,color:"var(--text-muted)",fontSize:13,textAlign:"center"},children:[(0,r.jsx)("span",{children:m("files.binaryNoPreview")}),(0,r.jsx)("a",{href:dV(t,"download",s),download:tM(t),className:"file-viewer-mode-button",style:{display:"inline-flex",alignItems:"center",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",textDecoration:"none"},children:m("files.download")})]}):ey?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...dF},children:ej}):ew})]})}function d8(e){let{tabs:t,activeTabId:n,onSelectTab:s,onCloseTab:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=c.current;if(!e)return;let t=t=>{t.ctrlKey||Math.abs(t.deltaY)<=Math.abs(t.deltaX)||e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[]),(0,i.useEffect)(()=>{let e=c.current,t=e?.querySelector('[role="tab"][aria-selected="true"]');if(!e||!t)return;let n=e.getBoundingClientRect(),{left:r,right:i}=t.getBoundingClientRect();r<n.left?e.scrollLeft-=n.left-r:i>n.right&&(e.scrollLeft+=i-n.right)},[n,t.length]),(0,r.jsx)("div",{ref:c,role:"tablist",className:"tabbar-scroll",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",overflowX:"auto",overflowY:"hidden",flexShrink:0,height:36},children:t.map(e=>{let i=e.id===n;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===e.kind?o("terminal.tabLabel",{name:e.label}):"agent"===e.kind?o("subagent.tabLabel",{name:e.label}):e.label,"aria-selected":i,tabIndex:i||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),s(e.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(n.key)){n.preventDefault();let r=t.findIndex(t=>t.id===e.id),i="Home"===n.key?0:"End"===n.key?t.length-1:(r+("ArrowRight"===n.key?1:-1)+t.length)%t.length;s(t[i].id),n.currentTarget.parentElement?.children[i]?.focus()}}},onClick:()=>s(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||l(e.id))},style:{display:"flex",alignItems:"center",gap:6,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"terminal"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"agent"===e.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):t$(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:e.filePath,children:e.label}),(0,r.jsx)("button",{disabled:e.closing,onClick:t=>{t.stopPropagation(),l(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:a===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:a===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:o("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${o("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function d3(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s}let d5=["general","models","archives","skills","agents","plugins","mcp"],d6="pi-web:settings-navigation",d9=new Set(["skills","agents","plugins"]);function d7(e){return d9.has(e)}function ce(){try{return window.localStorage}catch{return null}}function ct(e){let t=e.getItem(d6);if(!t)return{};try{let e=JSON.parse(t);if(null===e||"object"!=typeof e||Array.isArray(e))return{};return{section:"string"==typeof e.section?e.section:void 0,selections:null===e.selections||"object"!=typeof e.selections||Array.isArray(e.selections)?void 0:e.selections}}catch{return{}}}function cn(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function cr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ce();if(t)try{let n=ct(t);n.section=e,t.setItem(d6,JSON.stringify(n))}catch{}}function ci(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ce();if(!n)return null;let r=cn(e,t);if(!r)return null;try{let e=ct(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function cs(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:ce();if(!r||!t)return;let i=cn(e,n);if(i)try{let e=ct(r);e.selections={...e.selections,[i]:t},r.setItem(d6,JSON.stringify(e))}catch{}}function cl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class co extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function ca(e){if("string"==typeof e){let t=/^\d+$/.test(e.trim())?Number(e.trim()):0;return Number.isSafeInteger(t)&&t>0?t:void 0}return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}let cd={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class cc extends Error{constructor(e,t){super(cd[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function cu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return!cu(e)||"string"!=typeof e.id||e.id.trim().length>0}function ch(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cf(e){let t=ch(e.inputLimits)?e.inputLimits.images:void 0,n=ch(t)?t.resize:void 0;return ch(n)?n.maxBytes:void 0}function cm(e){let t="string"==typeof e?/^\d+$/.test(e.trim())?Number(e.trim()):0:e;return"number"==typeof t&&Number.isSafeInteger(t)&&t>=1?t:void 0}function cg(e){let t=["B","KiB","MiB","GiB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=0===r?String(n):String(Math.round(10*n)/10);return`${i} ${t[r]}`}class cx extends Error{constructor(e){super(`Image size limit of ${e} must be a positive whole number of bytes`),this.name="ImageMaxBytesError",this.model=e}}let cv=["input","output","cacheRead","cacheWrite"];function cb(e){return{input:e?.input===void 0?"":String(e.input),output:e?.output===void 0?"":String(e.output),cacheRead:e?.cacheRead===void 0?"":String(e.cacheRead),cacheWrite:e?.cacheWrite===void 0?"":String(e.cacheWrite)}}function cy(e){if(!cw(e))return;let t=e=>{if(!e.trim())return 0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0},n=t(e.input),r=t(e.output),i=t(e.cacheRead),s=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==s)return{input:n,output:r,cacheRead:i,cacheWrite:s}}function cw(e){return cv.some(t=>""!==e[t].trim())}function cj(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function ck(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function cS(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function cC(e,t){let{renames:n,savedProviders:r}=e;for(let[e,r]of n)if(r===t)return e;return!n.has(t)&&r.has(t)?t:null}function cN(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function c$(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:l,children:o,width:a=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${a}px`,"--config-panel-height":d};return(0,r.jsx)("div",{role:t?void 0:"dialog","aria-modal":t?void 0:"true","aria-label":n,className:`config-panel-root ${t?"is-embedded":"is-modal"}`,onClick:e=>{t||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:c,children:[!t&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:n}),i&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:i,children:i}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:l,title:s,"aria-label":s,children:"\xd7"})]}),o]})})}function cE(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-split-view",children:t})}function cI(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function cM(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function cT(e){let{children:t,aside:n}=e;return(0,r.jsxs)("div",{className:"config-sidebar-group-label",children:[(0,r.jsx)("span",{className:"config-sidebar-group-label-text",children:t}),n]})}function cR(e){let{enabled:t,total:n,checked:i,label:s,disabled:l=!1,loading:o=!1,describedBy:a,onChange:d}=e;return(0,r.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,r.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,r.jsx)(c4,{checked:i??(n>0&&t===n),disabled:l,loading:o,label:s,describedBy:a,onChange:d})]})}function cA(e){let{error:t,note:n}=e;return t||n?(0,r.jsxs)("div",{className:"config-sidebar-group-status",children:[n&&(0,r.jsx)("div",{role:"status",className:"config-sidebar-group-note",children:n}),t&&(0,r.jsx)("div",{role:"alert",className:"config-sidebar-group-error",children:t})]}):null}function cL(e){let{active:t=!1,className:n,children:i,...s}=e;return(0,r.jsx)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function cz(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function cP(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function cW(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function cO(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function cF(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function cD(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function cB(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function cH(e){let{label:t,children:n,style:i,ref:s}=e;return(0,r.jsxs)("div",{ref:s,className:"config-field",style:i,children:[(0,r.jsx)("span",{className:"config-field-label",children:t}),n]})}function c_(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function cU(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:l,children:o}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,r.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,i?"is-mono":null,s].filter(Boolean).join(" "),style:l,children:o})]})}function cq(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function cK(e){let{value:t,options:n,label:s,disabledReason:l,size:o="default",onChange:a,children:d}=e,c=(0,i.useId)(),u=l&&n.some(e=>e.disabled)?l:null;return(0,r.jsxs)("div",{className:"config-scope-switch-field",children:[(0,r.jsxs)("div",{className:"config-scope-switch-row",children:[(0,r.jsx)("div",{role:"group","aria-label":s,className:`config-scope-switch${"small"===o?" is-small":""}`,children:n.map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&u?c:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||a(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function cV(e){let{value:t,options:n,label:s,path:l,disabledReason:o,onChange:a,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(cK,{value:t,options:n,label:s,disabledReason:o,size:"small",onChange:a,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof l?l.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):l})}),d]})}function cZ(e){let{title:t,catalogs:n,target:i}=e;return(0,r.jsxs)("div",{className:"config-add-source-heading",children:[(0,r.jsxs)("div",{className:"config-add-source-title-row",children:[(0,r.jsx)(cD,{children:t}),(0,r.jsx)("span",{className:"config-add-source-catalogs",children:n.map(e=>(0,r.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"config-add-source-catalog",children:[e.icon,e.label]},e.href))})]}),i]})}function cJ(e){let{title:t,catalogs:n,target:s,inputLabel:l,inputId:o,placeholder:a,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:f,examples:m,error:g,multiline:x=!1,children:v}=e,b=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():b.current?.focus()},[x]);let w=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(cP,{className:"is-fill",children:[(0,r.jsx)(cZ,{title:t,catalogs:n,target:s}),(0,r.jsx)(cH,{label:l,children:x?(0,r.jsx)("textarea",{id:o,ref:y,value:d,"aria-label":l,className:"config-add-source-input is-multiline",placeholder:a,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),c&&h())}}):(0,r.jsx)("input",{id:o,ref:b,value:d,"aria-label":l,className:"config-add-source-input",placeholder:a,onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&c&&h()}})}),v,m.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:f}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:m.map(e=>"string"==typeof e?(0,r.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,r.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,r.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,r.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),g&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:g})]})}function cY(e){let{id:t,action:n,children:i}=e;return(0,r.jsxs)("div",{id:t,role:"status",className:`config-notice${n?" has-action":""}`,children:[n?(0,r.jsx)("span",{className:"config-notice-text",children:i}):i,n]})}function cG(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:l}=e;return(0,r.jsx)(cY,{id:t,action:l&&i?(0,r.jsx)(c2,{size:"small",onClick:l,disabled:s,children:i}):void 0,children:n})}function cX(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function cQ(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function c0(e){let{status:t,children:n}=e;return(0,r.jsxs)("footer",{className:"config-footer",children:[(0,r.jsx)("div",{className:"config-footer-status",children:t}),(0,r.jsx)("div",{className:"config-footer-actions",children:n})]})}function c1(e){let{summary:t,tone:n="default",details:i}=e,s=`config-footer-status-summary${"default"===n?"":` is-${n}`}`;return i?.length?(0,r.jsxs)("details",{className:"config-footer-status-details",children:[(0,r.jsx)("summary",{className:s,children:t}),(0,r.jsx)("ul",{className:"config-footer-status-list",children:i.map((e,t)=>(0,r.jsx)("li",{children:e},t))})]}):(0,r.jsx)("span",{className:s,children:t})}function c2(e){let{variant:t="secondary",size:n="default",className:i,children:s,...l}=e;return(0,r.jsx)("button",{type:"button",...l,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function c4(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:l,describedBy:o,onChange:a}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":l,"aria-describedby":o,title:l,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>a(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function c8(e){let{active:t=!1,children:n,className:i,...s}=e;return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...s,"aria-current":t?"page":void 0,className:["config-list-action-button",i].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function c3(e){let{active:t,color:n}=e;return(0,r.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${t?" is-active":!1===t?" is-inactive":""}`,style:n?{backgroundColor:n}:void 0})}function c5(e,t){let n=t.filter(e=>!e.enabled).map(e=>e.ref),r=t.filter(e=>e.enabled).map(e=>e.ref),i=e?.editable===!0;return{enableRefs:n,disableRefs:r,canEnable:i&&n.length>0,canDisable:i&&r.length>0&&(e?.enabledTotal??0)-r.length>=1}}function c6(e,t){let n=c5(e,t.models),r=t.models.length>0&&t.enabledCount===t.models.length,i=r?!n.canDisable:!n.canEnable;return{checked:r,blocked:i,reason:i?e?.editable?"last-model":"project-scope":null}}function c9(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function c7(e,t){return e?.providers.find(e=>e.id===t)}function ue(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:l=!1,describedBy:o}=e,{t:a}=(0,e0.s)(),d=void 0!==i&&void 0===ca(i);return(0,r.jsx)("input",{type:"text",inputMode:"numeric",className:"model-context-input",value:void 0===i?"":String(i),placeholder:void 0===n?void 0:String(n),title:a("models.contextWindow"),"aria-label":a("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":o,disabled:l,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let ut={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function un(e){let{controller:t}=e,{t:n}=(0,e0.s)(),{view:i,pending:s}=t;if(!i)return null;let l=!i.allEnabled,o=i.stalePatterns.length;return l||0!==o?(0,r.jsxs)("div",{className:"enabled-models-banner",children:[(0,r.jsxs)("span",{className:"enabled-models-banner-text",...o>0?{title:n("models.enabledStaleHint")}:{},children:[(0,r.jsx)("code",{className:"enabled-models-banner-key",title:i.settingsPath,children:i.settingsPath}),(0,r.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${i.enabledTotal}/${i.availableTotal}`,o>0&&` \xb7 ${n("models.enabledStale",{count:o})}`]})]}),i.editable&&o>0&&(0,r.jsx)(c2,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&l&&(0,r.jsx)(c2,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function ur(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,e0.s)(),{view:l,loading:o,pending:a,failure:d}=n,c=c7(l,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=ui(n,t)?i:void 0;if(o&&!l)return null;if(!c)return(0,r.jsx)(c4,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=c6(l,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(c4,{checked:h.checked,loading:a===`provider:${c.id}`,disabled:null!==a||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function ui(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=c7(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=c6(n,i);return s?ut[s]:null}function us(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,e0.s)(),l=ui(n,t);return l?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(l)}):null}function ul(e){var t;let n,{providerId:s,controller:l,contextSettings:o}=e,{t:a}=(0,e0.s)(),[d,c]=(0,i.useState)(""),{view:u,loading:p,pending:h,failure:f}=l,m=c7(u,s),g=function(e,t){let[n,r]=(0,i.useState)(!1),[s,l]=(0,i.useState)(null);return(0,i.useEffect)(()=>l(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),l(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);"offline"===r.reason?l("models.catalogOffline"):r.completed?l(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):l("models.catalogUnreachable"),r.changed&&t()}catch{l("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,l.refresh),x=(0,i.useId)();if((0,i.useEffect)(()=>c(""),[s]),p&&!u)return(0,r.jsx)("div",{className:"enabled-models-empty",children:a("agents.modelsLoading")});if(!m)return f?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:f.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledUnavailable")});let v=(t=m.models,(n=d.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),b=c5(u,v),y=v.length!==m.models.length,w=null!==h,j=`provider:${m.id}`,k=u?.editable===!0,S=`${x}-scope`,C=`${x}-last`,N=`${x}-context`,$=k&&!b.canDisable&&b.disableRefs.length>0,E=$||k&&v.some(e=>c9(u,e)),I=(e,t)=>{y?l.setModels(j,t,e):l.setProvider(m.id,e)};return(0,r.jsxs)("div",{className:"enabled-models-section",children:[(0,r.jsxs)("div",{className:"enabled-models-header",children:[(0,r.jsx)("span",{className:"enabled-models-title",children:a("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:a("models.enabledCount",{enabled:m.enabledCount,total:m.models.length})}),(0,r.jsx)(c2,{size:"small",disabled:w||!b.canEnable,"aria-describedby":k?void 0:S,onClick:()=>I(!0,b.enableRefs),children:y?a("models.enableShown"):a("models.enableAll")}),(0,r.jsx)(c2,{size:"small",disabled:w||!b.canDisable,"aria-describedby":k?$?C:void 0:S,onClick:()=>I(!1,b.disableRefs),children:y?a("models.disableShown"):a("models.disableAll")}),(0,r.jsx)(c2,{size:"small",disabled:w||g.refreshing,title:a("models.refreshCatalogHint"),onClick:g.refresh,children:g.refreshing?a("models.refreshingCatalog"):a("models.refreshCatalog")})]}),g.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:a(g.note)}),!k&&(0,r.jsx)("div",{id:S,className:"enabled-models-note",children:a("models.enabledProjectScope")}),E&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:a("models.enabledLastModel")}),f&&(0,r.jsx)("div",{className:"enabled-models-error",children:f.messageKey?a(f.messageKey):f.message}),m.models.length>8&&(0,r.jsx)("input",{value:d,onChange:e=>c(e.target.value),placeholder:a("models.enabledFilterPlaceholder",{count:m.models.length}),"aria-label":a("models.enabledFilter"),className:"enabled-models-filter"}),o&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:a("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledNoMatches")}):v.map(e=>{let t=c9(u,e),n=o?.overrides?.[e.id],i=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,r.jsxs)("div",{className:"enabled-models-row",children:[(0,r.jsxs)("span",{className:"enabled-models-row-text",children:[(0,r.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,r.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,r.jsx)("span",{className:"enabled-models-pin",title:a("models.enabledPinHint"),children:e.thinkingPin}),o&&(0,r.jsx)(ue,{modelName:e.name,effective:e.contextWindow,value:i,disabled:o.disabled,describedBy:N,onChange:t=>o.onChange(e.id,t)}),(0,r.jsx)(c4,{checked:e.enabled,loading:h===e.ref,disabled:w||!u?.editable||t,label:a("models.enabledToggle",{model:e.name}),describedBy:k?t?C:void 0:S,onChange:t=>l.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function uo(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:l,inputLabel:o,disabled:a=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!a&&i.trim().length>0;return(0,r.jsxs)("div",{className:"oauth-paste-panel",children:[(0,r.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,r.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,r.jsxs)("div",{className:"oauth-paste-row",children:[(0,r.jsx)("input",{ref:c,value:i,className:"oauth-paste-input",placeholder:s,"aria-label":o,disabled:a||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(d||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,r.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:l})]})]})}let ua={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},azure:{symbol:"azure",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function ud(e){let{id:t,size:n}=e,i=ua[t];if(i)return(0,r.jsx)("svg",{"aria-hidden":"true",width:n,height:n,viewBox:"0 0 24 24",fill:i.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${i.symbol}`})});let s=t.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:n,height:n,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*n)),fontWeight:700,lineHeight:1},children:s})}let uc=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],uu="pi-web:provider-usage:";function up(e){let{providerId:t,enabled:n}=e;return uc.includes(t)?(0,r.jsx)(uh,{providerId:t,enabled:n}):null}function uh(e){let{providerId:t,enabled:n}=e,[s,l]=(0,i.useState)(null),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:f,t:m}=(0,e0.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),l(null);try{let e=localStorage.getItem(`${uu}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&l(t)}}catch{try{localStorage.removeItem(`${uu}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,i.useCallback)(async()=>{a(!0),c(null);try{let e=await fetch("/api/provider-usage/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:t})}),n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);if("ready"===n.status){l(n);try{localStorage.setItem(`${uu}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??m("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:m("providerUsage.queryFailed"))}finally{a(!1)}},[t,m]),x=s?.status==="ready"?s.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:m("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:g,disabled:!n||o,title:m(o?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":m(o?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:u?"#4ade80":"var(--text-dim)",cursor:n&&!o?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:u?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:o?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,r.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(f),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:m("providerUsage.updated",{time:(0,t8.ob)(x.capturedAt,f)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:m("providerUsage.notQueried")}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:d}),x&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr)",columnGap:14,rowGap:8,alignItems:"baseline",minWidth:0,width:"min(100%, 420px)",maxWidth:"100%",fontSize:12},children:[x.buckets.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.groupLabel?`${e.groupLabel} / ${e.label}`:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:function(e,t){if("percent"===e.unit&&void 0!==e.remaining){let t=e.resetsAt?` / ${new Date(1e3*e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"";return`${Math.round(e.remaining)}%${t}`}return"currency"===e.unit?`${"CNY"===e.currency?"CNY ":"$"}${uf(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${uf(e.remaining)} / ${uf(e.limit)}`:e.period??t}(e,m("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function uf(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function um(){let e=ci("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}function ug(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let ux=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],uv={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function ub(e){let{label:t,children:n}=e;return(0,r.jsx)(cH,{label:t,children:n})}let uy={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function uw(e){let{value:t,onChange:n,placeholder:i,mono:s}=e;return(0,r.jsx)("input",{value:t,onChange:e=>n(e.target.value),placeholder:i,style:{...uy,fontFamily:s?"var(--font-mono)":"inherit"}})}function uj(e){let{value:t,onChange:n,placeholder:s,mono:l,onKeyDown:o,autoComplete:a="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,e0.s)();return(0,i.useEffect)(()=>{t||p(!1)},[t]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:u?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:o,placeholder:s,style:{...uy,paddingRight:34,fontFamily:l?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:d}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":h(u?"i18n.hideDetails":"i18n.showDetails"),title:h(u?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function uk(e){let{value:t,onChange:n,placeholder:i,invalid:s}=e;return(0,r.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:i,"aria-invalid":s||void 0,style:s?{...uy,borderColor:"#ef4444"}:uy})}function uS(e){let{value:t,onChange:n,options:i,required:s}=e,{t:l}=(0,e0.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...uy,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",l("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function uC(e){let{label:t,checked:n,onChange:i}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:n,onChange:e=>i(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),t]})}function uN(e){let{children:t}=e;return(0,r.jsx)(cB,{children:t})}function u$(e){let{name:t,editingName:n,provider:s,onChange:l,onEditingNameChange:o,onRename:a,onDelete:d,onAddModels:c,enabledModels:u}=e,{t:p}=(0,e0.s)(),[h,f]=(0,i.useState)({phase:"idle"}),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useId)(),j=(e,t)=>l({...s,[e]:t});(0,i.useEffect)(()=>{b.current+=1,f({phase:"idle"}),g(""),v([])},[t,s.baseUrl,s.api,s.apiKey]);let k=(0,i.useCallback)(async()=>{if("loading"===h.phase)return;let e=++b.current;f({phase:"loading"}),v([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...s,models:void 0}})}),r=await n.json();if(e!==b.current)return;if(!n.ok||r.error||!r.models)return void f({phase:"error",message:r.error??`HTTP ${n.status}`});f({phase:"success",models:r.models,endpoint:r.endpoint??s.baseUrl??""})}catch(t){if(e!==b.current)return;f({phase:"error",message:t instanceof Error?t.message:String(t)})}},[h.phase,t,s]),S=new Set((s.models??[]).map(e=>e.id)),C="success"===h.phase?h.models:[],N=m.trim().toLocaleLowerCase(),$=C.filter(e=>!N||e.id.toLocaleLowerCase().includes(N)||e.name?.toLocaleLowerCase().includes(N)),E=$.slice(0,300),I=E.filter(e=>!S.has(e.id)).map(e=>e.id),M=x.filter(e=>!S.has(e)).length,T=I.length>0&&I.every(e=>x.includes(e)),R=!T&&I.some(e=>x.includes(e));return(0,i.useEffect)(()=>{y.current&&(y.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:p("i18n.provider")})}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(ur,{providerId:t,controller:u,noteId:w}),(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:d,children:p("i18n.delete")})]})]}),(0,r.jsx)(us,{providerId:t,controller:u,id:w})]}),(0,r.jsxs)(ub,{label:p("i18n.providerName"),children:[(0,r.jsx)(uw,{value:n,onChange:o,placeholder:"provider-name",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>a(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:p("i18n.rename")})]}),(0,r.jsx)(ub,{label:"Base URL",children:(0,r.jsx)(uw,{value:s.baseUrl??"",onChange:e=>j("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(ub,{label:"API Key",children:(0,r.jsx)(uj,{value:s.apiKey??"",onChange:e=>j("apiKey",e||void 0),placeholder:p("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(ub,{label:"API",children:(0,r.jsx)(uS,{value:s.api??"",onChange:e=>j("api",e||void 0),options:ux})}),(0,r.jsx)(ub,{label:"Headers",children:(0,r.jsx)(uL,{headers:s.headers,onChange:e=>j("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==h.phase&&(0,r.jsx)("button",{onClick:k,disabled:"loading"===h.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===h.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===h.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===h.phase?p("models.discoveryFetching"):p("models.discoveryFetch")}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:m,onChange:e=>g(e.target.value),placeholder:p("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":p("models.discoveryFilter"),style:{...uy,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:y,type:"checkbox",checked:T,disabled:0===I.length,onChange:()=>{let e=new Set(I);v(t=>T?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),p("models.discoverySelectShown")]}),0===E.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:p("models.discoveryNoMatches")}):E.map((e,t)=>{let n=S.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void v(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:p("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:$.length>E.length?p("models.discoveryShowing",{shown:E.length,total:$.length}):p("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!S.has(t.id));0!==t.length&&(c(t),v([]))},disabled:0===M,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:M?"var(--accent)":"var(--bg-panel)",color:M?"var(--accent-contrast)":"var(--text-dim)",cursor:M?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:M?p("models.discoveryAddSelectedCount",{count:M}):p("models.discoveryAddSelected")})]})]})]})]})}let uE=["off","minimal","low","medium","high","xhigh","max"],uI={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function uM(e){let{value:t,onChange:n}=e,{t:i}=(0,e0.s)(),s=t??{},l=(e,t)=>{let r={...s};"omit"===t?delete r[e]:r[e]=t,n(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:uE.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",o="string"==typeof t?t:"",a=uI[e],d={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:a,flexShrink:0,opacity:"null"===n?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===n?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===n?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>l(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>l(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:i("i18n.disabled")})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===n?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>l(e,o||e),style:{...d,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:i("i18n.custom")}),(0,r.jsx)("input",{value:o,onChange:t=>l(e,t.target.value),onFocus:()=>{"string"!==n&&l(e,o||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===n?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===n?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let uT={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function uR(e){return e.compat?.thinkingFormat==="deepseek"}function uA(e,t){return{...e.compat??{},...t.compat??{}}}function uL(e){let{headers:t,onChange:n}=e,{t:s}=(0,e0.s)(),[l,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),a=(0,i.useRef)(l.length),d=e=>{o(e),n(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},c=(e,t)=>{d(l.map(n=>n.id===e?{...n,...t}:n))},u={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[l.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>c(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...uy,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>c(e.id,{value:t.target.value}),placeholder:"value",style:{...uy,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void d(l.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>o(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:["+ ",s("models.addHeader")]})]})}function uz(e){let{providerName:t,provider:n,model:s,onChange:l,onDelete:o}=e,[a,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,e0.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(()=>cb(s.cost)),x=(0,i.useRef)(m),[v,b]=(0,i.useState)(!1),y=(0,i.useRef)(0),w=s.baseUrl??n.baseUrl,j=(0,i.useRef)(0),k=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>l({...s,[e]:t}),N=(()=>{if("idle"===a.phase)return null;if("testing"===a.phase)return c("i18n.testingModel");let e=[void 0!==a.latencyMs?`${a.latencyMs}ms`:null,void 0!==a.status?`HTTP ${a.status}`:null].filter(Boolean);return"success"===a.phase?[c("i18n.connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,a.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>(y.current+=1,d({phase:"idle"}),()=>{y.current+=1}),[t,n,s]),(0,i.useEffect)(()=>{j.current+=1,p({phase:"idle"}),k.current=null},[t,w,s.id]);let $=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===a.phase)return;let e=++y.current;d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:s})}),i=await r.json();if(e!==y.current)return;if(!r.ok||!i.ok)return void d({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});d({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(t){if(e!==y.current)return;d({phase:"error",message:t instanceof Error?t.message:String(t)})}},[s,n,t,a.phase]),E=(0,i.useCallback)(async()=>{let e=s.id.trim();if(!e||"loading"===u.phase)return;let n=++j.current;p({phase:"loading"});try{let r=new URLSearchParams({q:e,provider:t,limit:"50"});w?.trim()&&r.set("baseUrl",w.trim());let i=await fetch(`/api/models-config/catalog?${r}`),o=await i.json();if(n!==j.current)return;if(!i.ok||o.error||!o.recommendation)return void p({phase:"error",message:o.error??`HTTP ${i.status}`});let a=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let l=cy(cb(i));s>0&&l&&(n.cost={...i,...l},r+=s)}return{model:n,appliedCount:r}}(s,o.recommendation.preset);a.appliedCount>0&&(k.current=s,l(a.model)),f(!1),p({phase:"success",recommendation:o.recommendation,appliedCount:a.appliedCount})}catch(e){if(n!==j.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,l,w,t]),I=(()=>{if("success"!==u.phase)return null;let{recommendation:e,appliedCount:n}=u,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?c("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?c("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):c("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),M="error"===u.phase?u.message:I,T="error"===u.phase?"#ef4444":"success"===u.phase&&"unreliable"===u.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:c("models.costInput")},{key:"output",label:c("models.costOutput")},{key:"cacheRead",label:c("models.costCacheRead")},{key:"cacheWrite",label:c("models.costCacheWrite")}],A=new Set(Object.keys(s.compat??{})),L=0;uR(s)&&(L+=1,A.delete("thinkingFormat"),A.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(s.compat??{},"supportsDeveloperRole")&&(L+=1,A.delete("supportsDeveloperRole")),L+=A.size;let z=cf(s),P=cm(z),W=[s.baseUrl?c("models.baseUrlOverride"):null,s.api?`API: ${s.api}`:null,Object.keys(s.headers??{}).length?c("models.headersSummary",{count:Object.keys(s.headers??{}).length}):null,L?c("models.compatSummary",{count:L}):null,Object.keys(s.thinkingLevelMap??{}).length?c("models.thinkingSummary",{count:Object.keys(s.thinkingLevelMap??{}).length}):null,void 0!==P?c("models.imageMaxBytesSummary",{size:cg(P)}):null].filter(e=>!!e),O=W.length?W.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:c("i18n.model")})}),(0,r.jsxs)(cF,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===a.phase?"#fecaca":"success"===a.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===a.phase?"#fee2e2":"success"===a.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:N}),(0,r.jsxs)(c2,{size:"small",variant:"success"===a.phase?"primary":"secondary",onClick:"success"===a.phase?()=>d({phase:"idle"}):$,disabled:!s.id.trim()||"testing"===a.phase,title:c("i18n.testConnection"),className:"success"===a.phase?"is-success":void 0,children:["success"===a.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===a.phase?c("i18n.checking"):"success"===a.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:o,children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(ub,{label:"ID *",children:(0,r.jsx)(uw,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(ub,{label:"Name",children:(0,r.jsx)(uw,{value:s.name??"",onChange:e=>C("name",e||void 0),placeholder:c("models.displayNamePlaceholder")})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void E(),disabled:!s.id.trim()||"loading"===u.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:s.id.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:s.id.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),M&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:T,fontSize:10},children:[(0,r.jsx)("span",{title:M,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),k.current&&(0,r.jsx)("button",{onClick:()=>{let e=k.current;e&&(k.current=null,l(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(uN,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(uC,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(uC,{label:c("models.imageInput"),checked:s.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(uN,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void f(!1);S.current=s.cost;let e=cb(s.cost);x.current=e,g(e),f(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?c("models.finishEditingCosts"):c("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(ub,{label:c("models.contextWindow"),children:(0,r.jsx)(uk,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(ub,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(uk,{value:void 0!==s.maxTokens?String(s.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:c("models.costPerMillion")}),h?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[R.map(e=>{let{key:t,label:n}=e;return(0,r.jsx)(ub,{label:n,children:(0,r.jsx)(uk,{value:m[t],onChange:e=>{let n,r,i;return r=cy(n={...x.current,[t]:e}),i={...s},void(x.current=n,g(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,l(i))},placeholder:"0"})},t)}),cw(m)&&!cy(m)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:c("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:R.map(e=>{let t,{key:n,label:i}=e,l=s.cost?.[n]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),(0,r.jsx)("div",{style:{marginTop:3,color:l?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=s.cost?.[n])?c("models.notProvided"):`$${String(t)}`})]},n)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>b(e=>!e),"aria-expanded":v,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:c("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(ub,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(uw,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(ub,{label:c("models.apiOverride"),children:(0,r.jsx)(uS,{value:s.api??"",onChange:e=>C("api",e||void 0),options:ux})}),(0,r.jsxs)(ub,{label:c("models.headers"),children:[(0,r.jsx)(uL,{headers:s.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("models.headersHelp")})]}),(s.input?.includes("image")||void 0!==z)&&(0,r.jsxs)(ub,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(uk,{value:void 0===z?"":String(z),onChange:e=>{var t;let n,r,i,o;return l((t=e.trim()||void 0,n={...ch(s.inputLimits)?s.inputLimits:{}},r={...ch(n.images)?n.images:{}},i={...ch(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=cm(t)??t,Object.keys(i).length?r.resize=i:delete r.resize,Object.keys(r).length?n.images=r:delete n.images,o={...s},Object.keys(n).length?o.inputLimits=n:delete o.inputLimits,o))},placeholder:String(4718592),invalid:void 0===P&&void 0!==z}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==P&&`${cg(P)} \xb7 `,c("models.imageMaxBytesHelp",{size:cg(4718592)})]}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"inputLimits.images.resize.maxBytes"})]}),s.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(uN,{children:c("models.compatibility")}),(0,r.jsx)(uC,{label:c("models.deepSeekThinkingCompat"),checked:uR(s),onChange:e=>l(function(e,t){if(t)return{...e,compat:{...e.compat??{},...uT}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(s,e))}),(0,r.jsx)(uC,{label:c("models.developerRole"),checked:!1!==uA(n,s).supportsDeveloperRole,onChange:e=>l(cj(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(uC,{label:c("models.adaptiveThinking"),checked:!0===uA(n,s).forceAdaptiveThinking,onChange:e=>l(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return cj(e,t,n);if(!e.compat||!Object.prototype.hasOwnProperty.call(e.compat,t))return e;let i={...e.compat};return delete i[t],{...e,compat:Object.keys(i).length?i:void 0}}(s,"forceAdaptiveThinking",e,n.compat?.forceAdaptiveThinking===!0))}),(0,r.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",paddingLeft:19},children:"compat.forceAdaptiveThinking"})]}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(uN,{children:c("models.thinkingLevelMap")}),s.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:c("models.clearAll")})]}),(0,r.jsx)(uM,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function uP(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:l}=e,[o,a]=(0,i.useState)({phase:"idle"}),{t:d}=(0,e0.s)(),[c,u]=(0,i.useState)(""),p=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===o.phase||"prompt"===o.phase)&&setTimeout(()=>h.current?.focus(),50)},[o.phase]),(0,i.useEffect)(()=>{a({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let f=(0,i.useCallback)(()=>{p.current?.close(),a({phase:"connecting"}),u("");let e=new EventSource(`/api/auth/login/${encodeURIComponent(t.id)}`);p.current=e,e.onmessage=t=>{let r=JSON.parse(t.data);"auth"===r.type?(a({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(a({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?a({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?a({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?a({phase:"progress",message:r.message}):"success"===r.type?(e.close(),a({phase:"success"}),n()):"error"===r.type?(e.close(),a({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),a({phase:"idle"}))},e.onerror=()=>{e.close(),a(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[t.id,n]),m=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),a({phase:"idle"}),n()},[t.id,n]),g=(0,i.useCallback)(async(e,n)=>{if(n.trim()){a({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??`Server error ${r.status}`});return}u("")}catch(e){a({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[t.id]),x=(0,i.useCallback)(async(e,n)=>{a({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));a({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){a({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[t.id]),v="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===o.phase?0:16},children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:d("i18n.subscription")})}),(0,r.jsxs)(cF,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.loggedIn?"#4ade80":"var(--text-dim)"},children:d(t.loggedIn?"i18n.connected":"i18n.notConnected")})]}),v?(0,r.jsx)(c2,{size:"small",onClick:()=>{p.current?.close(),a({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(c2,{variant:"primary",size:"small",onClick:f,children:d(t.loggedIn?"i18n.relogin":"i18n.login")}),t.loggedIn&&(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:m,children:d("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===o.phase?0:48},children:["idle"===o.phase&&!t.loggedIn&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthConnect",{provider:t.name})}),"connecting"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:d("i18n.openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:o.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:o.options.map(e=>(0,r.jsx)("button",{onClick:()=>x(o.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsx)(uo,{message:"auth"===o.phase?d("models.oauthPasteRedirect"):o.message,hint:"auth"===o.phase?(0,r.jsxs)(r.Fragment,{children:[d("models.oauthNoBrowser")," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",children:d("models.oauthOpenLoginPage")}),d("models.oauthOpenLoginPageEnd")]}):void 0,value:c,placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??d("models.oauthValuePlaceholder"),submitLabel:d("i18n.submit"),inputRef:h,onValueChange:u,onSubmit:()=>void g(o.token,c)}),"device_code"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:d("models.oauthDeviceCode")}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:o.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:o.verificationUri}),o.expiresInSeconds?` Expires in ${Math.ceil(o.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o.message}),"success"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:d("i18n.connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:o.message})]}),(0,r.jsx)(up,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(ul,{providerId:t.id,controller:s,contextSettings:l})]})}function uW(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:l}=e,[o,a]=(0,i.useState)(""),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),{t:x}=(0,e0.s)();(0,i.useEffect)(()=>{a(""),f(null),g(!1)},[t.id]);let v=(0,i.useCallback)(async()=>{if(o.trim()){c(!0),f(null),g(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o.trim()})}),r=await e.json();!e.ok||r.error?f(r.error??`HTTP ${e.status}`):(a(""),g(!0),setTimeout(()=>g(!1),2e3),n())}catch(e){f(String(e))}finally{c(!1)}}},[o,t.id,n]),b=(0,i.useCallback)(async()=>{p(!0),f(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?f(r.error??`HTTP ${e.status}`):n()}catch(e){f(String(e))}finally{p(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(uN,{children:"API Key"})}),(0,r.jsxs)(cF,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:x(t.configured?"i18n.configured":"i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:b,disabled:u,children:x(u?"i18n.removing":"i18n.disconnect")})]})]}),!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?x("models.apiKeyEnableOne",{provider:t.displayName}):x("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(uj,{value:o,onChange:a,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&v()},placeholder:t.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:v,disabled:d||!o.trim()||m,style:{padding:"6px 12px",background:m?"#16a34a":o.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:m?"#fff":o.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:d||!o.trim()||m?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[m&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),x(m?"i18n.saved":d?"i18n.saving":"i18n.save")]})]}),h&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:h}),(0,r.jsx)(up,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(ul,{providerId:t.id,controller:s,contextSettings:l})]})}function uO(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:l,onAddCustom:o,onClose:a}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,e0.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),f=t.filter(e=>!e.loggedIn&&cN(h,e.id,e.name)),m=n.filter(e=>!e.configured&&cN(h,e.id,e.displayName)),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=f.length+m.length+ +!!g,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),a())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:p,value:d,onChange:e=>c(e.target.value),placeholder:u("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{o(),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),f.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(ud,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(f.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{l(e.id),a()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:1===e.modelCount?u("models.modelCountOne"):u("models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(ud,{id:e.id,size:28})]},e.id))]})})]})})}function uF(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:l}=(0,e0.s)(),o=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[l,o]=(0,i.useState)(null),[a,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,f]=(0,i.useState)(0);(0,i.useEffect)(()=>{let t=new AbortController;s(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);n(t),d(null)}).catch(e=>{t.signal.aborted||d({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||s(!1)}),()=>t.abort()},[e,h]);let m=(0,i.useCallback)((t,r)=>{if(c.current){u.current={key:t,body:r};return}c.current=t,o(t),d(null),(async()=>{try{let t=await fetch("/api/models/enabled",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...e?{cwd:e}:{}})}),i=await t.json();if(!t.ok||i.error){let e=i.reason?ut[i.reason]:void 0;d(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){d({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,o(null);let e=u.current;u.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=m;let g=(0,i.useCallback)((e,t,n)=>{m(e,{op:"models",refs:t,enabled:n})},[m]),x=(0,i.useCallback)((e,t)=>{m(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[m]),v=(0,i.useCallback)(()=>m("clear",{op:"clear"}),[m]),b=(0,i.useCallback)(()=>m("prune",{op:"prune"}),[m]),y=(0,i.useCallback)(()=>f(e=>e+1),[]),w=(0,i.useCallback)((e,n)=>{m("resync",{op:"resync",renames:e,modelRenames:n,fullyEnabled:(t?.providers??[]).filter(e=>e.models.length>0&&e.enabledCount===e.models.length).map(e=>e.id)})},[m,t]);return{view:t,loading:r,pending:l,failure:a,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:w}}(s),[a,d]=(0,i.useState)({providers:{}}),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(um),[j,k]=(0,i.useState)([]),[S,C]=(0,i.useState)([]),[N,$]=(0,i.useState)(!1),[E,I]=(0,i.useState)(!1),M=(0,i.useRef)(new Set),T=(0,i.useRef)(new Map),R=(0,i.useRef)(new Map),[A,L]=(0,i.useState)(null),z=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&k(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&C(e.apiKeyProviders)}).catch(()=>{}).finally(()=>$(!0))},[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{let t=e.providers?e:{...e,providers:{}};d(t),M.current=new Set(Object.keys(t.providers??{})),R.current=ck(t);let n=Object.keys(t.providers??{});w(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(e=>x(e instanceof Error?e.message:String(e))).finally(()=>u(!1)),z()},[z]),(0,i.useEffect)(()=>{y&&cs("models",JSON.stringify(y))},[y]),(0,i.useEffect)(()=>{if(y?.type!=="provider")return;let e=a.providers?.[y.name];e&&ug(e)&&(j.some(e=>e.id===y.name)?w({type:"oauth",providerId:y.name}):S.some(e=>e.id===y.name)&&w({type:"apikey",providerId:y.name}))},[S,a.providers,j,y]);let P=e=>({overrides:a.providers?.[e]?.modelOverrides,disabled:c||p||null!==g,onChange:(t,n)=>{try{d(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},l={...s.modelOverrides},o=Object.hasOwn(l,n)?l[n]:void 0;if(void 0!==o&&!cl(o))throw Error("Model override must be an object");let a={...o};return void 0===r?delete a.contextWindow:a.contextWindow=r,Object.keys(a).length?Object.defineProperty(l,n,{value:a,enumerable:!0,configurable:!0}):delete l[n],Object.keys(l).length?s.modelOverrides=l:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(a,e,t,n)),b(!1),m(null)}catch(e){m(String(e))}}}),W=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;a.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),w({type:"provider",name:e})},[a.providers]),O=(0,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),F=(0,i.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:l}=t,o=cC(t,n);o===r?s.delete(o):null!==o&&s.set(o,r);let a=l.get(n);a&&(l.delete(n),l.set(r,a));let d=Object.entries(i),c=d.findIndex(e=>{let[t]=e;return t===n});return d[c]=[r,d[c][1]],{...e,providers:Object.fromEntries(d)}}(e,{savedProviders:M.current,renames:T.current,slots:R.current},t,n);return r?(d(r),L(null),w(e=>e?"provider"===e.type&&e.name===t?{type:"provider",name:n}:"model"===e.type&&e.providerName===t?{...e,providerName:n}:e:e),r):null},[]),D=(0,i.useCallback)((e,t)=>{F(a,e,t)?m(null):m(l("models.providerNameTaken",{name:t}))},[F,a,l]),B=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=cC(t={savedProviders:M.current,renames:T.current,slots:R.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...a.providers??{}},delete r[e],{...a,providers:r}),s=Object.keys(i.providers??{});L(t=>t?.provider===e?null:t),d(i),w(s.length>0?{type:"provider",name:s[0]}:null)},[a]),H=(0,i.useCallback)(e=>{cS(R.current,e,1),d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return w({type:"model",providerName:e,index:n}),t})},[]),_=(0,i.useCallback)((e,t)=>{d(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));cS(R.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],l=new Set(s.map(e=>e.id));for(let e of t)l.has(e.id)||(l.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),U=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),q=(0,i.useCallback)((e,t)=>{R.current.get(e)?.splice(t,1),d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),w({type:"provider",name:e})},[]),K=(0,i.useCallback)(async()=>{if(g)return;h(!0),m(null),b(!1);let e=a,t=A?.name.trim();if(A&&t&&a.providers?.[A.provider]){let n=F(a,A.provider,t);if(!n){m(l("models.providerNameTaken",{name:t})),h(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!cl(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(cl(n)&&cl(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!cl(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=ca(r.contextWindow);if(void 0===n)throw new co(`${e}/${t}`);r.contextWindow=n}return t}(e);if(cu(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!cu(t))continue;if(t.oauth&&!t.baseUrl)throw new cc(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(cp),r=cu(t.modelOverrides)&&Object.keys(t.modelOverrides).length>0;if(!n&&!t.baseUrl&&!t.headers&&!t.compat&&!r&&!t.apiKey&&!t.oauth&&void 0===t.authHeader)throw new cc(e,"empty")}var r=e;if(ch(r.providers)){for(let[e,t]of Object.entries(r.providers))if(ch(t)&&Array.isArray(t.models))for(let n of t.models){if(!ch(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=cf(n);if(void 0!==t&&void 0===cm(t))throw new cx(`${e}/${"string"==typeof n.id?n.id:"?"}`)}}let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),i=await t.json();if(!t.ok||i.error)m(i.error??`HTTP ${t.status}`);else{b(!0),setTimeout(()=>b(!1),2e3);let t=[...T.current].map(e=>{let[t,n]=e;return{from:t,to:n}}),n=function(e,t,n){let r=e=>{for(let[t,r]of n)if(r===e)return t;return e},i=[];for(let[n,s]of Object.entries(e.providers??{})){let e=t.get(n);e&&(s.models??[]).forEach((t,s)=>{let l=e[s];l&&t.id&&l!==t.id&&i.push({from:`${r(n)}/${l}`,to:`${n}/${t.id}`})})}return i}(e,R.current,T.current);M.current=new Set(Object.keys(e.providers??{})),R.current=ck(e),T.current.clear(),o.resync(t,n)}}catch(e){e instanceof cc?(m(l(uv[e.problem],{provider:e.provider})),w({type:"provider",name:e.provider})):e instanceof co?m(l("models.contextInvalid",{model:e.model})):m(e instanceof cx?l("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{h(!1)}},[F,a,o,g,A,l]),V=Object.entries(a.providers??{}).filter(e=>{let[t,n]=e;if(!ug(n))return!0;let r=j.some(e=>e.id===t)||S.some(e=>e.id===t);return N&&!r}),Z=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=c7(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(o.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},J=j.filter(e=>e.loggedIn),Y=S.filter(e=>e.configured),G=(()=>{if(!y)return null;if("oauth"===y.type){let e=j.find(e=>e.id===y.providerId);return e?(0,r.jsx)(uP,{provider:e,onRefresh:z,enabledModels:o,contextSettings:P(e.id)},e.id):null}if("apikey"===y.type){let e=S.find(e=>e.id===y.providerId);return e?(0,r.jsx)(uW,{provider:e,onRefresh:z,enabledModels:o,contextSettings:P(e.id)},e.id):null}if("provider"===y.type){let e=a.providers?.[y.name];return e&&V.some(e=>{let[t]=e;return t===y.name})?(0,r.jsx)(u$,{name:y.name,editingName:A?.provider===y.name?A.name:y.name,provider:e,onChange:e=>O(y.name,e),onEditingNameChange:e=>L(e===y.name?null:{provider:y.name,name:e}),onRename:e=>D(y.name,e),onDelete:()=>B(y.name),onAddModels:e=>_(y.name,e),enabledModels:o},y.name):null}let e=a.providers?.[y.providerName],t=e?.models?.[y.index];return t?(0,r.jsx)(uz,{providerName:y.providerName,provider:e,model:t,onChange:e=>U(y.providerName,y.index,e),onDelete:()=>q(y.providerName,y.index)},`${y.providerName}-${y.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(c$,{embedded:n,title:l("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:l("i18n.close"),onClose:t,children:[(0,r.jsx)(un,{controller:o}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsxs)(cM,{children:[J.map(e=>{let t=y?.type==="oauth"&&y.providerId===e.id;return(0,r.jsxs)(cL,{active:t,onClick:()=>w({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(ud,{id:e.id,size:16}),(0,r.jsx)(cz,{className:"is-grow",children:e.name}),Z(e.id)]},e.id)}),Y.map(e=>{let t=y?.type==="apikey"&&y.providerId===e.id;return(0,r.jsxs)(cL,{active:t,onClick:()=>w({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(ud,{id:e.id,size:16}),(0,r.jsx)(cz,{className:"is-grow",children:e.displayName}),Z(e.id)]},e.id)}),(J.length>0||Y.length>0)&&V.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):V.map(e=>{let[t,n]=e,i=y?.type==="provider"&&y.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(cL,{onClick:()=>w({type:"provider",name:t}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(cz,{className:"is-grow",children:t}),Z(t)]}),s.map((e,n)=>{let i=y?.type==="model"&&y.providerName===t&&y.index===n;return(0,r.jsxs)(cL,{active:i,className:"models-sidebar-indented-item",onClick:()=>w({type:"model",providerName:t,index:n}),children:[(0,r.jsx)(cz,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:e.name?.trim()||e.id||l("i18n.newModel")}),e.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)(cL,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),H(t)},children:(0,r.jsxs)(cz,{children:["+ ",l("i18n.model")]})})]},t)})]}),(0,r.jsx)(c8,{onClick:()=>I(!0),children:l("i18n.addProvider")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:c?null:G??(0,r.jsx)(cX,{children:l("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(c0,{status:g||f?(0,r.jsx)("span",{style:{color:"#f87171"},children:g?l("models.configUnreadable",{error:g}):f}):l("models.applyHelp"),children:[!n&&(0,r.jsx)(c2,{onClick:t,children:l("i18n.cancel")}),(0,r.jsxs)(c2,{variant:"primary",onClick:K,disabled:p||v||null!==g,className:v?"is-success":void 0,children:[v&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:v?l("i18n.saved"):p?l("i18n.saving"):l("i18n.save")})]})]})]}),E&&(0,r.jsx)(uO,{oauthProviders:j,apiKeyProviders:S,onSelectOAuth:e=>w({type:"oauth",providerId:e}),onSelectApiKey:e=>w({type:"apikey",providerId:e}),onAddCustom:W,onClose:()=>I(!1)})]})}let uD=null;async function uB(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(uD)return uD;let t=(async()=>{try{let t=await fetch("/api/push/config");if(!t.ok)return!1;let{publicKey:n}=await t.json();if(!n)return!1;let r=await navigator.serviceWorker.ready,i=await r.pushManager.getSubscription();return i||(i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}(n)})),(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscription:i.toJSON(),locale:e})})).ok}catch{return uD=null,!1}})();return uD=t,t.then(e=>{e||uD!==t||(uD=null)}),t}function uH(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function u_(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function uU(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function uq(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function uK(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function uV(e,t){return e?e.slice(0,8):t}function uZ(e){let{skill:t,cwd:n,onToggle:s,toggling:l,saveError:o,updateStatus:a,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:f}=(0,e0.s)(),m=uU(t),g=!t.disableModelInvocation,[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),w=t.filePath.split(/[\\/]/).pop(),[j,k]=(0,i.useState)([]),S=j.at(-1)??w,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[$,E]=(0,i.useState)(0),I=(0,i.useCallback)(e=>{let t=function(e,t){let n=e.indexOf("#"),[r,i]=[n<0?e:e.slice(0,n),n<0?"":e.slice(n+1)].map(e=>{try{return decodeURIComponent(e)}catch{return e}});if(!r)return{document:t,anchor:i};if(r.startsWith("/"))return{document:r,anchor:i};let s=t.split("/").slice(0,-1);for(let e of r.split("/"))".."===e&&s.length&&".."!==s[s.length-1]?s.pop():e&&"."!==e&&s.push(e);return{document:s.join("/"),anchor:i}}(e,S);N.current=t.anchor,t.document===S?E(e=>e+1):k(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||b)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,b,$]),(0,i.useEffect)(()=>{let e=new AbortController;return v(null),y(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});S!==w&&i.set("document",S);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),l=await s.json();if(!s.ok||l.error||"string"!=typeof l.content)throw Error(l.error??`HTTP ${s.status}`);v((r=l.content,dN(r).rest.trim()))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,S,w]),(0,r.jsxs)(cP,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(cW,{children:[(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:m,children:uq(m,f)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===m?ew(t.filePath,n):ey(t.filePath)})]}),(0,r.jsx)(cF,{children:(0,r.jsx)(c4,{checked:g,loading:l,label:f(g?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!g&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:f("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(cH,{label:f("config.source"),children:(0,r.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:t.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[t.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),t.install&&(0,r.jsxs)(cH,{label:f("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:uV(a?.currentVersion??t.install.versionHash,f("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(c2,{size:"small",onClick:p,disabled:d||c,children:f("i18n.check")}),a?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:uV(a.latestVersion,f("i18n.unknown"))}),(d||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":a?.state==="up-to-date"?"is-success":a?.state==="error"?"is-error":"is-muted"}`,children:d?f("i18n.checking"):a?.state==="up-to-date"?f("i18n.upToDate"):a?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):a?.message||f("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.jsx)(c2,{variant:"primary",size:"small",onClick:h,disabled:c||d,children:f(c?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(cH,{label:f("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(cH,{label:f("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(cH,{label:f("skills.instructions"),ref:C,children:[j.length>0&&(0,r.jsx)(cW,{children:(0,r.jsxs)(cO,{children:[(0,r.jsx)(c2,{size:"small",onClick:()=>{N.current="",k(e=>e.slice(0,-1))},children:f("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),b?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:b}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:f("i18n.loading")}):x?(0,r.jsx)(sk,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:I,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:f("skills.noInstructions")})]})]})}function uJ(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(new Set),[j,k]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(null),u([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);u(n.results??[]),0===(n.results??[]).length&&m(o("i18n.noSkills"))}catch(e){m(String(e))}finally{h(!1)}}},[o]),N=(0,i.useCallback)(async e=>{x(e),b(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:j,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);w(t=>new Set(t).add(`${j}:${e}`)),l()}catch(e){b(String(e))}finally{x(null)}},[l,j,t]),$="global"===j?"~/.pi/agent/skills/":`${ey(t)}/.pi/skills/`;return(0,r.jsxs)(cP,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(cZ,{title:o("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(cV,{value:j,label:o("config.saveTo"),options:[{value:"global",label:uq("global",o)},{value:"project",label:uq("project",o),disabled:!s}],path:$,disabledReason:o("trust.projectScopeUnavailable"),onChange:k})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(a)},placeholder:o("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(c2,{variant:"primary",onClick:()=>C(a),disabled:p||!a.trim(),children:p?o("i18n.searching"):o("i18n.search")})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:f}),v&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:v})]}),c.length>0&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let t=n[j].has(e.package)||y.has(`${j}:${e.package}`),i=g===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,a=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:a??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(c2,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==g,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${o("i18n.installed")}`:i?o("i18n.installing"):o("i18n.install")})]},e.package)})})]})}function uY(e){let{cwd:t,onClose:n,embedded:s=!1,trust:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)(()=>ci("skills",t)),[g,x]=(0,i.useState)(new Set),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),[j,k]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,$]=(0,i.useState)({}),[E,I]=(0,i.useState)(new Set),[M,T]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,z]=(0,i.useState)(null),[P,W]=(0,i.useState)(!0),O=(0,i.useCallback)(async()=>{u(!0),h(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}`),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);let r=n.skills??[];return d(r),W(n.projectResourcesLoaded??!0),m(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[t]);(0,i.useEffect)(()=>{$({}),z(null),O()},[t]);let F=u_(l),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,O())},[F,O]),(0,i.useEffect)(()=>{f&&cs("skills",f,t)},[t,f]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(uK).filter(e=>!!e);if(0!==n.length){z(null),I(e=>new Set([...e,...n])),e||T(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e?.install?.package,scope:e?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);$(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){z(e instanceof Error?e.message:String(e))}finally{I(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||T(!1)}}},[t,a]),H=(0,i.useCallback)(async e=>{if(!e.install)return;let n=uK(e);A(n),z(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,package:e.install.package,scope:e.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await O();let s=i.skill?.install?.versionHash;$(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,O]),_=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),b(null),k(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void b(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){b(String(e))}finally{x(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),U=(0,i.useCallback)(async(e,t,n)=>{let r=uH(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;x(e=>new Set([...e,...i])),w(e),b(null),k(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await t.json();if(!t.ok||n.error||!n.results)throw Error(n.error??`HTTP ${t.status}`);let l=n.results;d(e=>{let t;return t=new Set(l.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let a=l.filter(e=>e.error);if(a.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));k({group:e,error:[o("skills.bulkFailed",{count:a.length,total:l.length}),...a.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){k({group:e,error:t instanceof Error?t.message:String(t)})}finally{w(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[o]),q=a.find(e=>e.filePath===f)??null,K=c||g.size>0||null!==R;return(0,r.jsxs)(c$,{embedded:s,title:o("common.skills"),subtitle:ey(t),closeLabel:o("i18n.close"),onClose:n,children:[!P&&(0,r.jsx)(cG,{message:o("trust.skillsNotLoaded")}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===a.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:o("i18n.noSkills")}):(()=>{let e=[],t={project:o("skills.scope.project"),global:o("skills.scope.global"),path:o("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===uU(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===uU(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===uU(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===uU(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===uU(e)}]){let t=a.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&f===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(cL,{active:i,onClick:()=>{m(e.filePath),C(!1)},children:[(0,r.jsx)(c3,{active:!s}),(0,r.jsx)(cz,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=uK(e))?N[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:o("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:i}=e,s=i.filter(e=>!e.disableModelInvocation).length,l=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{aside:(0,r.jsx)(cR,{enabled:s,total:i.length,disabled:K,loading:y===t,label:o(l?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),j?.group===t&&(0,r.jsx)(cA,{error:j.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(c8,{onClick:()=>C(!0),active:S,children:o("i18n.addSkill")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:S?(0,r.jsx)(uJ,{cwd:t,projectResourcesLoaded:P,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{O()}}):c?null:q?(0,r.jsx)(uZ,{skill:q,cwd:t,onToggle:_,toggling:g.has(q.filePath),saveError:v,updateStatus:uK(q)?N[uK(q)]:void 0,checkingUpdate:!!uK(q)&&E.has(uK(q)),updating:R===uK(q),updateError:L,onCheckUpdate:()=>void B(q),onUpdate:()=>void H(q)},q.filePath):(0,r.jsx)(cX,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(c0,{status:Object.values(N).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(N).filter(e=>"update-available"===e.state).length," ",1===Object.values(N).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!s&&(0,r.jsx)(c2,{onClick:n,children:o("i18n.close")}),a.some(e=>!!e.install)&&(0,r.jsx)(c2,{variant:"secondary",onClick:()=>void B(),disabled:M||null!==R,children:M?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let uG={builtin:0,global:1,workspace:2,project:3},uX=["read","bash","edit","write","grep","find","ls"],uQ=["","off","minimal","low","medium","high","xhigh","max"],u0={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,codemode:"off",mcp:"off",promptMode:"append",inheritContext:!1,runInBackground:!1,enabled:!0},u1={width:"100%",minWidth:0,height:34,padding:"0 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},u2={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function u4(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,...void 0!==e.skills?{skills:[...e.skills]}:{},loadExtensions:e.loadExtensions,codemode:e.codemode??"off",mcp:e.mcp??"off",...void 0!==e.extensions?{extensions:[...e.extensions]}:{},promptMode:e.promptMode,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.maxTurns?{maxTurns:e.maxTurns}:{},inheritContext:e.inheritContext,runInBackground:e.runInBackground,enabled:e.enabled}}function u8(e){return`${e.scope}:${e.name}`}function u3(e){return"global"===e||"project"===e}function u5(e){return u3(e)||"builtin"===e}function u6(e){let{label:t,children:n}=e;return(0,r.jsx)(cH,{label:t,children:n})}function u9(e){let{checked:t,disabled:n,label:i,onChange:s}=e;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:7,color:n?"var(--text-dim)":"var(--text-muted)",fontSize:12,cursor:n?"default":"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,disabled:n,onChange:e=>s(e.target.checked)}),i]})}function u7(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:l,embedded:o=!1,trust:a}=e,d=te(),{t:c}=(0,e0.s)(),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(!0),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(()=>ci("agents",t)),[w,j]=(0,i.useState)(u0),[k,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[$,E]=(0,i.useState)(!0),[I,M]=(0,i.useState)(!1),[T,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,H]=(0,i.useState)(!0),[_,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[V,Z]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),G=(0,i.useMemo)(()=>u.find(e=>u8(e)===b)??null,[u,b]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{E(!0),P(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];p(i);let s=e??ci("agents",t),l=i.find(e=>u8(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(l?u8(l):null),l&&(j(u4(l)),S(u3(l.scope)?"edit":"view"),u3(l.scope)&&N(l.scope))}catch(e){P(e instanceof Error?e.message:String(e))}finally{E(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);O(n.enabled),"number"==typeof n.maxConcurrent&&D(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{b&&cs("agents",b,t)},[t,b]);let ee=u_(a);(0,i.useEffect)(()=>{let e=new AbortController;return g(!0),v(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);f(r.modelList??[]),v(r.modelError??null)}catch(t){if(e.signal.aborted)return;v(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||g(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{M(!0),P(null),R(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:C,profile:w})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(u8(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}},en=async()=>{if(G&&u3(G.scope)&&window.confirm(c("agents.deleteConfirm",{name:G.displayName}))){M(!0),P(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){P(e instanceof Error?e.message:String(e))}finally{M(!1)}}},er="view"!==k,ei="create"===k,es=!er||I||A,el=ei?C:G?.scope,eo=ei?"global"===C?`~/.pi/agent/agents/${w.name||"..."}.md`:`./.pi/agents/${w.name||"..."}.md`:G?(G.filePath?"project"===G.scope||"workspace"===G.scope?ew(G.filePath,t):ey(G.filePath):null)??c("agents.builtinPath"):"",ea=ei?eo:G?.filePath??eo,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=w.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&uQ.includes(r)?e.slice(0,n):e}(w.model,ed),eu=!ec||ed(ec),ep=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eh=es?{...u1,...u2}:u1,ef=ei?es:!G||!u5(G.scope)||I||A,em=(e,t)=>{j(n=>({...n,[e]:t}))},eg=0===w.tools.length&&!w.loadSkills&&!w.loadExtensions,ex=async e=>{if(ei)return void em("enabled",e);if(G&&u5(G.scope)){L(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:G.scope,name:G.name,enabled:e})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;p(e=>e.map(e=>u8(e)===u8(i)?i:e)),j(e=>({...e,enabled:i.enabled}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ev=async e=>{U(!0),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await t.json();if(!t.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${t.status}`);O(r.enabled),Z(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{U(!1)}},eb=async e=>{D(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);D(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ej=async()=>{if(n){Y(!0),K(null);try{await aI(n,{type:"reload"}),Z(!1),l?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(c$,{embedded:o,title:c("common.agents"),subtitle:ey(t),closeLabel:c("agents.close"),onClose:s,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:c("agents.builtInTitle")}),(0,r.jsx)("span",{children:c("agents.builtInDescription")}),V&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[V&&n&&(0,r.jsx)(c2,{size:"small",onClick:()=>void ej(),disabled:J||_,children:J?c("agents.reloading"):c("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:c("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:c("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":c("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:B||_,onChange:e=>D(Number(e.target.value)),onBlur:()=>void eb(F)})]}),(0,r.jsx)(c4,{checked:W,disabled:B||J,loading:_,label:c("agents.builtInTitle"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:$?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:c("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=u.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=uG[e.scope],u.some(e=>e.name.toLowerCase()===t&&uG[e.scope]>n));return(0,r.jsxs)(cL,{active:b===u8(e)&&!ei,onClick:()=>{y(u8(e)),j(u4(e)),S(u3(e.scope)?"edit":"view"),u3(e.scope)&&N(e.scope),P(null)},children:[(0,r.jsx)(c3,{active:e.enabled}),(0,r.jsx)(cz,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},u8(e))})]},e)})}),(0,r.jsx)(c8,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),j({...u0,name:e,displayName:e}),S("create"),N("global"),P(null)},children:c("agents.new")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:G||ei?(0,r.jsxs)(cP,{children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:ei?(0,r.jsx)(cV,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:I})),path:eo,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[el&&(0,r.jsx)(cq,{scope:el,children:c(`agents.scope.${el}`)}),(0,r.jsx)("span",{title:ea,className:"config-detail-path",children:eo})]})}),(0,r.jsxs)(cF,{children:[G&&("view"===k||"edit"===k)&&(0,r.jsx)(c2,{size:"small",onClick:()=>{if(!G)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(G.name,u);y(null),j({...u4(G),name:e,displayName:c("agents.copyName",{name:G.displayName})}),S("create"),N(u3(G.scope)?G.scope:"global"),P(null)},disabled:I||A,children:c("agents.duplicate")}),G&&u3(G.scope)&&"edit"===k&&(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:()=>void en(),disabled:I||A,children:c("agents.delete")}),(0,r.jsx)(c4,{checked:w.enabled,disabled:ef,label:w.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ex(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(u6,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:w.name,disabled:es,onChange:e=>em("name",e.target.value),style:u1}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:w.name})}),(0,r.jsx)(u6,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:w.displayName,disabled:es,onChange:e=>em("displayName",e.target.value),style:eh})})]}),(0,r.jsx)(u6,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:w.description,disabled:es,onChange:e=>em("description",e.target.value),style:eh})}),(0,r.jsx)(u6,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:w.systemPrompt,disabled:es,onChange:e=>em("systemPrompt",e.target.value),style:{...eh,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(u6,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:uX.map(e=>(0,r.jsx)(u9,{label:e,disabled:es,checked:w.tools.includes(e),onChange:t=>em("tools",t?[...w.tools,e]:w.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(u6,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(u9,{label:c("agents.loadSkills"),disabled:es,checked:w.loadSkills,onChange:e=>em("loadSkills",e)}),(0,r.jsx)(u9,{label:c("agents.loadExtensions"),disabled:es,checked:w.loadExtensions,onChange:e=>em("loadExtensions",e)}),(0,r.jsx)(u9,{label:c("agents.mcp"),disabled:es||eg&&"on"!==w.mcp,checked:"on"===w.mcp,onChange:e=>em("mcp",e?"on":"off")})]}),w.loadSkills&&void 0!==w.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:w.skills.length>0?c("agents.skillsOnly",{skills:w.skills.join(", ")}):c("agents.skillsNone")}),w.loadExtensions&&void 0!==w.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:w.extensions.length>0?c("agents.extensionsOnly",{extensions:w.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eg?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===w.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(u6,{label:c("agents.codemode"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsxs)("select",{"aria-label":c("agents.codemode"),value:w.codemode??"off",disabled:es,onChange:e=>em("codemode",e.target.value),style:{...eh,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,r.jsx)("option",{value:"inherit",children:c("agents.codemode.inherit")}),(0,r.jsx)("option",{value:"on",children:c("agents.codemode.on")}),(0,r.jsx)("option",{value:"off",children:c("agents.codemode.off")})]}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.codemodeHint")})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(u6,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(oW,{options:X,value:ep,onChange:(e,t)=>em("model",`${e}/${t}`),onClear:()=>em("model",void 0),emptyLabel:m?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:w.model&&!eu?c("agents.modelUnavailable",{model:w.model}):w.model!==ec?w.model:void 0,disabled:es||m||0===h.length&&!w.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(u6,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:w.thinking??"",disabled:es,onChange:e=>em("thinking",e.target.value||void 0),style:eh,children:uQ.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(u6,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:w.maxTurns??"",disabled:es,onChange:e=>em("maxTurns",e.target.value?Number(e.target.value):void 0),style:eh})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(u9,{label:c("agents.inheritContext"),disabled:es,checked:w.inheritContext,onChange:e=>em("inheritContext",e)}),(0,r.jsx)(u9,{label:c("agents.background"),disabled:es,checked:w.runInBackground,onChange:e=>em("runInBackground",e)})]})]}):(0,r.jsx)(cX,{children:c("agents.empty")})})})]}),(0,r.jsx)(c0,{status:(q||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||z}),children:er&&(0,r.jsxs)(c2,{variant:"primary",onClick:()=>void et(),disabled:I||T||A||!w.name.trim(),className:T?"is-success":void 0,children:[T&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:T?c("i18n.saved"):I?c("agents.saving"):c("agents.save")})]})})]})}let pe=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function pt(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function pn(e){return`${e.scope}\0${e.source}`}function pr(e){return`extension\0${e.path}`}function pi(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function ps(e,t){return t(`plugins.status.${e}`)}function pl(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function po(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function pa(e){let{pkg:t}=e,{t:n}=(0,e0.s)(),i=[["extension",n("i18n.extensions")],["skill",n("i18n.skills")],["prompt",n("i18n.prompts")],["theme",n("i18n.themes")]].map(e=>{let[n,r]=e;return{kind:n,label:r,resources:t.resources.filter(e=>e.kind===n)}}).filter(e=>e.resources.length>0);return 0===i.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n(t.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:i.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function pd(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:l,actionError:o,onSourceChange:a,onScopeChange:d,onInstall:c}=e,{t:u}=(0,e0.s)();return(0,r.jsx)(cJ,{title:u("i18n.addPlugin"),catalogs:[{href:"https://pi.dev/packages",label:"pi.dev/packages",icon:(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]})}],target:(0,r.jsx)(cV,{value:i,label:u("config.saveTo"),options:[{value:"global",label:pi("global",u)},{value:"project",label:pi("project",u),disabled:!s}],path:"project"===i?`${ey(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:d}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!l&&!!n.trim(),normalizeValue:pt,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:pe,error:o,children:(0,r.jsx)(c2,{variant:"primary",onClick:c,disabled:l||!n.trim(),className:"is-pushed-right",children:u(l?"i18n.installing":"i18n.install")})})}function pc(e){let t,{pkg:n,cwd:s,busyKey:l,actionError:o,actionMessage:a,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:f,onReloadSession:m}=e,{t:g}=(0,e0.s)(),x=pn(n),v=(l?.endsWith(x)||l?.startsWith("bulk:"))??!1,b="reload"===l,y=!n.disabled,w=n.canCheckForUpdates,j=c?.state==="update-available",k=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(cP,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cW,{className:"is-top-aligned",children:[(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:n.scope,children:pi(n.scope,g)}),n.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:g("i18n.disabled")}):n.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:g("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.source})]}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(c2,{size:"small",variant:j?"primary":void 0,onClick:j||!w?()=>h("update",n):f,disabled:v||b||u,title:j?g("i18n.updateAvailable"):void 0,children:g(l===`update:${x}`?"i18n.updating":u?"i18n.checking":j||!w?"i18n.update":"i18n.check")}),(0,r.jsx)(c2,{size:"small",onClick:m,disabled:!d||b||v,"aria-describedby":d?void 0:S,children:g(b?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(c2,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:v||b,children:g(l===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(c4,{checked:y,loading:v||b,onChange:()=>h(n.disabled?"enable":"disable",n),label:g(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:g("i18n.openSessionToReload")})]}),(0,r.jsxs)(c_,{children:[k&&(0,r.jsx)(cU,{label:g("i18n.description"),children:k}),(0,r.jsx)(cU,{label:g("i18n.status"),tone:"plain",style:{color:po(n.status),textTransform:"capitalize"},children:ps(n.status,g)}),(0,r.jsxs)(cU,{label:g("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(t=[],n.version&&t.push(g("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(g("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):g("i18n.unknown"))}),j&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:g("i18n.updateAvailable")}),w&&(u||c&&!j)&&(0,r.jsx)("span",{className:`skill-update-status ${u?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:u?g("i18n.checking"):c?.state==="up-to-date"?g("i18n.upToDate"):c?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):c?.message||g("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(cU,{label:g("i18n.package"),mono:!0,children:n.packageName??g("i18n.unknown")}),(0,r.jsx)(cU,{label:g("i18n.resources"),children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(n,g)}),(0,r.jsx)(cU,{label:g("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?ey(n.installedPath):g("i18n.notFound")}),(0,r.jsx)(cU,{label:g("i18n.cwd"),tone:"dim",mono:!0,children:ey(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(cB,{children:g("i18n.resolvedResources")}),(0,r.jsx)(pa,{pkg:n})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function pu(e){let{extension:t}=e,{t:n}=(0,e0.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(cP,{children:[(0,r.jsx)(cW,{children:(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:t.scope,children:pi(t.scope,n)}),(0,r.jsx)(cD,{children:t.name})]})}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(cU,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:ps(i,n)}),(0,r.jsx)(cU,{label:n("i18n.installedPath"),mono:!0,children:ey(t.path)})]})]})}function pp(e){var t;let{cwd:n,sessionId:s,onClose:l,onReloaded:o,embedded:a=!1,trust:d}=e,{t:c}=(0,e0.s)(),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(()=>ci("plugins",n)),[b,y]=(0,i.useState)(!1),[w,j]=(0,i.useState)(""),[k,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[$,E]=(0,i.useState)(null),[I,M]=(0,i.useState)(null),[T,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[z,P]=(0,i.useState)(new Set),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),_=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),q=_.find(e=>pn(e)===x)??null,K=U.find(e=>pr(e)===x)??null,V=u?.projectResourcesLoaded??!0,Z=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:_.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[_]),J=(0,i.useCallback)(async()=>{f(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>pn(t)===e)||t.standaloneExtensions.some(t=>pr(t)===e))?e:t.packages[0]?pn(t.packages[0]):t.standaloneExtensions[0]?pr(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{f(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let Y=u_(d),G=(0,i.useRef)(Y);(0,i.useEffect)(()=>{G.current!==Y&&(G.current=Y,J())},[Y,J]),(0,i.useEffect)(()=>{x&&cs("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:_.filter(e=>e.canCheckForUpdates)).map(pn);if(0!==t.length){D(null),P(e=>new Set([...e,...t])),e||O(!0);try{let t=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,source:e?.source,scope:e?.scope})}),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);L(e=>{let t={...e};for(let e of r.updates??[])t[pn(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||O(!1)}}},[n,_]),Q=(0,i.useCallback)(async()=>{H(!0),E(null),M(null),D(null);try{let e=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:n})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);p(t),L({}),M(c("i18n.packagesUpdated")),s&&M(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){E(e instanceof Error?e.message:String(e))}finally{H(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=pn(t);N(`${e}:${r}`),E(null),M(null),R(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,source:t.source,scope:t.scope,cwd:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);if(p(s),"remove"===e)v(s.packages[0]?pn(s.packages[0]):s.standaloneExtensions[0]?pr(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),M(c("i18n.packageRemoved")),L(e=>{let t={...e};return delete t[r],t});else{let t={install:c("i18n.packageInstalled"),update:c("i18n.packageUpdated"),disable:c("i18n.packageDisabled"),enable:c("i18n.packageEnabled")};M(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t,r)=>{let i=uH(t,r,e=>!e.disabled,e=>e.filtered),l=r?0:t.filter(e=>!e.disabled&&e.filtered).length,o=l>0?c("plugins.bulkKeptFiltered",{count:l}):void 0;if(E(null),M(null),R(o?{scope:e,note:o}:null),0===i.length)return;let a=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:a,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),l=await t.json();if(!t.ok||l.error||!l.results)throw Error(l.error??`HTTP ${t.status}`);let{results:d,...u}=l;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");M(s?`${e} ${c("agents.reloadRequired")}`:e)}h.length>0&&R({scope:e,note:o,error:[c("plugins.bulkFailed",{count:h.length,total:d.length}),...h.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:o,error:t instanceof Error?t.message:String(t)})}finally{N(null)}},[n,s,c]),en=(0,i.useCallback)(async()=>{let e=pt(w).trim();if(!e)return;j(e);let t=`${k}\0${e}`;N(`install:${t}`),E(null),M(null),R(null);try{var r;let i,s,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:k,cwd:n})}),o=await l.json();if(!l.ok||o.error)throw Error(o.error??`HTTP ${l.status}`);p(o);let a=(r=o.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===k&&e.source===i)??r.find(e=>e.scope===k&&e.source===`npm:${s}`)??r.find(e=>e.scope===k&&e.source.endsWith(i)));v(a?pn(a):t),y(!1),j(""),M(c("i18n.packageInstalled"))}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,k,w,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),E(null),M(null),R(null);try{await aI(s,{type:"reload"}),o?.(),await J(),M(c("i18n.sessionReloaded"))}catch(e){E(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,o,s,c]),ei=C?.startsWith("install:")??!1,es=Object.values(A).filter(e=>"update-available"===e.state).length,el=_.some(e=>e.canCheckForUpdates),eo=h||null!==C||z.size>0||B;return(0,r.jsxs)(c$,{embedded:a,title:c("common.plugins"),subtitle:ey(n),closeLabel:c("i18n.close"),onClose:l,children:[!V&&(0,r.jsx)(cG,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):m?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:m}):0===_.length&&0===U.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:c("i18n.noPlugins")}):(0,r.jsxs)(r.Fragment,{children:[U.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{children:c("i18n.extensions")}),U.map(e=>{let t=pr(e);return(0,r.jsxs)(cL,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),E(null),M(null)},children:[(0,r.jsx)(c3,{active:e.enabled}),(0,r.jsx)(cz,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),Z.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{aside:(0,r.jsx)(cR,{enabled:t,total:e.packages.length,disabled:eo,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:pi(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:pi(e.scope,c)}),T?.scope===e.scope&&(0,r.jsx)(cA,{error:T.error,note:T.note}),e.packages.map(e=>{let t=pn(e),n=!b&&x===t;return(0,r.jsxs)(cL,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),E(null),M(null)},children:[(0,r.jsx)(c3,{active:!e.disabled,color:po(e.status)}),(0,r.jsx)(cz,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[pn(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(c8,{active:b,onClick:()=>{y(!0),E(null),M(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:b?(0,r.jsx)(pd,{cwd:n,source:w,scope:k,projectResourcesLoaded:V,busy:ei,actionError:$,onSourceChange:j,onScopeChange:S,onInstall:en}):h?null:K?(0,r.jsx)(pu,{extension:K}):q?(0,r.jsx)(pc,{pkg:q,cwd:n,busyKey:C,actionError:$,actionMessage:I,sessionId:s,updateStatus:A[pn(q)],checkingUpdate:z.has(pn(q)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(q),onReloadSession:er},pn(q)):(0,r.jsx)(cX,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(c0,{status:es>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[es," ",1===es?c("i18n.update"):c("i18n.updates")]}):u?.diagnostics.length?(0,r.jsx)(c1,{tone:u.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===u.diagnostics.length?c("plugins.diagnostic"):c("plugins.diagnostics",{count:u.diagnostics.length}),details:u.diagnostics.map(pl)}):(0,r.jsx)(c1,{summary:u?[c("i18n.resourceCount",{count:(t=u.totals).extensions,label:c("i18n.extensionShort")}),c("i18n.resourceCount",{count:t.skills,label:c("i18n.skillShort")}),c("i18n.resourceCount",{count:t.prompts,label:c("i18n.promptShort")}),c("i18n.resourceCount",{count:t.themes,label:c("i18n.themeShort")})].join(" \xb7 "):""}),children:[!a&&(0,r.jsx)(c2,{onClick:l,children:c("i18n.close")}),el&&(0,r.jsx)(c2,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?Q():X()),disabled:eo,title:es>0?c("i18n.updateAllPluginsHint"):void 0,children:B?c("i18n.updating"):W?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(c2,{variant:"secondary",onClick:()=>void J(),disabled:eo,children:c("i18n.refresh")})]})]})}let ph={en:{title:"Archives",empty:"No archived projects.",loadFailed:"Could not load archives.",sessions:"{count} sessions",unarchive:"Unarchive",deleteSessions:"Delete",deleteConfirmLead:"Deletes {count} chat sessions. Does not delete the code folder.",deleteConfirmHint:"Type confirm to continue.",deleteConfirmName:"confirm",cancel:"Cancel",busy:"Working…",runningBlocked:"Stop the running agent in this project first.",deleteFailed:"Could not delete those sessions.",path:"Path",untitled:"Untitled session",messages:"{count} messages"},"zh-CN":{title:"归档",empty:"没有已归档的项目。",loadFailed:"无法加载归档列表。",sessions:"{count} 个会话",unarchive:"取消归档",deleteSessions:"删除",deleteConfirmLead:"将删除该项目下 {count} 个聊天会话,不会删除磁盘上的代码目录。",deleteConfirmHint:"输入「确认」继续。",deleteConfirmName:"确认",cancel:"取消",busy:"处理中…",runningBlocked:"请先停止该项目中正在运行的 agent。",deleteFailed:"删除会话失败。",path:"路径",untitled:"未命名会话",messages:"{count} 条消息"},"zh-TW":{title:"封存",empty:"沒有已封存的專案。",loadFailed:"無法載入封存清單。",sessions:"{count} 個工作階段",unarchive:"取消封存",deleteSessions:"刪除",deleteConfirmLead:"將刪除該專案下 {count} 個聊天工作階段,不會刪除磁碟上的程式碼目錄。",deleteConfirmHint:"輸入「確認」繼續。",deleteConfirmName:"確認",cancel:"取消",busy:"處理中…",runningBlocked:"請先停止該專案中正在執行的 agent。",deleteFailed:"刪除工作階段失敗。",path:"路徑",untitled:"未命名工作階段",messages:"{count} 則訊息"}};function pf(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function pm(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function pg(e){var t;let n,{onClose:s,embedded:l=!1}=e,{locale:o}=(0,e0.s)(),a=ph[o]??ph.en,[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(""),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,j]=(0,i.useState)(""),[k,S]=(0,i.useState)(null),C=(0,i.useCallback)(async()=>{g(!1);try{let[e,t]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok)throw Error("load failed");let n=await e.json(),r=await t.json().catch(()=>({}));"string"==typeof r.home&&f(r.home);let i=Array.isArray(n.projects)?n.projects:[];c(i),p(e=>e&&i.some(t=>t.key===e)?e:i[0]?.key??null)}catch{g(!0)}},[]);(0,i.useEffect)(()=>{C()},[C]);let N=d.find(e=>e.key===u)??null,$=async e=>{if(0!==e.length){v(!0),S(null);try{for(let t of L(e)){let e={action:"set",ids:t,archived:!1},n=await fetch("/api/sessions/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"});if(!n.ok)throw Error(`unarchive failed: ${n.status}`)}y(!1),j(""),await C()}catch{S(a.loadFailed)}finally{v(!1)}}},E=async e=>{v(!0),S(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:w.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void S(a.runningBlocked);if(!t.ok)throw Error(n.error??"delete failed");y(!1),j(""),c(t=>t.filter(t=>t.key!==e.key)),p(t=>t===e.key?null:t)}catch{S(a.deleteFailed)}finally{v(!1)}};return(0,r.jsx)(c$,{embedded:l,title:a.title,onClose:s,children:m?(0,r.jsx)(cX,{children:a.loadFailed}):0===d.length?(0,r.jsx)(cX,{children:a.empty}):(0,r.jsxs)(cE,{children:[(0,r.jsx)(cI,{children:(0,r.jsx)(cM,{children:d.map(e=>(0,r.jsx)(cL,{active:e.key===u,onClick:()=>{p(e.key),y(!1),j(""),S(null)},children:(0,r.jsx)(cz,{title:e.root,children:pm(e.root)})},e.key))})}),(0,r.jsx)(cQ,{children:N?(0,r.jsxs)(cP,{children:[(0,r.jsxs)(cW,{children:[(0,r.jsx)(cO,{children:(0,r.jsx)(cD,{children:pm(N.root)})}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(c2,{variant:"secondary",size:"small",disabled:x||0===N.families.length,onClick:()=>void $(N.families.map(e=>e.id)),children:x?a.busy:a.unarchive}),!b&&(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:x||0===N.families.length,onClick:()=>{y(!0),j(""),S(null)},children:a.deleteSessions})]})]}),(0,r.jsx)(cH,{label:a.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(t=N.root,h&&t.startsWith(h)?"~"+t.slice(h.length):t)})}),b&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:pf(a.deleteConfirmLead,{count:N.families.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:a.deleteConfirmHint}),(0,r.jsx)("input",{value:w,onChange:e=>j(e.target.value),placeholder:a.deleteConfirmName,"aria-label":a.deleteConfirmName,autoComplete:"off",style:{alignSelf:"flex-start",width:"min(220px, 100%)",fontFamily:"var(--font-mono)",fontSize:12,padding:"6px 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:x||"confirm"!==(n=w.trim().toLowerCase())&&"确认"!==n&&"確認"!==n,onClick:()=>void E(N),children:x?a.busy:a.deleteSessions}),(0,r.jsx)(c2,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),j("")},children:a.cancel})]})]}),(0,r.jsx)(cB,{children:pf(a.sessions,{count:N.families.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:N.families.map(e=>{let t=function(e,t){let n=e.name?.trim();if(n)return n;let r=e.firstMessage?.replace(/\s+/g," ").trim();return r&&"(no messages)"!==r?r:t}(e,a.untitled);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:6,background:"var(--bg-hover)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsx)(c2,{variant:"ghost",size:"small",disabled:x,onClick:()=>void $([e.id]),children:x?a.busy:a.unarchive})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,t8.fw)(new Date(e.archivedAt),o)}),(0,r.jsx)("span",{children:pf(a.messages,{count:e.messageCount})})]})]},e.id)})}),k&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:k})]}):(0,r.jsx)(cX,{children:a.empty})})]})})}let px="\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\u00A0\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000\\uFE00-\\uFE0F\\u{E0100}-\\u{E01EF}\\u115F\\u1160\\u3164\\uFFA0\\u2800",pv=RegExp(`[${px}]`,"gu"),pb=RegExp(`[${px}]`,"u");function py(e){return e.replace(pv,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let pw=/[\s"'`$|&;<>()*?#~]/;function pj(e){let t=pb.test(e),n=py(e);return""===n||t||pw.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function pk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(pj).join(" ")}function pS(e){let t=void 0!==e.command?pk(e.command,e.args):void 0,n=void 0!==e.url?py(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function pC(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&pb.test(e))}function pN(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:py(e.name??"")}}}function p$(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function pE(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function pI(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function pM(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?py(e.error):"link-outside"===e.reason?void 0===t?void 0:py(t):void 0}let pT="codemode";function pR(e){return`${e.scope}\0${e.name}`}function pA(e){return e?.trust?.decision===!0}function pL(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function pz(e,t){return void 0!==e.invalidError?"invalid":e.webPasswordField?"web-password":e.enabled?"project"!==e.scope||t.projectServersLoad?"global"===e.scope&&e.shadowedByProject&&t.projectServersLoad?"replaced":"global"===e.scope&&e.overriddenByProject&&t.projectServersLoad?"overridden":t.mcpAvailable?e.status?pL(e.status):"on":"mcp-off":"not-trusted":"disabled"}let pP={invalid:"mcp.state.invalid","web-password":"mcp.state.web-password",disabled:"mcp.state.disabled","not-trusted":"mcp.state.not-trusted",replaced:"mcp.state.replaced",overridden:"mcp.state.overridden","mcp-off":"mcp.state.mcp-off",connected:"mcp.state.connected","needs-auth":"mcp.state.needs-auth",failed:"mcp.state.failed",connecting:"mcp.state.connecting",disconnected:"mcp.state.disconnected",conflict:"mcp.state.conflict",on:"mcp.state.on"},pW={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function pO(e,t){return(t?.origin==="session"?pW[e]:void 0)??pP[e]}let pF={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},pD={invalid:"mcp.stateShort.invalid","web-password":"mcp.stateShort.web-password",disabled:"mcp.stateShort.disabled","not-trusted":"mcp.stateShort.not-trusted",replaced:"mcp.stateShort.replaced",overridden:"mcp.stateShort.overridden","needs-auth":"mcp.stateShort.needs-auth",failed:"mcp.stateShort.failed",connecting:"mcp.stateShort.connecting",disconnected:"mcp.stateShort.disconnected",conflict:"mcp.stateShort.conflict"};function pB(e){return"on"===e||"connected"===e?"on":"invalid"===e||"web-password"===e||"failed"===e||"conflict"===e?"error":"not-trusted"===e||"needs-auth"===e||"disconnected"===e?"warning":"off"}function pH(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function p_(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=new Date(e),i=new Date(n);return r.getFullYear()===i.getFullYear()&&r.getMonth()===i.getMonth()&&r.getDate()===i.getDate()?r.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"}):r.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}let pU={connecting:"mcp.session.state.connecting",connected:"mcp.session.state.connected","needs-auth":"mcp.session.state.needs-auth",failed:"mcp.session.state.failed",disconnected:"mcp.session.state.disconnected",conflict:"mcp.session.state.conflict","not-trusted":"mcp.session.state.not-trusted"},pq={connecting:"mcp.session.summary.connecting",connected:"mcp.session.summary.connected","needs-auth":"mcp.session.summary.needs-auth",failed:"mcp.session.summary.failed",disconnected:"mcp.session.summary.disconnected",conflict:"mcp.session.summary.conflict","not-trusted":"mcp.session.summary.not-trusted"},pK={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},pV={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},pZ=["codemode","deferred","direct","hidden"],pJ={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function pY(e){return"auto-enable-codemode-invalid"!==e.reason}function pG(e,t){return(t?["project","global"]:["global"]).map(t=>{let n=e.files.find(e=>e.scope===t);return{scope:t,...n?{file:n}:{},servers:e.servers.filter(e=>e.scope===t)}})}function pX(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function pQ(e,t){let n=e.flatMap(e=>e.servers.map(pR));return t===pT||null!==t&&n.includes(t)?t:n[0]??null}function p0(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function p1(e){return e.projectOverride?.preference??e.preference}let p2={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},p4={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},p8={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},p3={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function p5(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let p6=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function p9(e,t){let n=e??{},r=n.breadth,i=n.trust;return{error:"string"==typeof n.error?n.error:`HTTP ${t}`,..."string"==typeof n.reason?{reason:n.reason}:{},..."string"==typeof n.path?{path:n.path}:{},..."string"==typeof n.name?{name:n.name}:{},..."string"==typeof n.suggestedName?{suggestedName:n.suggestedName}:{},...p6(n.names)?{names:n.names}:{},...p6(n.fields)?{fields:n.fields}:{},...Array.isArray(n.notes)?{notes:n.notes.filter(e=>"string"==typeof e?.code)}:{},..."string"==typeof r?.kind&&"string"==typeof r.path?{breadth:r}:{},..."boolean"==typeof i?.requiresTrust&&"boolean"==typeof i.trusted?{trust:i}:{},...!0===n.trustKept?{trustKept:!0}:{}}}async function p7(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},l=new AbortController,o=()=>l.abort();r?.aborted?l.abort():r?.addEventListener("abort",o,{once:!0});let a=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&l.abort()},n)});try{return await Promise.race([e(l.signal),a])}finally{clearTimeout(i),r?.removeEventListener("abort",o)}}function he(e){return null!==e&&"object"==typeof e&&"object"==typeof e.mcp&&null!==e.mcp&&"object"==typeof e.codemode&&null!==e.codemode&&Array.isArray(e.files)&&Array.isArray(e.servers)}async function ht(e,t,n){let r,i;try{r=await t(e?`/api/mcp?cwd=${encodeURIComponent(e)}`:"/api/mcp",{cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&he(i)?{ok:!0,data:i}:{ok:!1,error:p9(i,r.status)}}let hn=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function hr(e,t,n){let r=await ht(e,t,n);if(r.ok||!e||!r.error.reason||!hn.has(r.error.reason))return r;let i=await ht(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function hi(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(n=>hr(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function hs(e,t,n,r){let i,s;try{i=await n("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{s=await i.json()}catch{return{ok:!1,error:{error:`HTTP ${i.status}`}}}let l=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==l?{ok:!0,stored:l}:{ok:!1,error:p9(s,i.status)}}async function hl(e,t,n){let r=await hs({codemode:e},e=>{var t;return"automatic"===(t=e.codemode)||"always"===t?e.codemode:void 0},t,n);return r.ok?{ok:!0,preference:r.stored}:r}async function ho(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(n=>hl(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function ha(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(async n=>{let r=await hs({codemodeMode:e},e=>{var t;return null!==(t=e.codemodeMode)&&"object"==typeof t&&("on"===t.value||"only"===t.value)&&(void 0===t.invalid||"string"==typeof t.invalid)?e.codemodeMode:void 0},t,n);return r.ok?{ok:!0,mode:r.stored}:r},()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function hd(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return p7(async n=>{let r=await hs({codemodeInlineBudget:e},e=>{var t;return null!==(t=e.codemodeInlineBudget)&&"object"==typeof t&&(void 0===t.value||"number"==typeof t.value)&&(void 0===t.invalid||"string"==typeof t.invalid)?e.codemodeInlineBudget:void 0},t,n);return r.ok?{ok:!0,inlineBudget:r.stored}:r},()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}function hc(e){return!e.available&&"builtin-disabled"!==e.reason}function hu(e,t){if(hc(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!pA(t.project))return"project-untrusted"}}let hp={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function hh(e){return!0!==e.notAnObject}function hf(e){return hh(e)&&void 0===e.webPasswordField}async function hm(e,t,n){let r,i;try{r=await t("/api/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&he(i)?{ok:!0,data:i}:{ok:!1,error:p9(i,r.status)}}async function hg(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3,s={...e,...t?{cwd:t}:{}};return p7(e=>hm(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let hx={"mcp-off":"mcp.test.blocked.mcp-off","project-untrusted":"mcp.test.blocked.project-untrusted","trust-unreadable":"mcp.test.blocked.trust-unreadable",invalid:"mcp.test.blocked.invalid","web-password":"mcp.test.blocked.web-password"};function hv(e,t){let n=hu(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let hb={"mcp-off":"mcp.test.blocked.mcp-off","project-untrusted":"mcp.test.blocked.project-untrusted","trust-unreadable":"mcp.test.blocked.trust-unreadable","server-invalid":"mcp.test.blocked.invalid","web-password":"mcp.test.blocked.web-password","entry-not-object":"mcp.test.refused.entry-not-object","invalid-request":"mcp.test.refused.invalid-request",unparsable:"mcp.test.refused.unparsable","invalid-shape":"mcp.test.refused.invalid-shape","link-dangling":"mcp.test.refused.link-dangling","link-outside":"mcp.test.refused.link-outside","not-a-file":"mcp.test.refused.not-a-file","too-large":"mcp.test.refused.too-large","too-many-servers":"mcp.test.refused.too-many-servers"},hy={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},hw={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},hj={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function hk(e){return(Math.max(0,e)/1e3).toFixed(1)}async function hS(e,t,n){let r,i;try{r=await t("/api/mcp/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store",signal:n})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{i=await r.json()}catch{return{ok:!1,error:{error:`HTTP ${r.status}`}}}return r.ok&&function(e){if(null===e||"object"!=typeof e)return!1;let t=e.result;return"string"==typeof e.configKey&&"string"==typeof e.name&&("global"===e.scope||"project"===e.scope)&&"object"==typeof t&&null!==t&&"string"==typeof t.state&&Array.isArray(t.tools)&&"number"==typeof t.testedAt}(i)?{ok:!0,data:i}:{ok:!1,error:p9(i,r.status)}}async function hC(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:6e4,s={scope:e.scope,name:e.name,...t?{cwd:t}:{}};return p7(e=>hS(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let hN="•••",h$=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),hE=new Set([...h$,"auth","sig","code","pw"]),hI=["token","secret","password","passwd","apikey"],hM=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),hT=new Set(["-k"]);function hR(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function hA(e,t){let n=hR(e);return!(n.length>1&&hM.has(n[n.length-1]))&&n.some(e=>t.has(e)||hI.some(t=>e.length>t.length&&e.endsWith(t)))}function hL(e){return hA(e,h$)}let hz=RegExp("^(?:sk-[A-Za-z0-9_-]{16,}|(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abposr]-[A-Za-z0-9-]{10,}|(?:AKIA|ASIA)[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|ya29\\.[0-9A-Za-z_-]{20,}|npm_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{30,}|shp(?:at|ss|ca|pa)_[A-Fa-f0-9]{20,}|dop_v1_[a-f0-9]{40,}|lin_api_[A-Za-z0-9]{20,})"),hP=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,hW=/^[A-Za-z0-9_\-+/=.~]+$/;function hO(e){return!(/\s/.test(e)||h_(e))&&(!!(hz.test(e)||hP.test(e))||!(e.length<24||!hW.test(e)||/^[./~]/.test(e)||/\.[A-Za-z][A-Za-z0-9]{0,4}$/.test(e)||e.split("/").length>2)&&!!/\d/.test(e)&&!!/[A-Za-z]/.test(e)&&(/[a-z]/.test(e)&&/[A-Z]/.test(e)||/^[0-9a-f]+$/i.test(e)||!/[-_.]/.test(e))&&function(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0;for(let r of t.values()){let t=r/e.length;n-=t*Math.log2(t)}return n}(e)>=3.5)}let hF=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,hD=RegExp(hF.source,"g"),hB=/^(?:bearer|basic|token)\s+/i;function hH(e,t,n){let r=e.replace(hB,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function h_(e){return hH(e.replace(/\$[$!]/g,"_x"),hF,hD)}let hU=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,hq=RegExp(hU.source,"g");function hK(e){return hH(e,hU,hq)}function hV(e,t){if(!e||""===t)return;e.push(t);let n=hY(t);n!==t&&e.push(n)}let hZ=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function hJ(e,t,n){let r=!1,i=e,s="",l=hZ.exec(e);if(l){let[o,a,d]=l,c=d.lastIndexOf("@");if(c>=0&&!t(hY(d.slice(0,c)))){s=`${a}${hN}${d.slice(c)}`,r=!0;let e=d.slice(0,c);hV(n,e);let t=e.indexOf(":");t>=0&&hV(n,e.slice(t+1))}else s=o;i=e.slice(o.length)}let o=i.search(/[?#]/),a=o<0?i:i.slice(0,o),d=o<0?"":i.slice(o),c=a.split("/").map(e=>hO(hY(e))?(r=!0,hV(n,e),hN):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let l=s.indexOf("=");if(l<0){let l=hY(s);return!hO(l)||t(l)?e:(r=!0,hV(n,s),`${i}${hN}`)}let o=s.slice(0,l),a=hY(s.slice(l+1));return""===a||t(a)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return hA(t,hE)}(o)&&!hO(a)?e:(r=!0,hV(n,s.slice(l+1)),`${i}${o}=${hN}`)}),{value:`${s}${c}${d}`,masked:r}}function hY(e){try{return decodeURIComponent(e)}catch{return e}}let hG=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function hX(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&hL(r[1])){let[,i,s,l]=r;return t(l)?{value:e,masked:!1}:(hV(n,l.trim()),{value:`${i}:${s}${hN}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||hG.test(e)))return;let i=!1;return{value:r.map(e=>{let r=hG.exec(e);if(!r)return e;let[,s,l]=r;if(""===l.trim()||t(l))return e;if(hL(s.slice(0,-1).trim()))return i=!0,hV(n,l.trim()),`${s}${hN}`;let o=hX(l,t,n);return i||=o.masked,`${s}${o.value}`}).join(";"),masked:i}}(e,t,n):void 0;if(i)return i;let s=/^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(e);if(s&&""!==s[2]&&hL(s[1]))return t(s[2])?{value:e,masked:!1}:(hV(n,s[2]),{value:`${s[1]}=${hN}`,masked:!0});if(/\s/.test(e)){var l,o,a;let r,i;return l=e,o=t,a=n,i=h1((r=l.split(/(\s+)/)).filter((e,t)=>t%2==0),o,!0,a),{value:r.map((e,t)=>t%2==0?i.values[t/2]:e).join(""),masked:i.masked}}if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(e))return hJ(e,t,n);if(s&&""!==s[2]){let e=hX(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return hO(e)&&!t(e)?(hV(n,e),{value:hN,masked:!0}):{value:e,masked:!1}}function hQ(e){if(hT.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return hL(t)||"auth"===hR(t).at(-1)}let h0=/^(?:bearer|basic|token)$/i;function h1(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&h0.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,hV(r,e),hN)}let l=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(l){let[,e,n]=l;if(""!==n&&hQ(e)&&!t(n))return i=!0,hV(r,n),`${e}=${hN}`;let s=hX(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=hQ(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(h0.test(e)||t&&hL(t[1]))return s=!0,e}let o=hX(e,t,r);return i||=o.masked,o.value}),masked:i}}function h2(e){let{values:t,masked:n}=h1(e,hK,!1);return{args:t,masked:n}}function h4(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function h8(e){return!e.startsWith("!")&&!h_(e)}function h3(e){return JSON.parse(e.replace(/^\uFEFF/,"").replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,e=>'"'===e[0]?e:"*"===e[1]?" ":"").replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g,(e,t)=>t??('"'===e[0]?e:"")))}let h5={"empty-input":"error","unrecognized-input":"error","invalid-json":"error","no-servers-found":"error","shell-operator":"error","shell-command-substitution":"error","shell-multiple-commands":"error","shell-unterminated-quote":"error","shell-parameter":"error","shell-expansion":"error","unsupported-url-scheme":"error","github-repo-link":"error","github-mcp-page":"error","github-page":"error","by-name-link":"error","badge-image":"error","install-link-invalid":"error","claude-desktop-import":"error","cli-unsupported":"error","cli-usage":"error","cli-unknown-option":"error","cli-option-needs-value":"error","cli-option-wrong-transport":"error","cli-invalid-pair":"error","cli-not-a-server":"error","pi-help":"error","field-required":"error","field-invalid-option":"error","field-reference-invalid":"error","sse-transport":"error","websocket-transport":"error","unsupported-transport":"error","ambiguous-command-and-url":"error","no-command-or-url":"error","zed-extension-server":"error","registry-packages-unsupported":"error","invalid-config":"error","dropped-key":"warning","variable-unsupported-here":"warning","variable-fallback-dropped":"warning","bare-dollar-literal":"warning","header-env-reference":"warning","client-secret-env-reference":"warning","shell-command-value":"warning","shell-variable":"warning","unsupported-variable":"warning","input-undefined":"warning","input-command-unsupported":"warning","timeout-clamped":"warning","timeout-dropped":"warning","timeout-unit-guessed":"warning","env-null-dropped":"warning","oauth-option-dropped":"warning","oauth-disable-unsupported":"warning","callback-url-dropped":"warning","callback-port-dropped":"warning","invalid-exposure-dropped":"warning","tool-filter-imported":"warning","transport-guessed":"warning","insecure-http":"warning","literal-secret":"warning","cli-option-ignored":"warning","cli-option-as-arg":"warning","cli-extra-arguments":"warning","mcp-remote-bridge":"warning","looks-like-pi-config":"warning","workspace-folder-relative":"warning","home-variable-translated":"warning","name-taken":"warning","escaped-value":"info","variable-translated":"info","home-translated":"info","timeout-converted":"info","env-value-stringified":"info","empty-authorization-dropped":"info","imported-disabled":"info","name-derived":"info","name-sanitized":"info","name-deduplicated":"info","command-split":"info","transport-assumed-http":"info","scheme-assumed":"info","client-secret-prompt":"info","userinfo-moved-to-header":"info"};Object.keys(h5);let h6={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},h9={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},h7={...h9,bareDollar:!0},fe={...h6,braceEnv:!0},ft=/^[A-Za-z_][A-Za-z0-9_]*$/,fn=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function fr(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function fi(e,t,n){let r=[],i=0;fn.lastIndex=0;for(let s=fn.exec(e);s;s=fn.exec(e)){let[l,o,a,d,c,u]=s,p=l;if(void 0!==o&&t.dollarBrace)p=function(e,t){let n=/^env:([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);if(n)return{kind:"env",name:n[1],from:t};let r=/^input:(.+)$/.exec(e);if(r)return{kind:"input",id:r[1],from:t};if("userHome"===e)return{kind:"home",from:t};if("workspaceFolder"===e||"workspaceRoot"===e||"CLAUDE_PROJECT_DIR"===e)return{kind:"workspace",from:t};if("workspaceFolderBasename"===e)return{kind:"workspace-basename",from:t};if("pathSeparator"===e||"/"===e)return"/";if("CLAUDE_PLUGIN_ROOT"===e||"CLAUDE_PLUGIN_DATA"===e)return{kind:"unsupported",from:t};if(ft.test(e))return{kind:"env",name:e,from:t};let i=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(e);return i?{kind:"env",name:i[1],from:t,fallback:i[2]}:/^[A-Za-z]+:/.test(e)?{kind:"unsupported",from:t}:t}(o,l);else if(void 0!==a&&t.bareDollar)p={kind:"env",name:a,from:l};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:l};else if(void 0!==c&&t.braceEnv)p="env"===c&&ft.test(u)?{kind:"env",name:u,from:l}:{kind:"unsupported",from:l};else if(void 0!==d||void 0!==c){fr(r,e.slice(i,s.index+1)),i=s.index+1,fn.lastIndex=s.index+1;continue}fr(r,e.slice(i,s.index)),"string"==typeof p?fr(r,p):r.push(p),i=s.index+l.length}return fr(r,e.slice(i)),r}function fs(e){let{atStart:t=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.replace(/\$/g,"$$$$");return t&&n.startsWith("!")?`$${n}`:n}function fl(e){return e.startsWith("!")}function fo(e){if(fl(e))return[];let t=[];for(let n=0;n<e.length;n++){if("$"!==e[n])continue;let r=e[n+1];if("$"===r||"!"===r){n++;continue}if("{"===r){let r=e.indexOf("}",n+2);if(r<0)continue;let i=e.slice(n+2,r);ft.test(i)&&!t.includes(i)&&t.push(i),n=r;continue}let i=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(n+1));i&&(t.includes(i[0])||t.push(i[0]),n+=i[0].length)}return t}let fa=/<[A-Za-z][^<>\n]{0,80}>|\{\{\s*[A-Za-z_][\w.-]*\s*\}\}|\b[Yy][Oo][Uu][Rr][_-][A-Za-z0-9_.-]*[A-Za-z0-9]|\b[A-Za-z0-9_-]{0,80}[A-Za-z0-9][_-](?:HERE|[Hh]ere)\b|\b(?:REPLACE[_-]?ME|CHANGE[_-]?ME|PLACEHOLDER)\b|\bMY_[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PAT)\b|\b(?:sk|pk|ghp|gho|github_pat|glpat|xoxb|xoxp)[_-][xX*]{4,}\b|\b[xX]{6,}\b/g,fd=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,fc=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,fu=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function fp(e){return e.join("\0")}function fh(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function ff(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function fm(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let fg=new Set(["HOME","USERPROFILE"]);class fx{constructor(e,t){this.source=e,this.rawPi=t,this.args=[],this.env=[],this.headers=[],this.oauth={},this.notes=[]}note(e,t){let n=JSON.stringify([e,t??{}]);this.notes.some(e=>JSON.stringify([e.code,e.params??{}])===n)||this.notes.push(t?{code:e,params:t}:{code:e})}}function fv(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let fb=/\$\{[^{}]*\}/g,fy=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class fw{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(fv),this.urlText=fv(e.url??[])}encode(e,t){let n,r=ff(e),i=fh(e),s=fv(t),l=[],o=!1,a=()=>l.every(e=>""===e),d=e=>{if(!r)return void l.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=fs(e,{atStart:a()});n!==e&&(o=!0),l.push(n)},c=e=>l.push(e),u=e=>l.push({field:e});if(!r&&fm(e)&&1===t.length&&"text"in t[0]&&fc.test(s)){let t="args"===e[0]?/^(?:--?[A-Za-z][A-Za-z0-9_.-]*|[A-Za-z_][A-Za-z0-9_]*)=/.exec(s)?.[0]??"":"",n=s.slice(t.length);if(fc.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,l,void 0)}let p=0;return t.forEach((l,o)=>{let h=t[o+1],f=void 0===h||"text"in h&&/^[\\/]/.test(h.text),m=(t,r,i)=>{let l=0;for(let[d,c]of function(e){let t=e.trim();if(fd.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=fu.exec(t);if(n&&fd.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];fa.lastIndex=0;for(let t=fa.exec(e);t;t=fa.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var o,a;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>l&&r(t.slice(l,d)),"url"===e[0]&&fj(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(o=e,a=h,"env"===o[0]||"headers"===o[0]?o[1]:a.replace(/^[<{\s]+|[>}\s]+$/g,"")||fh(o)),h)),l=c}l<t.length&&r(t.slice(l))};switch(l.kind){case"text":m(l.text,d,[]);break;case"pi":{var g;let e=h?(g=l.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):l.text;if(r&&a()&&fl(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(fb)].map(e=>[e.index,e.index+e[0].length]);m(e,c,t);break}case"env":r?(c(`\${${l.name}}`),void 0!==l.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:l.name,fallback:l.fallback}),l.shell?this.draft.note("shell-variable",{field:i,name:l.name}):l.from!==`\${${l.name}}`&&this.draft.note("variable-translated",{field:i,from:l.from,to:`\${${l.name}}`})):fm(e)&&a()&&fg.has(l.name)&&f?(c("~"),this.draft.note("home-translated",{field:i,from:l.from})):(u(this.field(e,"variable",l.name,l.from,void 0,l.fallback)),this.draft.note(l.shell?"shell-variable":"variable-unsupported-here",{field:i,name:l.name}));break;case"input":u(this.inputField(e,l));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:l.from,to:"${HOME}"})):fm(e)&&a()&&f?(c("~"),this.draft.note("home-translated",{field:i,from:l.from})):u(this.field(e,"home","userHome",l.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",l.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:l.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",l.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",l.from,l.from)),this.draft.note("unsupported-variable",{field:i,variable:l.from});break;case"prompt":"url"===e[0]&&fj(s,p)&&(n="uri-component"),u(this.promptField(e,l))}p+=("text"in l?l.text:l.from).length}),o&&this.draft.note("escaped-value",{field:i}),this.target(e,l,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>fp(t.path)===fp(e))||i.targets.push({path:e,parts:r,...n?{encoding:n}:{}})}return r.map(e=>"string"==typeof e?e:this.fields.get(e.field).placeholder??"").join("")}field(e,t,n,r,i,s){let l=fy.has(t)?`${t}.${n}`:fh(e);if(fy.has(t)){if(this.fields.has(l))return l}else for(let t=2;this.fields.has(l);t++)l=`${fh(e)}#${t}`;let o=this.isSecretContext(e,r)||hL(n),a="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(l,{id:l,kind:i??(o?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&a?{optional:!0}:{},targets:[]}),l}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return hL(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(h2([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&h2([t,"x"]).args[1]===hN}case"url":{var n;let e=this.urlText.indexOf(t),r=e<0?void 0:/[?&]([^=&?#]+)=[^&#]*$/.exec(this.urlText.slice(0,e))?.[1];return void 0!==r&&(n=r,hJ(`https://host.invalid/?${n}=x`,hK).masked)}default:return!1}}}function fj(e,t){let n=e.indexOf("//"),r=e.slice(n<0?0:n+2).search(/[/?#]/);return r>=0&&t>=(n<0?0:n+2)+r}function fk(e,t,n){let r=n?void 0:function(e){let t;try{t=new URL(e)}catch{return}if(""===t.username&&""===t.password)return;let n=e=>{try{return decodeURIComponent(e)}catch{return e}},r=new TextEncoder().encode(`${n(t.username)}:${n(t.password)}`),i="";for(let e of r)i+=String.fromCharCode(e);return t.username="",t.password="",{url:t.toString(),authorization:`Basic ${btoa(i)}`}}(t);if(!r){e.url=[{kind:"text",text:t}];return}e.url=[{kind:"text",text:r.url}],e.headers.push(["Authorization",[{kind:"text",text:r.authorization}]]),e.note("userinfo-moved-to-header")}let fS=/^[A-Za-z0-9_-]+$/;function fC(e,t){let n=new Set(t);if(!n.has(e))return e;for(let t=2;;t++){let r=`${e}-${t}`;if(!n.has(r))return r}}let fN=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function f$(e){let t=e.trim(),n=t.lastIndexOf("@");n>0&&(t=t.slice(0,n)),t=t.replace(/==.*$|\[.*\]$/,"");let r="",i=/^@([^/]+)\/(.+)$/.exec(t);if(i)r=i[1],t=i[2];else if(t.includes("/")){let e=t.split("/").filter(Boolean);t=e[e.length-1]??t}let s=fI(t);return s&&!fN.has(s.toLowerCase())?s:fI(r)||r||s||t}let fE=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function fI(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,fE)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let fM=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function fT(e){let t;try{t=new URL(e).hostname}catch{return""}if("localhost"===t||"127.0.0.1"===t||"[::1]"===t||"::1"===t)return"local";if(/^\d+(?:\.\d+){3}$/.test(t))return"";let n=t.split(".").filter(Boolean);n.length>1&&n.pop(),n.length>1&&/^(?:co|com|org|net|ac|gov)$/.test(n[n.length-1])&&n.pop();let r=n.filter(e=>!fM.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let fR=new Set(["-e","--env","--env-file","-v","--volume","-p","--publish","--name","--network","--net","-w","--workdir","-u","--user","--mount","--entrypoint","-l","--label","--platform","--pull","-h","--hostname","--add-host","--cpus","-m","--memory","--restart","--runtime","--cap-add","--cap-drop","--device","--dns","--ipc","--pid","--security-opt","--tmpfs","--ulimit","--log-driver","--log-opt","--gpus"]);function fA(e,t){for(let n=0;n<e.length;n++){let r=e[n];if("--"===r)return e[n+1];if(r.startsWith("-")){!r.includes("=")&&t.has(r)&&n++;continue}return r}}function fL(e){let t=e.split(/[\\/]/).filter(Boolean);for(let e=t.length-1;e>=0;e--){let n=t[e].replace(/\.[A-Za-z0-9]+$/,"");if(!fN.has(n.toLowerCase())&&"."!==n&&".."!==n)return fI(n.replace(/_/g,"-"))||n}return""}function fz(e,t){fP(e,t)&&fW(e,Math.ceil(t/1e3),t)}function fP(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function fW(e,t,n){let r=Math.min(Math.max(t,1),3600);void 0!==n&&e.note("timeout-converted",{from:n,to:r}),r!==t&&e.note("timeout-clamped",{from:t,to:r}),e.timeout=r}let fO=["codemode","deferred","direct","hidden"],fF={"codemode-deferred":"codemode"},fD=["localhost","127.0.0.1","[::1]"];function fB(e){return"string"==typeof e&&fO.includes(e)?e:"string"==typeof e&&Object.hasOwn(fF,e)?fF[e]:void 0}function fH(e){try{return new URL(e)}catch{return}}function f_(e){let t=fH(e);return void 0!==t&&"http:"===t.protocol&&fD.includes(t.hostname)&&""===t.search&&""===t.hash}function fU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fq(e){return fU(e)&&Object.values(e).every(e=>"string"==typeof e)}function fK(e,t){if(!fS.test(e))return{problem:"name",name:e};if(!fU(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:l,description:o}=t;if(void 0!==r&&!fB(r))return{problem:"exposure",value:String(r)};if(void 0!==l){if(!fU(l))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(l))if(!fB(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==o&&"string"!=typeof o)return{problem:"description"};if(void 0!==s&&("number"!=typeof s||!(s>0)))return{problem:"timeout",value:String(s)};if("sse"===n)return{problem:"sse"};if("string"==typeof t.url&&(void 0===n||"http"===n||"streamable-http"===n)){let e=fH(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!fq(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!fU(e))return{problem:"oauth"};if(void 0!==e.clientId&&"string"!=typeof e.clientId)return{problem:"oauth-client-id"};if(void 0!==e.clientSecret&&"string"!=typeof e.clientSecret)return{problem:"oauth-client-secret"};let r=e.callbackPort;if(void 0!==r&&("number"!=typeof r||!Number.isInteger(r)||r<1||r>65535))return{problem:"callback-port",value:String(r)};if(void 0!==e.callbackUrl){if("string"!=typeof e.callbackUrl||!f_(e.callbackUrl))return{problem:"callback-url",value:String(e.callbackUrl)};let t=new URL(e.callbackUrl).port;if(t&&void 0!==r&&Number(t)!==r)return{problem:"callback-port-mismatch",value:t}}if(void 0!==e.scope&&"string"!=typeof e.scope)return{problem:"oauth-scope"};if(void 0!==e.clientName&&("string"!=typeof e.clientName||!e.clientName.trim()))return{problem:"oauth-client-name"};if(void 0!==e.clientRegistration&&"dcr"!==e.clientRegistration){if("cimd"!==e.clientRegistration)return{problem:"oauth-client-registration",value:String(e.clientRegistration)};if(void 0!==e.clientId||void 0!==e.clientName)return{problem:"oauth-client-registration-client"};let t="string"==typeof e.callbackUrl?fH(e.callbackUrl):void 0;if(t&&("[::1]"===t.hostname||"/callback"!==t.pathname))return{problem:"oauth-client-registration-callback"}}if(void 0!==e.authServerMetadataUrl&&!(void 0!==(n="string"==typeof(t=e.authServerMetadataUrl)?fH(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&fD.includes(n.hostname))))return{problem:"auth-server-metadata-url",value:String(e.authServerMetadataUrl)}}(t.oauth);if(n)return n;let r=t.auth;if(void 0!==r){if(!fU(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!fD.includes(e.hostname))return{problem:"auth-url"}}return}return"string"==typeof t.command&&(void 0===n||"stdio"===n)?void 0===t.args||Array.isArray(t.args)&&t.args.every(e=>"string"==typeof e)?void 0===t.env||fq(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let fV=/[A-Za-z_]/,fZ=/[A-Za-z0-9_]/,fJ=/^[A-Za-z_][A-Za-z0-9_]*$/,fY=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),fG=new Set([..."|&;<>()"]),fX=/[0-9@*#?$!-]/,fQ={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function f0(e,t){let n=t+1;for(;" "===e[n]||" "===e[n];)n++;return"\r"===e[n]&&"\n"===e[n+1]?n+2-t:"\n"===e[n]?n+1-t:0}function f1(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class f2{constructor(e){this.input=e,this.index=0,this.words=[],this.windowsWord=!1,this.lineBreak=!1}run(){try{this.scan()}catch(e){if(e instanceof f4)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new f4(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=f1(this.input,this.index)),this.parts}endWord(){if(!this.parts)return;let e=this.parts.filter(e=>"text"!==e.type||""!==e.value),t=e.length>0?e:this.parts.slice(0,1);this.words.push({parts:t,text:t.map(e=>"text"===e.type?e.value:e.raw).join("")}),this.parts=void 0,this.windowsWord=!1}appendText(e,t){let n=this.startWord(),r=n[n.length-1];r?.type==="text"&&r.quote===t?r.value+=e:n.push({type:"text",value:e,quote:t})}scan(){let{input:e}=this;for(;this.index<e.length;){let t=e[this.index];if(" "===t||" "===t)this.endWord(),this.index++;else if("\r"===t&&"\n"===e[this.index+1])this.index++;else if("\n"===t)this.endWord(),this.words.length>0&&(this.lineBreak=!0),this.index++;else if(("\\"===t||"^"===t||"`"===t)&&f0(e,this.index)>0)this.index+=f0(e,this.index);else if("#"!==t||this.parts)"'"===t?(this.startWord(),this.singleQuoted()):'"'===t?(this.startWord(),this.doubleQuoted()):"$"===t?this.dollar("none"):"`"===t?this.fail({code:"command-substitution",syntax:"`"}):fG.has(t)?this.fail({code:"shell-operator",operator:function(e,t){let n=e.slice(t,t+2);return["||","&&",";;",">>","<<",">&","<&",">|","<(",">(","&>"].includes(n)?n:e[t]}(e,this.index)}):"\\"===t?this.backslash():(this.appendText(t,"none"),this.index++);else for(;this.index<e.length&&"\n"!==e[this.index];)this.index++}this.endWord()}backslash(){let e=this.input[this.index+1];if(this.startWord(),void 0===e||this.windowsWord||!fY.has(e)){this.appendText("\\","none"),this.index++;return}this.appendText(e,"none"),this.index+=2}singleQuoted(){let e=this.input.indexOf("'",this.index+1);e<0&&this.fail({code:"unterminated-quote",quote:"'"}),this.appendText(this.input.slice(this.index+1,e),"single"),this.index=e+1}doubleQuoted(){let{input:e}=this,t=f1(e,this.index+1);for(this.index++,this.appendText("","double");this.index<e.length;){let n=e[this.index];if('"'===n)return void this.index++;if("\\"===n){let n=e[this.index+1];"\n"===n?this.index+=2:"\r"===n&&"\n"===e[this.index+2]?this.index+=3:'"'!==n&&(t||"$"!==n&&"`"!==n&&"\\"!==n)?(this.appendText("\\","double"),this.index++):(this.appendText(n,"double"),this.index+=2)}else"$"===n?this.dollar("double"):"`"===n?this.fail({code:"command-substitution",syntax:"`"}):(this.appendText(n,"double"),this.index++)}this.fail({code:"unterminated-quote",quote:'"'})}ansiQuoted(){let{input:e}=this;this.index+=2;let t="";for(;this.index<e.length;){let n=e[this.index];if("'"===n){this.appendText(t,"ansi"),this.index++;return}if("\\"!==n){t+=n,this.index++;continue}let r=e[this.index+1];if("x"===r&&/^[0-9A-Fa-f]{1,2}/.test(e.slice(this.index+2))){let n=/^[0-9A-Fa-f]{1,2}/.exec(e.slice(this.index+2))[0];t+=String.fromCharCode(parseInt(n,16)),this.index+=2+n.length}else if(("u"===r||"U"===r)&&/^[0-9A-Fa-f]{1,8}/.test(e.slice(this.index+2))){let n=RegExp(`^[0-9A-Fa-f]{1,${"u"===r?4:8}}`).exec(e.slice(this.index+2))[0],i=parseInt(n,16);t+=i>1114111||i>=55296&&i<=57343?e.slice(this.index,this.index+2+n.length):String.fromCodePoint(i),this.index+=2+n.length}else void 0!==r&&r in fQ?(t+=fQ[r],this.index+=2):(t+="\\",this.index++)}this.fail({code:"unterminated-quote",quote:"'"})}dollar(e){let{input:t}=this,n=t[this.index+1];if("("===n&&this.fail({code:"command-substitution",syntax:"("===t[this.index+2]?"$((":"$("}),"none"===e&&"'"===n){this.startWord(),this.ansiQuoted();return}if("none"===e&&'"'===n){this.startWord(),this.index++,this.doubleQuoted();return}if("{"===n)return void this.braced(e);if(void 0!==n&&fV.test(n)){let n=this.index+1;for(;n<t.length&&fZ.test(t[n]);)n++;let r=t.slice(this.index+1,n);this.startWord().push({type:"variable",name:r,raw:`$${r}`,quote:e}),this.index=n;return}void 0!==n&&fX.test(n)&&this.fail({code:"shell-parameter",parameter:`$${n}`}),this.appendText("$",e),this.index++}braced(e){let{input:t}=this,n=t.indexOf("}",this.index+2);n<0&&this.fail({code:"unsupported-expansion",expansion:t.slice(this.index)});let r=t.slice(this.index,n+1),i=r.slice(2,-1);if(/^[0-9@*#?$!-]$/.test(i)&&this.fail({code:"shell-parameter",parameter:r}),fJ.test(i)){this.startWord().push({type:"variable",name:i,raw:r,quote:e}),this.index=n+1;return}let s=/^([A-Za-z_][A-Za-z0-9_]*):?-([\s\S]*)$/.exec(i);if(s&&!/[$`{}\\'"]/.test(s[2])){this.startWord().push({type:"variable",name:s[1],raw:r,quote:e,fallback:s[2]}),this.index=n+1;return}this.fail({code:"unsupported-expansion",expansion:r})}}class f4 extends Error{constructor(e){super(e.code),this.detail=e}}function f8(e){return new f2(e).run()}function f3(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function f5(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let f6=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function f9(e){if(f6.some(t=>t in e))return!0;let t=e.oauth;return f5(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function f7(e){if(!f5(e))return!1;let{command:t,url:n,serverUrl:r,httpUrl:i}=e;return"string"==typeof t&&""!==t||Array.isArray(t)&&"string"==typeof t[0]||f5(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function me(e){switch(e.toLowerCase().replace(/[-_]/g,"")){case"stdio":case"local":return"stdio";case"http":case"streamablehttp":case"remote":return"http";case"sse":return"sse";case"ws":case"wss":case"websocket":return"ws";default:return"unknown"}}function mt(e){try{let t=new URL(e);if(!/\/sse\/?$/.test(t.pathname))return;return t.pathname=t.pathname.replace(/\/sse\/?$/,"/mcp"),t.toString()}catch{return}}function mn(e,t){let n=t?mt(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function mr(e){return e?{server:e}:{}}function mi(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function ms(e,t,n){let r;if(!f5(t))return{note:{code:"no-command-or-url",params:mr(e)}};let i=new Set,s=e=>(i.add(e),t[e]),l=n.rawPi,o=function(e,t){switch(e.flavor){case"zed":return h6;case"opencode":return fe;case"vscode":return h9;default:return f9(t)?h7:h9}}(n,t),a=s("name"),d=e??("string"==typeof a?a:void 0),c=new fx(n.source,l),u=(e,t)=>{if(l)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),fi(e,o,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...ma(p)]));let h=s("type"),f=s("command"),m=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:mr(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?me(h):"unknown"))return{note:{code:"unsupported-transport",params:{...mr(d),type:String(h)}}};let g="string"==typeof f&&""!==f||Array.isArray(f)||f5(f),x=void 0!==m;if("sse"===r)return{note:mn(d,m)};if("ws"===r)return{note:{code:"websocket-transport",params:{...mr(d),...m?{url:m}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:mr(d)}};if(x){if(void 0!==mt(m))return{note:mn(d,m)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:mr(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...mr(d),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:mr(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let l,o=r("args"),a=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===a&&(a=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...mr(e.name),problem:"args"}};l=n[0],o=[...n.slice(1),...Array.isArray(o)?o:[]]}else if(f5(n))for(let t of(l="string"==typeof n.path?n.path:void 0,void 0===o&&(o=n.args),void 0===a&&(a=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(l=n);if(!l)return{code:"no-command-or-url",params:mr(e.name)};let d=Array.isArray(o)?[...o]:[];if(void 0!==o&&!Array.isArray(o))return{code:"invalid-config",params:{...mr(e.name),problem:"args"}};if(0===d.length&&/\s/.test(l.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(l.trim())){let t=f8(l.trim()),n=t.ok?t.words.map(f3):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:l}),l=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(l,!1),d.entries())){let r=mi(n);if(void 0===r)return{code:"invalid-config",params:{...mr(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==a){if(!f5(a))return{code:"invalid-config",params:{...mr(e.name),problem:"env"}};for(let[t,n]of Object.entries(a)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=mi(n);if(void 0===r){e.note("dropped-key",{key:`env.${t}`});continue}if("string"!=typeof n&&e.note("env-value-stringified",{name:t}),""===r&&hL(t)){e.env.push([t,[{kind:"prompt",id:`env.${t}`,reason:"empty",label:t,from:"",secret:!0}]]);continue}e.env.push([t,i(r,!0)])}}let c=r("cwd");for(let n of("string"==typeof c&&""!==c?e.cwd=i(c,!1):void 0!==c&&""!==c&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,f,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),l=i(n,!1),o=f5(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===l.length&&"text"in l[0]?fk(e,n,o):e.url=l,f5(s))for(let[t,n]of Object.entries(s)){let r=mi(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):hL(t)?e.headers.push([t,[{kind:"prompt",id:`headers.${t}`,reason:"empty",label:t,from:"",secret:!0,optional:!0}]]):e.headers.push([t,[]]);continue}e.headers.push([t,i(r,!0)])}else void 0!==s&&e.note("dropped-key",{key:"headers"});let a=r("oauth"),d=r("auth");if(!1===a?e.note("oauth-disable-unsupported"):f5(a)?ml(e,a,i):void 0!==a&&e.note("dropped-key",{key:"oauth"}),f5(d))for(let t of(ml(e,{...void 0!==d.CLIENT_ID?{clientId:d.CLIENT_ID}:{},...void 0!==d.CLIENT_SECRET?{clientSecret:d.CLIENT_SECRET}:{},...void 0!==d.scopes?{scopes:d.scopes}:{}},i,"auth."),Object.keys(d)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==d&&e.note("dropped-key",{key:"auth"});for(let n of["command","args","env","environment","cwd"])n in t&&(r(n),e.note("dropped-key",{key:n}))}(c,t,m,s,u);let v=s("timeout");if(void 0!==v)if(l)"number"==typeof v&&v>0?c.timeout=v:c.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(v)});else if(f9(t))fz(c,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?fP(c,v)&&fW(c,Math.ceil(v),void 0):!function(e,t){if(!fP(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?fW(e,Math.ceil(t/1e3),t):fW(e,Math.ceil(t),void 0)}(c,v);let b=s("enabled"),y=s("disabled");!1===b||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let w=s("exposure");if(void 0!==w){let e=fB(w);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(w)})}let j=s("toolExposure");if(void 0!==j){let e=f5(j)?Object.entries(j).map(e=>{let[t,n]=e;return[t,fB(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?c.toolExposure=Object.fromEntries(e):c.note("invalid-exposure-dropped",{value:"toolExposure"})}if(l||void 0===w&&void 0===j||c.note("looks-like-pi-config"),l){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(mo(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function ml(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"oauth.";for(let[i,s]of Object.entries(t))switch(i){case"clientId":"string"==typeof s&&""!==s&&(e.oauth.clientId=n(s,!1));break;case"clientSecret":"string"==typeof s&&""!==s&&(e.oauth.clientSecret=n(s,!0));break;case"callbackPort":"number"==typeof s&&Number.isInteger(s)&&s>=1&&s<=65535?e.oauth.callbackPort=s:e.note("callback-port-dropped",{value:String(s)});break;case"clientName":"string"==typeof s&&s.trim()?e.oauth.clientName=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"clientRegistration":"dcr"===s||"cimd"===s?e.oauth.clientRegistration=s:e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"authServerMetadataUrl":"string"==typeof s&&""!==s?e.oauth.authServerMetadataUrl=n(s,!1):e.note("oauth-option-dropped",{key:`${r}${i}`});break;case"callbackUrl":case"redirectUri":"string"==typeof s&&f_(s)?e.oauth.callbackUrl=n(s,!1):e.note("callback-url-dropped",{value:String(s)});break;case"scope":case"scopes":{let t=Array.isArray(s)?s.filter(e=>"string"==typeof e).join(" "):"string"==typeof s?s:"";t&&(e.oauth.scope=n(t,!1));break}case"enabled":!1===s&&e.note("oauth-disable-unsupported");break;default:e.note("oauth-option-dropped",{key:`${r}${i}`})}let{callbackPort:i,callbackUrl:s}=e.oauth;if(void 0!==i&&s){let t=s.map(e=>"text"in e?e.text:"").join(""),n="";try{n=new URL(t).port}catch{}n&&Number(n)!==i&&(e.note("callback-url-dropped",{value:t}),e.oauth.callbackUrl=void 0)}}function mo(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),s=r(n);if(0===i.length&&0===s.length)return;let l={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))l[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)l[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=l}function ma(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)f5(n)&&"string"==typeof n.id&&t.set(n.id,{id:n.id,..."string"==typeof n.type?{type:n.type}:{},..."string"==typeof n.description?{description:n.description}:{},...!0===n.password?{password:!0}:{},..."string"==typeof n.default?{default:n.default}:{},...Array.isArray(n.options)?{options:n.options.map(e=>f5(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function md(e,t,n,r){let i=[],s=0;for(let l of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){l.index>s&&i.push({kind:"text",text:e.slice(s,l.index)});let o=f5(t)&&f5(t[l[1]])?t[l[1]]:{};i.push(mc(`${n}${l[1]}`,l[1],l[0],o,r)),s=l.index+l[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function mc(e,t,n,r,i){let s=Array.isArray(r.choices)?r.choices.filter(e=>"string"==typeof e):[];return{kind:"prompt",id:e,reason:i,label:t,from:n,secret:!0===r.isSecret,..."string"==typeof r.description?{description:r.description}:{},..."string"==typeof r.default?{defaultValue:r.default}:{},...!0===r.isRequired?{}:{optional:"registry-header"===i},...s.length>0?{options:s}:{}}}function mu(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...fi(i,t,n)),i="")};for(let t of e)"variable"===t.type?(s(),r.push({kind:"env",name:t.name,from:t.raw,shell:!0,...void 0!==t.fallback?{fallback:t.fallback}:{}})):i+=t.value;return s(),r}function mp(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if("variable"===i.type){n+=i.raw;continue}let s=i.value.indexOf(t);if(s<0){n+=i.value;continue}n+=i.value.slice(0,s);let l=i.value.slice(s+t.length);return[n,[...l?[{...i,value:l}]:[],...e.slice(r+1)]]}}let mh=/^https?:\/\//i,mf=/^wss?:\/\//i,mm={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},mg=new Set(["pi","claude","codex","gemini"]),mx=new Set(["install","remove","uninstall","update","list","config"]);function mv(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let mb={local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},my=new Map([["-l","--local"]]),mw=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"],mj=["env","cwd"];function mk(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let l=t[s],o=l.text;if("--"===o){i.afterDashDash.push(...t.slice(s+1));break}if(void 0!==r.stopAfter&&i.positional.length>=r.stopAfter){i.positional.push(...t.slice(s));break}if(!o.startsWith("-")||"-"===o){i.positional.push(l);continue}let a=o.startsWith("--")?o.indexOf("="):-1,d=a>0?o.slice(0,a):o,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(l),i.seen.set(`as-arg:${d}`,d);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:d}}}}if(i.seen.set(c.name,d),"flag"===c.kind){i.values.set(c.name,!0);continue}let u=a>0?mS(l,a+1):void 0;if("value"===c.kind||"list"===c.kind){let n=u??t[++s];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};"value"===c.kind?i.values.set(c.name,n):i.lists.set(c.name,[...i.lists.get(c.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;s+1<t.length&&r.variadic(c.name,t[s+1]);)p.push(t[++s]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:d}}};i.lists.set(c.name,[...i.lists.get(c.name)??[],...p])}return i}function mS(e,t){let n=0,r=[];for(let i of e.parts){let e="text"===i.type?i.value.length:i.raw.length;n>=t?r.push(i):n+e>t&&"text"===i.type&&r.push({...i,value:i.value.slice(t-n)}),n+=e}return{parts:r,text:e.text.slice(t)}}let mC=/^[A-Za-z_][A-Za-z0-9_]*=/,mN=/^[^\s:]+:/;function m$(e,t,n,r){for(let i of t??[]){let t=mp(i.parts,"=");if(!t||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t[0]))return{code:"cli-invalid-pair",params:{cli:r,option:"--env",value:i.text}};e.env.push([t[0],mu(t[1],n,!0)])}}function mE(e,t,n,r){for(let i of t??[]){let t=mp(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let l=function(e){let t=e.map(e=>({...e})),n=t[0];n?.type==="text"&&(n.value=n.value.replace(/^\s+/,""));let r=t[t.length-1];return r?.type==="text"&&(r.value=r.value.replace(/\s+$/,"")),t}(t[1]);if("authorization"===s.toLowerCase()&&l.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,mu(l,n,!0)])}}function mI(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function mM(e,t,n,r,i){let s,[l,o,...a]=r;if(!l||!o)return{code:"cli-usage",params:{cli:t}};e.name=l.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=mh.test(o.text)?"http":mf.test(o.text)?"ws":"stdio")&&void 0!==mt(o.text))return mn(l.text,o.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?mn(l.text,o.text):"ws"===s?{code:"websocket-transport",params:{server:l.text,url:o.text}}:"http"===s?(e.transport="http",e.url=mu(o.parts,i,!1),a.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:a.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:l.text,type:s}}:(e.transport="stdio",e.command=mu(o.parts,i,!1),e.args=a.map(e=>mu(e.parts,i,!1)),"stdio")}let mT={"-t":{name:"transport",kind:"value"},"--transport":{name:"transport",kind:"value"},"-e":{name:"env",kind:"variadic"},"--env":{name:"env",kind:"variadic"},"-H":{name:"header",kind:"variadic"},"--header":{name:"header",kind:"variadic"},"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-id":{name:"client-id",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"},"--callback-port":{name:"callback-port",kind:"value"},"--no-browser":{name:"no-browser",kind:"flag"}};function mR(e,t){return"env"===e?mC.test(t.text):mN.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function mA(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let mL={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function mz(e){let t,n=f3(e)??e.text;try{t=h3(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return f5(t)?{value:t}:{error:{code:"no-servers-found"}}}let mP={"--env":{name:"env",kind:"list"},"--url":{name:"url",kind:"value"},"--bearer-token-env-var":{name:"bearer-token-env-var",kind:"value"},"--oauth-client-id":{name:"oauth-client-id",kind:"value"},"--oauth-resource":{name:"oauth-resource",kind:"value"},"-c":{name:"config",kind:"value"},"--config":{name:"config",kind:"value"},"--enable":{name:"enable",kind:"value"},"--disable":{name:"disable",kind:"value"}},mW={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"-t":{name:"transport",kind:"value"},"--transport":{name:"transport",kind:"value"},"--type":{name:"transport",kind:"value"},"-e":{name:"env",kind:"list"},"--env":{name:"env",kind:"list"},"-H":{name:"header",kind:"list"},"--header":{name:"header",kind:"list"},"--timeout":{name:"timeout",kind:"value"},"--trust":{name:"trust",kind:"flag"},"--description":{name:"description",kind:"value"},"--include-tools":{name:"include-tools",kind:"value"},"--includeTools":{name:"include-tools",kind:"value"},"--exclude-tools":{name:"exclude-tools",kind:"value"},"--excludeTools":{name:"exclude-tools",kind:"value"}};function mO(e){let t=new Map;for(let n of e.replace(/^\?/,"").split("&")){if(!n)continue;let e=n.indexOf("="),r=e<0?n:n.slice(0,e),i=e<0?"":n.slice(e+1);t.set(mF(r),mF(i))}return t}function mF(e){try{return decodeURIComponent(e)}catch{return e}}function mD(e){let t=e.trim();for(let e=0;e<4;e++)try{return h3(t)}catch{let e=mF(t);if(e===t)break;t=e.trim()}}function mB(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function mH(e){let t=e.get("config");if(!t)return mB("config");let n=t.trim().startsWith("{")?t:function(e){let t=e.trim().replace(/ /g,"+").replace(/-/g,"+").replace(/_/g,"/").replace(/=+$/,"");if(/^[A-Za-z0-9+/]+$/.test(t)&&t.length%4!=1){t+="=".repeat((4-t.length%4)%4);try{let e=atob(t),n=Uint8Array.from(e,e=>e.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return}}}(t),r=void 0===n?void 0:mD(n);return f5(r)?{entries:[ms(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:mB("config")}function m_(e,t,n,r){return f5(e)?{entries:[ms(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:ma(r)})],notes:[]}:mB("config")}function mU(e){return{error:{code:"by-name-link",params:{name:e}}}}function mq(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function mK(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&amp;/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[mZ(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return mB("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return mH(mO(t.search));return mB("cursor");case"vscode":case"vscode-insiders":case"code-oss":{let e=r.slice(r.indexOf(":")+1).replace(/^\/+/,""),t=/^mcp\/by-name\/([^?#]+)/.exec(e);if(t)return mU(mF(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return mU(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return m_(mD(mq(r)),"vscode-install-link");return mB(i)}case"vsweb+mcp":return m_(mD(mq(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return m_(mD(mq(r)),"copilot-app-install-link");return mB(i);case"ws":case"wss":return{entries:[{note:{code:"websocket-transport",params:{url:r}}}],notes:[]};case"http":case"https":return function(e,t,n){let r=e.hostname.toLowerCase().replace(/^www\./,""),i=e.pathname;if(("cursor.com"===r||"lmstudio.ai"===r)&&/^\/(?:[a-z]{2}(?:-[A-Za-z]{2,4})?\/)?install-mcp\/?$/.test(i))return mH(mO(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=mO(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return mK(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?m_(mD(e),"vscode-install-link",t.get("name")||void 0,mD(t.get("inputs")??"[]")):mB("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return m_(mD(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=mO(e.search).get("open");return t?mK(t,n+1):mB("open")}if(/\.(?:svg|png)$/i.test(i)&&("cursor.com"===r||"img.shields.io"===r||r.endsWith("githubusercontent.com")))return{error:{code:"badge-image"}};if("github.com"===r){let e=i.split("/").filter(Boolean);return"mcp"===e[0]&&e.length>=2?{error:{code:"github-mcp-page",params:{name:e.slice(1).join("/")}}}:"mcp"!==e[0]&&e.length>=2?{error:{code:"github-repo-link",params:{repository:`${e[0]}/${e[1]}`}}}:{error:{code:"github-page"}}}return{entries:[mZ(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let mV=new Set(["localhost","127.0.0.1","[::1]"]);function mZ(e,t){let n=fT(t)||void 0;if(void 0!==mt(t))return{note:mn(n,t)};let r=new fx("url",!1);return r.transport="http",fk(r,t,!1),e?.protocol!=="http:"||mV.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let mJ=/[\u200B-\u200D\u2060\uFEFF]/g,mY=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,mG={"unterminated-quote":"shell-unterminated-quote","shell-operator":"shell-operator","command-substitution":"shell-command-substitution","multiple-commands":"shell-multiple-commands","shell-parameter":"shell-parameter","unsupported-expansion":"shell-expansion"};function mX(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>fp(e.path))))}function mQ(e){var t;let n,r,i,s,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(n=e.replace(mJ,"").replace(/\u00A0/g," ").trim(),(r=/```[^\n]*\n([\s\S]*?)(?:```|$)/.exec(n))?n=r[1].trim():/^`[^`\n]+`$/.test(n)&&(n=n.slice(1,-1).trim()),(i=n.startsWith("[")?/\]\(([^()\s]+)\)\s*$/.exec(n):null)&&(n=i[1]),/^<\S+>$/.test(n)&&(n=n.slice(1,-1)),n);if(!o)return{ok:!1,notes:[{code:"empty-input"}]};if(o.startsWith("{")||o.startsWith("[")||/^"[^"\n]+"\s*:/.test(o))s=function(e,t){let n;try{n=h3(e)}catch(t){try{n=h3(`{${e.replace(/,\s*$/,"")}}`)}catch{return{error:{code:"invalid-json",params:{detail:t instanceof Error?t.message:String(t)}}}}}return function(e,t){let n=[],r=(e,t)=>Object.entries(e).map(e=>{let[n,r]=e;return ms(n,r,t)});if(Array.isArray(e)){let r=e.filter(f7);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>ms(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!f5(e))return{error:{code:"no-servers-found"}};let i=f5(e.server)&&(Array.isArray(e.server.remotes)||Array.isArray(e.server.packages))?e.server:Array.isArray(e.remotes)||Array.isArray(e.packages)?e:void 0;if(i)return{entries:function(e){let t="string"==typeof e.name?e.name:"",n=t?f$(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(f5):[],i=r.filter(e=>"string"==typeof e.type&&"http"===me(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:mn(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:mr(n)}}]}return i.map(e=>{let r=new fx("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=md(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(f5):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,md(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[mc(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(f5(e.mcpServers))return"boolean"!=typeof e.autoEnableCodemode||t||n.push({code:"looks-like-pi-config"}),{entries:r(e.mcpServers,{source:"mcp-servers-json",flavor:"mcp-servers",rawPi:t}),notes:n};if(f5(e.servers)){let t=ma(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(f5(e.mcp)){let t=e.mcp;if(f5(t.servers)){let e=ma(t.inputs);return{entries:r(t.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:e}),notes:n}}return{entries:r(t,{source:"opencode-json",flavor:"opencode",rawPi:!1}),notes:n}}if(f5(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return f5(r)&&("extension"===r.source||!f7(r))?{note:{code:"zed-extension-server",params:{server:n}}}:ms(n,f5(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(f7(e))return{entries:[ms(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(f5)&&s.some(f7)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(o,!0===l.rawPi);else if(mY.test(o)){if(!("error"in(s=mK(`http://${o}`))))for(let e of s.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${o}`})}else{let e;s=!/\s/.test(o)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(o)?mK(o):(e=f8(o.replace(/^(?:\$|%|>|❯|PS [^\n>]*>)[ \t]+/,"").replace(/[\u201C\u201D\u201E\u201F\u2033]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032]/g,"'").replace(/(^|\s)[\u2013\u2014](?=\S)/g,"$1--").replace(/(^|\s)[\u2013\u2014](?=\s|$)/g,"$1--"))).ok?0===e.words.length?{error:{code:"empty-input"}}:function(e){var t;let n=0,r=(t=e[0],(t?.text.split(/[\\/]/).pop()??"").replace(/\.(?:cmd|exe|ps1)$/i,"").toLowerCase());if(["npx","bunx","pnpx"].includes(r)){let t=1;for(;e[t]?.text.startsWith("-");)t++;let i=e[t]?.text.replace(/^(@?[^@]+)@.*$/,"$1");i&&mm[i]&&e[t+1]?.text==="mcp"&&(n=t,r=mm[i])}let i=e.slice(n+1);if(i[0]?.text==="mcp"&&i.length>=2){let e=i[1].text,t=i.slice(2);if("pi"===r&&"add"===e)return mv(function(e,t){if(t.some(e=>"--help"===e.text||"-h"===e.text))return{error:{code:"pi-help"}};let n=[],r=new Map,i=new Map;for(let t=0;t<e.length;t++){let s=my.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let l=s.slice(2),o=mb[l];if(!o)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===o){r.set(l,!0);continue}let a=e[++t];if(void 0===a)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===o?i.set(l,[...i.get(l)??[],a]):r.set(l,a)}let[s,...l]=n,o=r.get("url");if(!s||""===s.text||void 0===o==(0===l.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let a=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===o?mw:mj).find(e=>r.has(e)||i.has(e));if(d)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${d}`,transport:void 0===o?"stdio":"http"}}};let c=new fx("pi-mcp-add",!0);c.name=s.text,c.scopeHint=r.has("local")?"project":"global";let u=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"=",n=[];for(let r of i.get(e)??[]){let i=mp(r.parts,t);if(!i||""===i[0])return{error:{code:"cli-invalid-pair",params:{cli:"pi",option:`--${e}`,value:r.text}}};let s=n.findIndex(e=>{let[t]=e;return t===i[0]});s>=0?n[s]=i:n.push(i)}return n},p={};if(void 0!==o&&!0!==o){c.transport="http",c.url=mu(o.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,mu(n,"pi",!0)]);let t=a("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer \${${t.text}}`}]],n=c.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?c.headers[n]=e:c.headers.push(e)}let n=a("oauth-client-id"),r=a("oauth-client-secret"),i=a("oauth-callback-port"),s=a("oauth-client-name");n&&(c.oauth.clientId=mu(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=mu(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=mu(s.parts,"pi",!1)),p.url=o.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":o.text,(i||s)&&(p.oauth={...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{}})}else{c.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)c.env.push([t,mu(n,"pi",!0)]);let[t,...n]=l;c.command=mu(t.parts,"pi",!1),c.args=n.map(e=>mu(e.parts,"pi",!1));let r=a("cwd");r&&(c.cwd=mu(r.parts,"pi",!1)),p.command=t.text}let h=a("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=fB(h.text)??h.text);let f=a("description");void 0!==f&&(p.description=f.text,c.description=f.text);let m=fK("server",p);return m?{note:{code:"invalid-config",params:{server:s.text,...m}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return mv(function(e){let t=mk("claude",e,mT,{asArgAfter:2,variadic:mR});if("error"in t)return{error:t.error};let n=new fx("claude-mcp-add",!1),r=mM(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],h9);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};for(let[e,r]of t.seen)e.startsWith("as-arg:")&&n.note("cli-option-as-arg",{cli:"claude",option:r});if(n.scopeHint=mI(t.values.get("scope")),"http"===r){var i,s;let e;t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"claude",option:"--env",transport:"http"});let r=mE(n,t.lists.get("header"),h9,"claude");if(r)return{error:r};let l=t.values.get("client-id");l&&!0!==l&&(n.oauth.clientId=mu(l.parts,h9,!1)),t.values.has("client-secret")&&mA(n);let o=t.values.get("callback-port");o&&!0!==o&&(i=n,Number.isInteger(e=Number(s=o.text))&&e>=1&&e<=65535?i.oauth.callbackPort=e:i.note("callback-port-dropped",{value:s}))}else{for(let e of["header","client-id","client-secret","callback-port"])(t.lists.has(e)||t.values.has(e))&&n.note("cli-option-wrong-transport",{cli:"claude",option:t.seen.get(e)??`--${e}`,transport:"stdio"});let e=m$(n,t.lists.get("env"),h9,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return mv(function(e){let t=mk("claude",e,mL,{asArgAfter:1/0});if("error"in t)return{error:t.error};let[n,r,...i]=[...t.positional,...t.afterDashDash];if(!n||!r||i.length>0)return{error:{code:"cli-usage",params:{cli:"claude"}}};let s=mz(r);if("error"in s)return s;let l=ms(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in l||(l.draft.scopeHint=mI(t.values.get("scope")),t.values.has("client-secret")&&"http"===l.draft.transport&&!l.draft.oauth.clientSecret&&mA(l.draft)),l}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return mv(function(e){let t=mk("codex",e,mP,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,l=n.length>0?n:s,o=t.values.get("url");if(!i||void 0===o==(0===l.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let a=new fx("codex-mcp-add",!1);for(let e of(a.name=i.text,["config","enable","disable"]))t.values.has(e)&&a.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&a.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==o&&!0!==o){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==mt(o.text))return{note:mn(i.text,o.text)};a.transport="http",a.url=mu(o.parts,h6,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&a.headers.push(["Authorization",[{kind:"text",text:"Bearer "},{kind:"env",name:e.text,from:`\${${e.text}}`}]]);let n=t.values.get("oauth-client-id");n&&!0!==n&&(a.oauth.clientId=mu(n.parts,h6,!1))}else{for(let e of["bearer-token-env-var","oauth-client-id","oauth-resource"])if(t.values.has(e))return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:`--${e}`,transport:"stdio"}}};a.transport="stdio";let e=m$(a,r,h6,"codex");if(e)return{error:e};a.command=mu(l[0].parts,h6,!1),a.args=l.slice(1).map(e=>mu(e.parts,h6,!1))}return{draft:a}}(t));if("gemini"===r&&"add"===e)return mv(function(e){let t=mk("gemini",e,mW,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new fx("gemini-mcp-add",!1),r=mM(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],h7);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=mI(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=mE(n,t.lists.get("header"),h7,"gemini");if(e)return{error:e}}else{t.lists.has("header")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--header",transport:"stdio"});let e=m$(n,t.lists.get("env"),h7,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&fz(n,Number(i.text)),["trust","description"]))t.values.has(e)&&n.note("cli-option-ignored",{cli:"gemini",option:`--${e}`});let s=e=>{let n=t.values.get(e);return n&&!0!==n?n.text.split(",").map(e=>e.trim()).filter(Boolean):void 0};return mo(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(mg.has(r)&&!e.startsWith("-")&&("claude"!==r||"serve"!==e))return{error:{code:"cli-not-a-server",params:{cli:r,command:`mcp ${e}`}}}}return"pi"===r&&i[0]&&mx.has(i[0].text)?{error:{code:"cli-not-a-server",params:{cli:r,command:i[0].text}}}:["code","code-insiders","codium","cursor"].includes(r)&&e.some(e=>"--add-mcp"===e.text||e.text.startsWith("--add-mcp="))?function(e){let t=[];for(let n=0;n<e.length;n++){let r,i=e[n].text;if("--add-mcp"===i)r=e[++n];else{if(!i.startsWith("--add-mcp="))continue;r=mS(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=mz(r);if("error"in s)return s;t.push(ms(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):mv(function(e){let t=new fx("command-line",!1);t.transport="stdio";let n=0,r=()=>{for(;n<e.length;n++){let r=function(e){let[t,...n]=e.parts;if(t?.type!=="text"||"none"!==t.quote)return;let r=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(t.value);if(!r)return;let i=t.value.slice(r[0].length);return{name:r[1],value:[...i?[{...t,value:i}]:[],...n]}}(e[n]);if(!r)break;t.env.push([r.name,mu(r.value,h6,!0)])}};if(r(),e[n]?.text==="env"){if(n++,e[n]?.text.startsWith("-"))return{error:{code:"cli-unknown-option",params:{cli:"env",option:e[n].text}}};r()}let i=e[n];if(!i)return{error:{code:"no-command-or-url"}};t.command=mu(i.parts,h6,!1),t.args=e.slice(n+1).map(e=>mu(e.parts,h6,!1));let s=e.slice(n+1).map(e=>e.text),l=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>mh.test(e)):void 0;return l&&t.note("mcp-remote-bridge",{url:l}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:mG[t],params:n}:{code:mG[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let a=[...s.notes],d=[],c=[...l.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){a.push(e.note);continue}let n=function(e){let t,n=new fw(e);if("stdio"===e.transport&&e.command&&""!==fv(e.command)){let r=n.encode(["command"],e.command),i=e.args.map((e,t)=>n.encode(["args",t],e)),s={};for(let[t,r]of e.env)s[t]=n.encode(["env",t],r);t={command:r,...i.length>0?{args:i}:{},...Object.keys(s).length>0?{env:s}:{},...e.cwd?{cwd:n.encode(["cwd"],e.cwd)}:{}}}else{if("http"!==e.transport||!e.url||""===fv(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:l,clientSecret:o,callbackPort:a,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;l&&(s.clientId=n.encode(["oauth","clientId"],l)),o&&(s.clientSecret=n.encode(["oauth","clientSecret"],o)),void 0!==a&&(s.callbackPort=a),d&&(s.clientName=n.encode(["oauth","clientName"],d)),c&&(s.clientRegistration=c),u&&(s.callbackUrl=n.encode(["oauth","callbackUrl"],u)),p&&(s.scope=n.encode(["oauth","scope"],p)),h&&(s.authServerMetadataUrl=n.encode(["oauth","authServerMetadataUrl"],h)),t={url:r,...Object.keys(i).length>0?{headers:i}:{},...Object.keys(s).length>0?{oauth:s}:{}}}return void 0!==e.exposure&&(t.exposure=e.exposure),void 0!==e.toolExposure&&(t.toolExposure=e.toolExposure),!1===e.enabled&&(t.enabled=!1),void 0!==e.timeout&&(t.timeout=e.timeout),void 0!==e.description&&(t.description=e.description),{server:{name:e.name??"",...void 0!==e.originalName?{originalName:e.originalName}:{},config:t,fields:[...n.fields.values()],notes:e.notes,source:e.source,rawPi:e.rawPi,...e.scopeHint?{scopeHint:e.scopeHint}:{}}}}(e.draft);if("note"in n){a.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return fT(e.url);let t=e.args??[],n=t.some(e=>/^mcp-remote(?:@|$)/.test(e))?t.find(e=>/^https?:\/\//i.test(e)):void 0;return n&&fT(n)||function(e,t){let n=e.split(/[\\/]/).pop()?.replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase()??"";switch(n){case"npx":case"bunx":case"pnpx":{let e=fA(t,new Set(["-p","--package","-c","--call"]));return e?f$(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?fA(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?f$(n):""}case"uvx":case"pipx":{let e=fA("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?f$(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?fA(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?fL(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?fA(t.slice(e+1),fR):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return fI(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return f$(t[e+1].replace(/_/g,"-"));let n=fA(t,new Set(["-X","-W"]));return n?fL(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=fA("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?fL(e):""}default:return fI(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let l=(t=i,fS.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";l!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:l}}));let o=fC(l,s?[...c,...u]:u);o!==l&&(r.notes.push({code:"name-deduplicated",params:{original:l,name:o}}),l=o),!s&&c.includes(l)&&r.notes.push({code:"name-taken",params:{name:l,suggestedName:fC(l,[...c,...u])}}),r.name=l;let p=fK(l,function(e){let t=mX(e),n=JSON.parse(JSON.stringify(e.config));t.has(fp(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(fp(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){a.push({code:"invalid-config",params:{server:l,...p}});continue}!function(e){let t=mX(e);for(let n of m6(e.config))t.has(fp(n))||e.notes.push({code:"literal-secret",params:{field:fh(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=fo(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=fo(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(l),d.push(r)}return 0===d.length?{ok:!1,notes:a.length>0?a:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:a}}let m0=/^[A-Za-z_][A-Za-z0-9_]*$/;function m1(e,t,n){let[r,i]=t;if("command"===r||"url"===r||"cwd"===r){void 0!==n&&(e[r]=n);return}if("args"===r){e.args[i]=n??"";return}let s={...e[r]??{}};void 0===n?delete s[i]:s[i]=n,0===Object.keys(s).length?delete e[r]:e[r]=s}function m2(e){let t=mX(e);return m6(e.config).filter(e=>ff(e)&&!t.has(fp(e)))}function m4(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let m8=/^(?:bearer|basic|token)\s+/i;function m3(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],l=new Map(m2(e).map(e=>[fh(e),e])),o=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=l.get(e);r?m0.test(n)?o.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:m4(t)}}):s.push({code:"field-reference-invalid",params:{field:e,problem:"target"}})}for(let n of e.fields){let e=t[n.id];if("object"==typeof e&&null!==e){let t=e.reference,r="string"==typeof t?t.trim():"";m0.test(r)?"select"!==n.kind&&n.targets.every(e=>ff(e.path)&&void 0===e.encoding)?i.set(n.id,{reference:r}):s.push({code:"field-reference-invalid",params:{field:n.id,problem:"target"}}):s.push({code:"field-reference-invalid",params:{field:n.id,problem:m4(t)}});continue}let r=("string"==typeof e?e:n.defaultValue??"").trim();""===r?n.optional?i.set(n.id,void 0):s.push({code:"field-required",params:{field:n.id}}):"select"===n.kind&&n.options&&!n.options.includes(r)?s.push({code:"field-invalid-option",params:{field:n.id}}):i.set(n.id,{text:r})}if(s.length>0)return{ok:!1,notes:s};let a=new Set,d=new Set;for(let t of e.fields)for(let e of t.targets){let n=i.get(t.id);"password"===t.kind&&void 0!==n&&"text"in n&&a.add(fh(e.path));let s=fp(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){m1(r,e.path,void 0);continue}let l="";for(let t of e.parts){var c,u,p,h;l+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===l,h=e.encoding,"reference"in c?`\${${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):ff(u)?fs(c.text,{atStart:p}):c.text)}m1(r,e.path,l)}for(let[e,t]of o){let n=function(e,t){let[n,r]=t,i=e[n];return void 0===r||"object"!=typeof i||null===i?void 0===r?i:void 0:i[r]}(r,e),i="headers"===e[0]&&"string"==typeof n?n.match(m8)?.[0]??"":"";m1(r,e,`${i}\${${t}}`)}for(let e of m6(r))a.add(fh(e));return{ok:!0,config:r,secretPaths:[...a]}}let m5=["command","args","env","cwd","url","headers","oauth"];function m6(e){let t=[];for(let n of function(e){if(!h4(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(h4(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&h8(i)&&""!==i&&(hL(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||hX(i,h_).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=h4(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&h8(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&hJ(e.url,hK).masked&&t.push({kind:"url"}),"string"==typeof e.command&&hX(e.command,hK).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&h2(e.args.filter(e=>"string"==typeof e)).masked&&t.push({kind:"args"}),t}(e))switch(n.kind){case"env":t.push(["env",n.name]);break;case"header":t.push(["headers",n.name]);break;case"oauth-client-secret":t.push(["oauth","clientSecret"]);break;case"url":t.push(["url"]);break;case"command":t.push(["command"]);break;case"args":{let n="args"in e&&Array.isArray(e.args)?e.args.map(e=>"string"==typeof e?e:""):[];h2(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>m5.indexOf(e[0])-m5.indexOf(t[0]))}let m9="PI_WEB_PASSWORD";function m7(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ge(e){return m7(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function gt(e){if(!m7(e))return[];if(!("url"in e))return ge(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=ge(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=m7(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let gn={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function gr(e,t,n){let r=mQ(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,l="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,l])}function gi(e,t){let n={...e,...t},r=gr(e.text,e.rawPi,e.server);if(void 0!==r&&r===gr(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function gs(e){return h5[e.code]??"warning"}function gl(e,t){let n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=e.params??{},s={};for(let[e,t]of Object.entries(i))s[e]="string"==typeof t?py(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=py(e.label))}"invalid-config"===e.code&&(s.problem=t("tool-exposure"===(n=String(i.problem??"no-command-or-url"))&&void 0!==i.tool?"mcp.importProblem.tool-exposure.tool":"args"===n&&void 0!==i.index?"mcp.importProblem.args.index":`mcp.importProblem.${n}`,s)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(s.transport=t(`mcp.transport.${i.transport}`));let l=t(function(e){let t=e.params??{};switch(e.code){case"field-reference-invalid":return`mcp.importNote.field-reference-invalid.${"target"===t.problem||"missing"===t.problem?t.problem:"name"}`;case"sse-transport":return void 0===t.suggestedUrl?"mcp.importNote.sse-transport":"mcp.importNote.sse-transport.suggested";case"timeout-unit-guessed":return`mcp.importNote.timeout-unit-guessed.${"milliseconds"===t.unit?"milliseconds":"seconds"}`;case"tool-filter-imported":return`mcp.importNote.tool-filter-imported.${"exclude"===t.mode?"exclude":"include"}`;default:return`mcp.importNote.${e.code}`}}(e),s);return"string"==typeof s.server?t("mcp.importNote.forServer",{server:s.server,note:l}):l}let go={empty:"mcp.importField.reason.empty",input:"mcp.importField.reason.input",variable:"mcp.importField.reason.variable",home:"mcp.importField.reason.home","workspace-basename":"mcp.importField.reason.workspace-basename","unsupported-variable":"mcp.importField.reason.unsupported-variable","client-secret":"mcp.importField.reason.client-secret","registry-header":"mcp.importField.reason.registry-header","registry-variable":"mcp.importField.reason.registry-variable"},ga={url:"mcp.add.source.url","command-line":"mcp.add.source.command-line","pi-mcp-add":"mcp.add.source.pi-mcp-add","claude-mcp-add":"mcp.add.source.claude-mcp-add","claude-mcp-add-json":"mcp.add.source.claude-mcp-add-json","codex-mcp-add":"mcp.add.source.codex-mcp-add","gemini-mcp-add":"mcp.add.source.gemini-mcp-add","vscode-add-mcp":"mcp.add.source.vscode-add-mcp","mcp-servers-json":"mcp.add.source.mcp-servers-json","vscode-json":"mcp.add.source.vscode-json","zed-json":"mcp.add.source.zed-json","opencode-json":"mcp.add.source.opencode-json","server-object":"mcp.add.source.server-object","server-map":"mcp.add.source.server-map","registry-server-json":"mcp.add.source.registry-server-json","cursor-install-link":"mcp.add.source.cursor-install-link","vscode-install-link":"mcp.add.source.vscode-install-link","visual-studio-install-link":"mcp.add.source.visual-studio-install-link","copilot-app-install-link":"mcp.add.source.copilot-app-install-link"},gd=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),gc=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),gu=[{source:"url",text:"https://mcp.example.com/mcp"},{source:"command-line",text:"npx -y @modelcontextprotocol/server-everything"},{source:"pi-mcp-add",text:"pi mcp add docs --url https://mcp.example.com/mcp"},{source:"claude-mcp-add",text:"claude mcp add --transport http docs https://mcp.example.com/mcp"},{source:"claude-mcp-add-json",text:'claude mcp add-json docs \'{"type":"http","url":"https://mcp.example.com/mcp"}\''},{source:"codex-mcp-add",text:"codex mcp add fetch -- uvx mcp-server-fetch"},{source:"gemini-mcp-add",text:"gemini mcp add --transport http docs https://mcp.example.com/mcp"},{source:"vscode-add-mcp",text:`code --add-mcp '${gc}'`},{source:"mcp-servers-json",text:'{ "mcpServers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } }'},{source:"vscode-json",text:'{ "servers": { "docs": { "type": "http", "url": "https://mcp.example.com/mcp" } } }'},{source:"zed-json",text:'{ "context_servers": { "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } } }'},{source:"opencode-json",text:'{ "mcp": { "docs": { "type": "remote", "url": "https://mcp.example.com/mcp" } } }'},{source:"server-object",text:'{ "type": "http", "url": "https://mcp.example.com/mcp" }'},{source:"server-map",text:'{ "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] } }'},{source:"registry-server-json",text:'{ "name": "com.example/docs", "version": "1.0.0", "remotes": [{ "type": "streamable-http", "url": "https://mcp.example.com/mcp" }] }'},{source:"cursor-install-link",text:`cursor://anysphere.cursor-deeplink/mcp/install?name=fetch&config=${btoa(gd)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(gc)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(gc)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(gc)}`}];function gp(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!(!r&&e.targets.every(e=>{let{parts:t}=e;return 1===t.length})))return[...new Set(e.targets.map(r=>{let{parts:i}=r;return i.map(r=>"string"==typeof r?py(r):r.field===e.id?n:`‹${py(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function gh(e){return"select"!==e.kind&&e.targets.every(e=>ff(e.path)&&void 0===e.encoding)}let gf=/^[A-Za-z_][A-Za-z0-9_]*$/;function gm(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];let r=t.map(e=>e.replace(/[^A-Za-z0-9]+/g,"_")).join("_").replace(/_+/g,"_").replace(/^_|_$/g,"").toUpperCase();return gf.test(r)?r:void 0}let gg=/^(?:proxy-)?authorization$/i;function gx(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return gf.test(t)?t:gm(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return gm(t,...n)??gm(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(gg.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===m9?void 0:n}function gv(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function gb(e,t){let n=e;for(let e of t)n=n.split(e).join(hN);return{text:n,masked:n!==e}}function gy(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function gw(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(pY);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function gj(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function gk(e,t,n){return{action:"add",text:e.text,values:t.values,...Object.keys(t.secretReferences).length>0?{secretReferences:{...t.secretReferences}}:{},server:t.server&&t.parsed.ok?t.parsed.servers.indexOf(t.server):0,name:t.name,scope:t.scope,rawPi:e.rawPi,...t.trustFolder?{trustFolder:!0}:{},...n&&n.length>0?{confirmHostEnv:[...n]}:{}}}function gS(e,t,n){switch(e.kind){case"trust-too-broad":return t(gN[e.breadth.kind],{path:n(e.breadth.path)});case"secret":return t(e.fixed?"mcp.add.projectBlocked.secretFixed":"mcp.add.projectBlocked.secret",{fields:e.fields.join(", ")});case"file-problem":return t("mcp.add.projectBlocked.file-problem",{path:n(e.path),reason:t(`mcp.fileProblem.${e.reason}`)});default:return t(gC[e.kind])}}let gC={"no-project":"mcp.add.projectBlocked.no-project","project-not-listed":"mcp.add.projectBlocked.project-not-listed","trust-unreadable":"mcp.add.projectBlocked.trust-unreadable","project-untrusted":"mcp.add.projectBlocked.project-untrusted","untrusted-decision":"mcp.add.projectBlocked.untrusted-decision","folder-not-fresh":"mcp.add.projectBlocked.folder-not-fresh"},gN={home:"mcp.add.projectBlocked.trust-too-broad.home",root:"mcp.add.projectBlocked.trust-too-broad.root","contains-home":"mcp.add.projectBlocked.trust-too-broad.contains-home","contains-agent-dir":"mcp.add.projectBlocked.trust-too-broad.contains-agent-dir","contains-folder":"mcp.add.projectBlocked.trust-too-broad.contains-folder","contains-project":"mcp.add.projectBlocked.trust-too-broad.contains-project","too-many-folders":"mcp.add.projectBlocked.trust-too-broad.too-many-folders"};function g$(e){return py(ey(e))}function gE(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let gI=[{href:"https://glama.ai/mcp/servers",label:"glama.ai"},{href:"https://smithery.ai/servers",label:"smithery.ai"},{href:"https://mcp.so/",label:"mcp.so"},{href:"https://registry.modelcontextprotocol.io/",label:"MCP Registry"},{href:"https://github.com/mcp",label:"github.com/mcp"}],gM=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function gT(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,e0.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},l=[...t].sort((e,t)=>s[gs(e)]-s[gs(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:l.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${gs(e)}`,children:gl(e,i,n)},`${t}\0${e.code}`))})}let gR={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function gA(e){let{data:t,cwd:n,draft:s,busy:l,controlsBusy:o,failure:a,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,e0.s)(),h=(0,i.useId)(),f=(0,i.useId)(),m=(0,i.useMemo)(()=>(function e(t,n,r){let i,s=function(e,t){let n=e=>({kind:"blocked",block:e});if(!t)return n({kind:"no-project"});let r=e.project;if(!r)return n({kind:"project-not-listed"});let i=r.trust;if(!i||void 0!==i.decisionError)return n({kind:"trust-unreadable"});if(!0===i.decision)return{kind:"write"};if(!1===i.decision)return n({kind:"untrusted-decision"});if(i.requiresTrust)return n({kind:"project-untrusted",trustable:p0(r)});let s=r.trustFolder;return s?s.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===s.reason?{kind:"trust-too-broad",breadth:s.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),l=e=>mQ(t.text,{rawPi:t.rawPi,takenNames:gj(n,e)}),o=l(t.scope??"global"),a=o.ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0,d=t.scope??(a?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(a=(o=l(d)).ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0);let c={parsed:o,name:t.name??"",scope:d,projectMode:s,..."blocked"===s.kind?{projectBlock:s.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=hc(n.mcp);if(!a)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??a.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&gh(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(a,t),f=m2(a).map(fh),m=Object.fromEntries(f.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=m3(a,h,m),x={};if(!g.ok)for(let e of g.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let v=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=gf.test(e.reference.trim())?e:{reference:"VALUE"}:void 0!==e&&""!==e.trim()?r[n.id]=e:void 0!==n.defaultValue?r[n.id]=n.defaultValue:n.optional?r[n.id]=void 0:r[n.id]="select"===n.kind?n.options?.[0]??"x":"x"}let i=m3(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,gf.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(a,h,m),b=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,l={source:e.source,commandFields:gt(r).filter(e=>{let{value:t}=e;return fl(t)}).map(gy),variableReferences:gt(r).map(e=>({...gy(e),variables:fo(e.value)})).filter(e=>{let{variables:t}=e;return t.length>0}),...r.exposure?{exposure:r.exposure}:{},enabled:s,unfilled:!n?.ok&&e.fields.length>0};if("url"in r){let e=gb(r.url,i);return{...l,transport:"http",target:py(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let o=gb(pk(r.command,r.args??[]),i);return{...l,transport:"stdio",target:o.text,...void 0!==r.cwd?{cwd:py(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:o.masked}}(a,h,g),y=g.ok?fK(p,g.config):void 0,w="blocked"===s.kind?s.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(gv)}:gw("project",n),j=gj(n,d),k=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(fS.test(p))if(j.includes(p))i={kind:"name-taken",name:p,suggestedName:fC(p,j),...k?{path:k.path}:{}};else if(g.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:b.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of gt(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(m9):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===m9))return r}(g.config,{isCommandConfigValue:fl,getConfigValueEnvVarNames:fo}))i={kind:"web-password"};else if("project"===d&&w)i={kind:"scope",block:w};else{let e=gw(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return a.fields.find(e=>e.id===t)?.label??t},t=g.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(g.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&w?e({...t,scope:"global"},n,r):{parsed:o,server:a,name:p,scope:d,projectMode:s,...w?{projectBlock:w}:{},values:h,pasteSecrets:f,secretReferences:m,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),g=(0,i.useMemo)(()=>(function(e){let t=mQ(e,{rawPi:!0});if(!t.ok)return!1;let n=mQ(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:w}=m,j=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!m.pasteSecrets.includes(String(e.params?.field))):[],k=void 0!==s.name&&s.name!==v?.name?[]:j.filter(e=>gM.has(e.code)),S=j.filter(e=>!gM.has(e.code)),C=!l&&!o&&void 0===w,N=()=>{C&&c(gk(s,m))},$=e=>d({...s,...e}),E=t.files.find(e=>e.scope===m.scope)?.path??("project"===m.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),I=w&&(""!==s.text.trim()||"mcp-off"===w.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:py(e.name),path:e.path?g$(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(py).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(py).join(", ")});case"config-invalid":return gl(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return gS(e.block,t,g$)}}(w,p,v?.fields):void 0,M=y?.kind==="project-untrusted"&&y.trustable&&u,T=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,r.jsxs)(cJ,{title:p("mcp.add.title"),catalogs:gI,target:(0,r.jsxs)(cV,{value:m.scope,label:p("config.saveTo"),options:[{value:"global",label:gE("global",p)},{value:"project",label:gE("project",p),disabled:void 0!==y&&"project"!==m.scope}],path:g$(E),disabledReason:y?gS(y,p,g$):null,onChange:e=>$({scope:e}),children:[M&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),m.trustFolder&&"trust-and-write"===m.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:g$(m.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(gi(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?gu.map(e=>{let{source:t,text:n}=e;return{label:p(ga[t]),value:n}}):[],multiline:!0,children:[g&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(gi(s,{rawPi:e.target.checked}))}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:p("mcp.add.rawPi")}),s.rawPi&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.rawPiOn")})]})]}),!x.ok&&""!==s.text.trim()&&(0,r.jsx)(gT,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(cH,{label:p("mcp.add.serverLabel"),children:[(0,r.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>$({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:py(e.name)},`${t}\0${e.name}`))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cH,{label:p("config.name"),children:(0,r.jsx)("input",{id:f,className:"mcp-add-input","aria-label":p("config.name"),value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>$({name:e.target.value})})}),(0,r.jsx)(gT,{notes:k,fields:v.fields}),w?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{size:"small",onClick:()=>$({name:w.suggestedName}),children:p("mcp.add.useName",{name:py(w.suggestedName)})})})]}),v&&b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cB,{children:p("mcp.add.preview")}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(cU,{label:p("mcp.add.readAs"),children:p(ga[b.source])}),(0,r.jsx)(cU,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,r.jsx)(cU,{label:"http"===b.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:b.target}),"stdio"===b.transport&&void 0!==b.cwd&&(0,r.jsx)(cU,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),T.length>0&&(0,r.jsx)(cU,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(gL,{names:T})}),b.commandFields.length>0&&(0,r.jsx)(cU,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:b.commandFields.map(e=>{let t=pN(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),b.variableReferences.length>0&&(0,r.jsx)(cU,{label:p("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===b.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:pI(b.variableReferences).map(e=>{let{variable:t,field:n}=e,i=pN(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:py(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[b.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),b.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(gT,{notes:S,fields:v.fields}),v.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cB,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,r.jsx)(gz,{field:e,fields:v.fields,draft:s,suggestedName:(t=m.name,(n=e.targets[0])?gx(fh(n.path),t):void 0),problem:m.fieldProblems[e.id],onDraftChange:d},e.id)})]}),m.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cB,{children:p("mcp.add.secrets")}),m.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(gP,{label:e,draft:s,suggestedName:gx(e,m.name),stored:m.fill?.ok?(t=m.fill.config,void 0!==(i="oauth.clientSecret"===(n=e)?"url"in t?t.oauth?.clientSecret:void 0:n.startsWith("headers.")?"url"in t?t.headers?.[n.slice("headers.".length)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice("env.".length)]:void 0)&&h_(i)?i:void 0):void 0,problem:m.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(c2,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":l||void 0,"aria-describedby":I?h:void 0,onClick:N,children:l?p("mcp.add.adding"):m.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),I&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${w?.kind==="scope"?"is-warning":"is-dim"}`,children:I}),v&&!w&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),a&&(0,r.jsxs)("div",{role:"alert",className:"mcp-add-failure",children:[(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[p("mcp.add.failed")," ",function(e,t){if(e.timedOut)return t("mcp.actionTimedOut");if("trust-too-broad"===e.reason&&e.breadth)return t(gN[e.breadth.kind],{path:g$(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(gv)?"mcp.add.projectBlocked.secret":"mcp.add.projectBlocked.secretFixed",{fields:e.fields.join(", ")});if("name-taken"===e.reason&&e.name)return t("mcp.add.nameTaken",{name:py(e.name),path:e.path?g$(e.path):"mcp.json"});let n=e.reason?gR[e.reason]:void 0;return n?t(n,{error:py(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):py(e.error)}(a,p)]}),a.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:g$(a.trust?.decisionPath??n??"")})}),a.notes&&a.notes.length>0&&(0,r.jsx)(gT,{notes:a.notes,fields:v?.fields}),"name-taken"===a.reason&&a.suggestedName&&w?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{size:"small",onClick:()=>$({name:a.suggestedName}),children:p("mcp.add.useName",{name:py(a.suggestedName)})})}),"host-env-confirm"===a.reason&&a.names&&a.names.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.hostEnv.body",{names:a.names.map(py).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:l||o||void 0!==w,onClick:()=>c(gk(s,m,a.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function gL(e){let{names:t}=e,{t:n}=(0,e0.s)();return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:py(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function gz(e){let t,{field:n,fields:s,draft:l,suggestedName:o,problem:a,onDraftChange:d}=e,{t:c}=(0,e0.s)(),u=(0,i.useId)(),p=a?{"aria-invalid":!0,"aria-describedby":u}:{},h=gh(n),f=h?l.references[n.id]:void 0,m=void 0!==f,g=py(n.label),x=l.values[n.id]??n.defaultValue??"",v=go[n.reason],b=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=m?f&&!a?gp(n,s,"${"+f+"}",!0):void 0:gp(n,s,`‹${c("mcp.add.field.slot")}›`),w=e=>d({...l,values:{...l.values,[n.id]:e}}),j=e=>{let t={...l.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...l,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(cH,{label:g,children:m?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:g}),value:f,placeholder:o??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)}):"select"===n.kind?(0,r.jsxs)("select",{className:"mcp-add-input","aria-label":g,value:x,...p,onChange:e=>w(e.target.value),children:[!n.options?.includes(x)&&(0,r.jsx)("option",{value:"",children:c("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,r.jsx)("option",{value:e,children:py(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":g,value:x,autoComplete:"off",placeholder:n.placeholder?py(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>w(e.target.value)})}),a&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:gl(a,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:py(n.description)}),v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(v)}),m?(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:y?c("mcp.add.field.storedAsVariable",{value:y}):c("mcp.add.field.variableHint")}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:b?c("mcp.add.field.optionalHeader",{name:py(b)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:m,onChange:e=>j(e.target.checked?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function gP(e){let{label:t,draft:n,suggestedName:s,stored:l,problem:o,onDraftChange:a}=e,{t:d}=(0,e0.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=py(t),f=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,a({...n,secretReferences:r})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)("span",{className:"mcp-config-lines",children:(0,r.jsxs)("span",{className:"mcp-config-line",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:h})," ",d("mcp.add.secret.holds")]})}),(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:p,onChange:e=>f(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(cH,{label:d("mcp.add.field.variableName",{field:h}),children:(0,r.jsx)("input",{className:"mcp-add-input","aria-label":d("mcp.add.field.variableName",{field:h}),value:u,placeholder:s??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...o?{"aria-invalid":!0,"aria-describedby":c}:{},onChange:e=>f(e.target.value)})}),o&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:gl(o,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==l?d("mcp.add.secret.storedAs",{value:py(l)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let gW=new Set(["done","failed","cancelled","expired"]);function gO(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!gW.has(t))}let gF={"mcp-off":"mcp.signIn.blocked.mcp-off","project-untrusted":"mcp.signIn.blocked.project-untrusted","trust-unreadable":"mcp.signIn.blocked.trust-unreadable",invalid:"mcp.signIn.blocked.invalid","web-password":"mcp.test.blocked.web-password"},gD={"mcp-off":"mcp.signIn.blocked.mcp-off","project-untrusted":"mcp.signIn.blocked.project-untrusted","trust-unreadable":"mcp.signIn.blocked.trust-unreadable","server-invalid":"mcp.signIn.blocked.invalid","web-password":"mcp.test.blocked.web-password","entry-not-object":"mcp.signIn.refused.file","server-missing":"mcp.signIn.refused.file",unparsable:"mcp.signIn.refused.file","invalid-shape":"mcp.signIn.refused.file","link-dangling":"mcp.signIn.refused.file","link-outside":"mcp.signIn.refused.file","not-a-file":"mcp.signIn.refused.file","too-large":"mcp.signIn.refused.file","too-many-servers":"mcp.signIn.refused.file","invalid-request":"mcp.signIn.refused.invalid-request"},gB={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},gH={"connect-failed":"mcp.signIn.failed.connect-failed","queue-timed-out":"mcp.signIn.failed.queue-timed-out","sign-in-failed":"mcp.signIn.failed.sign-in-failed",internal:"mcp.signIn.failed.internal"};function g_(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,gW.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function gU(e){return"sign-in-unknown"===e.reason}async function gq(e,t,n,r){var i;let s,l;try{s=await n(e,{...t,cache:"no-store",signal:r})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{l=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=l)&&"object"==typeof i&&"string"==typeof i.flowId&&"string"==typeof i.phase&&"string"==typeof i.name&&("global"===i.scope||"project"===i.scope)&&"number"==typeof i.expiresInMs?{ok:!0,data:l}:{ok:!1,error:p9(l,s.status)}}function gK(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},l=t.method??"GET";return p7(r=>gq(e,t,n,r),()=>({ok:!1,error:{error:`${l} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function gV(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function gZ(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"mcp.signIn.requestTimedOut";if(e.timedOut)return t(n);let r=e.reason?gD[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function gJ(e){let{server:t,run:n,block:s,signOutBlock:l,controlsBusy:o,signingOut:a,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,e0.s)(),f=(0,i.useId)(),m=(0,i.useId)(),g=(0,i.useId)(),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=gO(n),y=(0,i.useRef)(b);if((0,i.useEffect)(()=>{let e=y.current;y.current=b,!e&&b?eI(document,v.current):e&&!b&&eI(document,x.current)},[b]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(cU,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:py(t.authProvider)}):h("mcp.signIn.header")});let w=n?.flow,j=n?.starting===!0,k=void 0!==w&&(w.scope!==t.scope||w.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=j||a||void 0!==s,N=o||j||void 0!==l,$=w?.phase==="finishing";return(0,r.jsx)(cU,{label:h("mcp.detail.signIn"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line",children:h(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),w&&b&&k&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:py(w.name)})}),w&&b&&("authorize"===w.phase?(0,r.jsx)(gY,{flow:w,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,w.flowId,e)},w.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(gB[w.phase]??"mcp.signIn.phase.connecting")})),w&&b&&$&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),w&&!b&&!n?.gone&&(0,r.jsx)(gG,{flow:w,shared:k}),n?.gone&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:h("mcp.signIn.gone")}),n?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.requestFailed")," ",gZ(n.error,h)]}),b&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",gZ(n.cancelError,h,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.signOutFailed")," ",gZ(n.signOutError,h,"mcp.actionTimedOut")]}),n?.signedOut&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),s&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h(gF[s])}),!s&&l&&S&&!b&&(0,r.jsx)("span",{id:m,className:"mcp-config-line is-dim",children:h(gF[l])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[b&&w?(0,r.jsx)(c2,{ref:v,size:"small",disabled:n?.cancelling===!0||$,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":$?g:void 0,onClick:()=>p(t,w.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(c2,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":j||void 0,"aria-describedby":s?f:void 0,onClick:()=>d(t),children:h(j?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!b&&(0,r.jsx)(c2,{size:"small",disabled:N,"aria-busy":a||void 0,"aria-describedby":l?s?f:m:void 0,onClick:()=>c(t),children:h(a?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!b&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!l&&!b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function gY(e){let{flow:t,pasting:n,pasteError:s,onPaste:l}=e,{t:o}=(0,e0.s)(),[a,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{let e=u.current;u.current=n,e&&!n&&eI(document,c.current)},[n]);let p=function(e){if(void 0!==e)try{let t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol?t.href:void 0}catch{return}}(t.authorizationUrl);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(uo,{message:o("mcp.signIn.authorize.message"),hint:p?(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.link")," ",(0,r.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:py(p)})]}):(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.authorizationUrl??"")})]}),value:a,placeholder:o("mcp.signIn.paste.placeholder"),inputLabel:o("mcp.signIn.paste.label"),submitLabel:o(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:c,onValueChange:d,onSubmit:()=>l(a)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.signIn.paste.refused")," ",gZ(s,o,"mcp.signIn.paste.timedOut"),"redirect-denied"===s.reason&&s.error&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.redirect",{url:py(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.wait")})]})}function gG(e){let{flow:t,shared:n}=e,{t:i}=(0,e0.s)(),s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];switch(e.phase){case"done":{if(t)return e.alreadySignedIn?"mcp.signIn.shared.already":"mcp.signIn.shared.done";if(e.alreadySignedIn)return"mcp.signIn.done.already";let n=e.result;if(n&&"needs-auth"===n.state)return"mcp.signIn.done.needsAuthAfter";if(n&&"failed"===n.state)return"mcp.signIn.done.failedAfter";if(!n)return"mcp.signIn.done.notConnected";return e.refreshed?"mcp.signIn.done.refreshed":"mcp.signIn.done.signedIn"}case"failed":if(t&&"connect-failed"===e.failure)return"mcp.signIn.shared.connect-failed";return gH[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let l=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return"done"===e.phase?!t&&e.result&&"connected"!==e.result.state?"warning":"on":"failed"===e.phase?"error":"expired"===e.phase?"warning":"off"}(t,n);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{role:"status",className:"error"===l?"mcp-config-line is-error":"warning"===l?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:py(t.name)})}),t.error&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.error)})]})]})}function gX(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function gQ(e){return py(ey(e))}function g0(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:gQ(r.path)}):t(n)}function g1(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function g2(e,t){return e.timedOut?t("mcp.actionTimedOut"):g1(e,t)}function g4(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function g8(e){let{cwd:t,onClose:n,embedded:s=!1,trust:l,onTrustProject:o,onProjectTrustChanged:a}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(()=>ci("mcp",t)),[m,g]=(0,i.useState)({saving:!1,error:null}),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(null),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[$,E]=(0,i.useState)({}),I=(0,i.useRef)(0),M=(0,i.useRef)(null),T=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,z]=(0,i.useState)({}),P=(0,i.useRef)(L);P.current=L;let[W,O]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)(gn),_=(0,i.useRef)(B);_.current=B;let[U,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(null),Z=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let Y=(0,i.useCallback)(async()=>{let e=++I.current;M.current?.abort();let n=new AbortController;M.current=n,p(!0);let r=await hi(t,void 0,n.signal);if(e===I.current){if(p(!1),!r.ok)return void c({state:"failed",error:r.error});c({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),f(e=>pQ(pG(r.data,!!t),e))}},[t]),G=u_(l);(0,i.useEffect)(()=>(Y(),()=>{I.current+=1,M.current?.abort()}),[Y,G]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"preference"});let n=await ho(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&c(e=>{var t,r;let i;return"loaded"===e.state?{...e,data:(t=e.data,r=n.preference,i={...t.codemode,preference:r},delete i.preferenceError,{...t,codemode:i})}:e}),Y())},[Y]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"mode"});let n=await ha(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.mode;if(!n)return e;let r={settingsPath:n.settingsPath,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,mode:r}}}(e.data,n.mode)}:e),Y())},[Y]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await hd(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&c(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.inlineBudget;if(!n)return e;let r={settingsPath:n.settingsPath,default:n.default,max:n.max,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,inlineBudget:r}}}(e.data,n.inlineBudget)}:e),Y())},[Y]);(0,i.useEffect)(()=>{let e=A.current;return Z.current=!0,()=>{Z.current=!1,T.current?.abort(),T.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=pR(e);if(A.current.has(n))return;let r={};A.current.set(n,r),E(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await hC({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),E(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let s=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...s,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...s,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],l,e.configKey)}));let o=J.current,a="loaded"===o.state?o.data.servers.find(e=>pR(e)===n):void 0;(l.ok?a?.configKey===l.data.configKey:void 0===l.error.reason||l.error.timedOut)||Y()},[t,Y]),en=(0,i.useCallback)((e,n)=>{I.current+=1,M.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),f(r=>pQ(pG(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=pR(e),r=P.current[n];if(r?.starting||gO(r))return;z(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return gK("/api/mcp/sign-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e.scope,name:e.name,...t?{cwd:t}:{}})},n,r,i,{abortAtDeadline:!1})}({scope:e.scope,name:e.name},s);Z.current&&(z(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?g_({},e.data,t):{error:e.error}}(l)})),l.ok||void 0===l.error.reason||l.error.timedOut||Y())},[t,Y]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=pR(e);z(e=>e[r]?.flow?.flowId===t?{...e,[r]:{...e[r],pasting:!0,pasteError:void 0}}:e);let i=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return gK(gV(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);Z.current&&z(e=>{let n=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,pasting:!1,version:(e.version??0)+1};return n.ok?{...g_(i,n.data,r),pasteError:void 0}:gU(n.error)?{...i,gone:!0}:{...i,pasteError:n.error}}(e[r],t,i);return void 0===n||n===e[r]?e:{...e,[r]:n}})},[]),es=(0,i.useCallback)(async(e,t)=>{let n=pR(e);z(e=>e[n]?.flow?.flowId===t?{...e,[n]:{...e[n],cancelling:!0}}:e);let r=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return gK(gV(e),{method:"DELETE"},t,n,r)}(t);Z.current&&z(e=>{let i=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now();if(!e?.flow||e.flow.flowId!==t)return e;let i={...e,cancelling:!1,cancelError:void 0,version:(e.version??0)+1};return n.ok?g_(i,n.data,r):gU(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),el=Object.entries(L).flatMap(e=>{let[t,n]=e;return gO(n)&&n.flow?[`${t}\u0001${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!el)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of el.split("\x02")){let[n,r]=t.split("\x01"),i=P.current[n]?.version??0,s=await function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t)=>fetch(e,t),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:15e3;return gK(gV(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;z(e=>{let t=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:Date.now(),i=arguments.length>4?arguments[4]:void 0;return e?.flow&&e.flow.flowId===t&&(void 0===i||(e.version??0)===i)?n.ok?g_(e,n.data,r):gU(n.error)||void 0!==e.deadlineAt&&r>e.deadlineAt+5e3?{...e,gone:!0}:e:e}(e[n],r,s,Date.now(),i);return void 0===t||t===e[n]?e:{...e,[n]:t}})}O(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[el,W]);let eo=(0,i.useRef)(L);(0,i.useEffect)(()=>{let e=eo.current;eo.current=L,Object.keys(L).some(t=>{var n,r;return n=e[t],r=L[t],gO(n)&&!gO(r)})&&Y()},[L,Y]);let ea=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let s=J.current,l="loaded"===s.state&&s.data.project?t:null,o=await hg(e,l,void 0,i.signal);if(R.current===i)return R.current=null,v(null),o.ok?en(o.data,r?.(o.data)):Y(),o},[en,t,Y]),ed=(0,i.useCallback)(async(e,t)=>{let n=pR(e),r=g4();y(null),j(null);let i=await ea({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ec=(0,i.useCallback)(async(e,t)=>{let n=pR(e),r=g4();y(null),j(null);let i=await ea({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),eu=(0,i.useCallback)(async(e,t)=>{let n=pR(e),r=g4();y(null),j(null);let i=await ea({action:"set-exposure",scope:e.scope,name:e.name,exposure:t},`exposure:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[ea]),ep=(0,i.useCallback)(async e=>{let t=pR(e),n=g4();y(null),j(null);let r=await ea({action:"remove",scope:e.scope,name:e.name},`remove:${t}`);if(!r)return;if(!r.ok){y({key:t,failure:r.error}),N({control:n});return}let i=r.data.undo;i&&S({...i,undoing:!1})},[ea]),eh=(0,i.useCallback)(async()=>{if(!k)return;let e=g4();y(null),j(null),S({...k,undoing:!0,error:void 0});let t=await ea({action:"undo",token:k.token},"undo",e=>e.restored?pR(e.restored):void 0);t&&(S(e=>e?.token!==k.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[ea,k]),ef=(0,i.useCallback)(async e=>{let t=pR(e),n=g4();y(null),j(null),z(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await ea({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(z(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();E(n=>{let r=function(e,t){if(e)return{running:e.running,...void 0!==e.startedAt?{startedAt:e.startedAt}:{},signedOutAt:t}}(n[t],e);return r?{...n,[t]:r}:n})}N({control:n})}},[ea]),em=(0,i.useCallback)(async e=>{let n=g4(),r=_.current;y(null),j(null),q(null);let i=await ea(e,"add",e=>e.added?pR(e.added):void 0);if(!i)return;let s=_.current!==r;if(!i.ok){s||q(i.error),i.error.trust&&t&&a?.(t,i.error.trust),N({control:n});return}let{added:l,trust:o,trustedFolder:d}=i.data;if(D(!1),s||H(gn),N({control:null,toSelectedRow:!0}),!l)return;V({...l,key:pR(l),...d&&t?{trustedFolder:t}:{}}),o&&t&&a?.(t,o);let c=i.data.servers.find(e=>pR(e)===pR(l));c&&!hv(c,i.data)&&et(c)},[t,a,ea,et]),eg=k?.token,ex=k?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:uH(t,n,e=>e.enabled).filter(n?hf:hh),keptOff:n?t.filter(e=>!e.enabled&&hh(e)&&!hf(e)).length:0},s=g4();if(y(null),j(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let l=await ea({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!l)return;if(N({control:s}),!l.ok)return void j({scope:e,keptOff:i,failures:[],total:r.length,error:l.error});let o=l.data.results??[],a=o.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));j(a.length>0||i>0?{scope:e,keptOff:i,failures:a,total:o.length}:null)},[ea]);return(0,i.useEffect)(()=>{h&&cs("mcp",h,t)},[t,h]),(0,r.jsx)(g3,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:m,busy:x,actionError:b,groupStatus:w,undo:k,focusBack:C,tests:$,signIns:L,adding:F,addDraft:B,addFailure:U,added:K,onAddOpen:()=>{D(!0),V(null),y(null)},onAddDraftChange:e=>{_.current=e,H(e),q(null)},onAddSubmit:e=>void em(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void ef(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{f(e),y(null),D(!1),V(t=>t?.key===e?t:null)},onRefresh:()=>void Y(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ed(e,t),onServerSwitchInProject:(e,t)=>void ec(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:o,onClose:n})}function g3(e){var t,n,s,l;let o,a,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:f,codemodeSave:m={saving:!1,error:null},busy:g=null,actionError:x=null,groupStatus:v=null,undo:b=null,focusBack:y=null,tests:w={},signIns:j={},adding:k=!1,addDraft:S=gn,addFailure:C=null,added:N=null,onAddOpen:$=()=>{},onAddDraftChange:E=()=>{},onAddSubmit:I=()=>{},onSelect:M,onRefresh:T,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:z=()=>{},onServerSwitchInProject:P=()=>{},onExposureChange:W=()=>{},onGroupSwitch:O=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:H=()=>{},onSignOut:_=()=>{},onSignInPaste:U=()=>{},onSignInCancel:q=()=>{},onTrustProject:K,onClose:V}=e,{t:Z}=(0,e0.s)(),J=(0,i.useId)(),Y=(0,i.useId)(),G="loaded"===u.state?(t=u.data,o=!1,a=t.servers.map(e=>{var t;let n=w[pR(e)]?.response;if(!n||n.configKey!==e.configKey||e.status&&("test"===(t=e.status).origin?t.testedAt:t.closedAt??t.updatedAt)>=n.result.testedAt)return e;o=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),o?{...t,servers:a}:t):void 0,X=G?pG(G,!!c):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:pA(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>pR(e)===p),en=N?ee.find(e=>pR(e)===N.key):void 0,er=G?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(G.mcp):void 0,ei=er?void 0:G?.hostInactive,es=G?.files.find(e=>"project"===e.scope),el=G?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(G.project,es):void 0,eo=K&&p0(G?.project)?K:void 0,ea=el?.kind==="untrusted"&&void 0!==eo,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(ea);(0,i.useEffect)(()=>{let e=eu.current;eu.current=ea,e&&!ea&&eI(document,ed.current??ec.current)},[ea]);let ep=(0,i.useRef)(null),eh=b?.token,ef=(0,i.useRef)(eh);(0,i.useEffect)(()=>{let e=ef.current;ef.current=eh,void 0!==eh&&eh!==e?eI(document,ep.current):void 0!==e&&void 0===eh&&eI(document,ed.current??ec.current)},[eh]);let em=G?[...G.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],eg=pX(ee),ex=G?.files.find(e=>"global"===e.scope),ev=G?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&pA(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(G):void 0,eb=G?(n=ee.length,s=G.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(pY))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ew=null!==g||h||m.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ew&&ej.current!==y)if(ej.current=y,y.toSelectedRow)eI(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&eI(e,t.isConnected&&!t.disabled?t:n)}},[y,ew]);let ek=e=>G?hu(e,G):void 0,eS=!!G&&hc(G.mcp),eC=X.find(e=>"project"===e.scope)?.servers??[],eN=ek("project"),e$=el?.kind==="untrusted"?[g0(el,Z),eN&&"mcp-off"!==eN&&eC.length>0?Z(hp[eN]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(c$,{embedded:f,title:Z("settings.mcp"),subtitle:c?ey(c):void 0,closeLabel:Z("i18n.close"),onClose:V,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(cY,{id:J,children:[g0(er,Z),eS&&(0,r.jsxs)(r.Fragment,{children:[" ",Z(hp["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(G.mcp.detail)})]})]}),ei&&(0,r.jsx)(cY,{children:Z("mcp.hostInactive",{path:gQ(ei.cwd),owner:gQ(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(cY,{children:Z("mcp.projectNotListed",{reason:g1(u.projectError,Z)})}),el?.kind==="untrusted"&&(0,r.jsx)(cG,{id:Y,message:e$,trustLabel:Z("mcp.trust.trustButton"),onTrust:eo}),el?.kind==="inherited"&&(0,r.jsx)(cY,{children:g0(el,Z)}),b&&(0,r.jsxs)(cY,{action:b.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(c2,{ref:ep,size:"small",onClick:D,disabled:b.undoing||ew,children:b.undoing?Z("mcp.undoing"):Z("mcp.undo")}),children:[Z("mcp.removed",{name:py(b.name),path:gQ(b.path)}),b.error&&(0,r.jsxs)(r.Fragment,{children:[" ",Z("mcp.undoFailed")," ",g2(b.error,Z)]})]}),N&&G&&en&&(0,r.jsx)(g5,{added:N,cwd:c,server:en,testing:w[N.key]?.running===!0,signIn:j[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?hv(en,G):void 0,onSignIn:H})]}),(0,r.jsxs)(cE,{children:[(0,r.jsxs)(cI,{children:[(0,r.jsx)(cM,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:Z("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[Z("mcp.loadFailed")," ",g1(u.error,Z)]}):G&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(g6,{codemode:G.codemode,active:!k&&p===pT,rowRef:ed,onSelect:M})}),X.map(e=>{let t=ek(e.scope);return(0,r.jsx)(g9,{group:e,context:Q,selected:k?null:p,selectedRowRef:ed,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&el?.kind==="untrusted"?Y:void 0,busy:g,controlsBusy:ew,status:v?.scope===e.scope?v:null,onSelect:M,onGroupSwitch:O},e.scope)})]}):null}),G&&(0,r.jsx)(c8,{ref:ec,active:k,onClick:$,children:Z("mcp.add.action")})]}),(0,r.jsx)(cQ,{children:(0,r.jsx)(cP,{className:"is-fill",children:G&&Q&&ev&&eb?k?(0,r.jsx)(gA,{data:G,cwd:c,draft:S,busy:"add"===g,controlsBusy:ew,failure:C,onDraftChange:E,onSubmit:I,onTrustProject:eo}):p===pT?(0,r.jsx)(xc,{codemode:G.codemode,autoEnable:ev,save:m,serverBusy:null!==g,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(xt,{server:et,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ev,block:ek(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!pA(t.project))return;let n=t.files.find(e=>"project"===e.scope);if(!n||n.problems.some(e=>"auto-enable-codemode-invalid"!==e.reason))return;let r=t.servers.find(t=>"project"===t.scope&&t.name===e.name);return r?r.override?{kind:"override",key:pR(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,G),inProjectBlock:ek("project"),savedWhileOff:!G.mcp.available&&!eS,busy:g,controlsBusy:ew,actionError:x?.key===pR(et)?x.failure:null,test:(l=w[pR(et)],l&&void 0!==l.configKey&&l.configKey!==et.configKey?{running:l.running,...l.response?{response:l.response}:{}}:l),testBlock:hv(et,G),signIn:j[pR(et)],signInBlock:hv(et,G),signOutBlock:(d=hu(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:z,onSwitchInProject:P,onShowServer:e=>{M(e),requestAnimationFrame(()=>eI(document,ed.current??ec.current))},onExposureChange:W,onRemove:F,onTest:B,onSignIn:H,onSignOut:_,onSignInPaste:U,onSignInCancel:q},pR(et)):(0,r.jsx)(cX,{children:"mcp.empty"===eb?Z(eb,{globalPath:gQ(ex?.path??"~/.pi/agent/mcp.json")}):Z(eb)}):null})})]}),(0,r.jsxs)(c0,{status:em.length>0?(0,r.jsx)(c1,{tone:em.some(e=>{let{problem:t}=e;return pY(t)})?"error":"warning",summary:1===em.length?Z("mcp.footer.fileProblem"):Z("mcp.footer.fileProblems",{count:em.length}),details:em.map(e=>{let{file:t,problem:n}=e,i=pM(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:gQ(t.path)})," ",Z(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(c1,{summary:eg.total>0?Z("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):""}),children:[!f&&(0,r.jsx)(c2,{onClick:V,children:Z("i18n.close")}),(0,r.jsx)(c2,{variant:"secondary",onClick:T,disabled:ew,children:Z("i18n.refresh")})]})]})}function g5(e){let{added:t,cwd:n,server:i,testing:s,signIn:l,signingOut:o,signInBlock:a,onSignIn:d}=e,{t:c}=(0,e0.s)(),u=py(t.name),p="project"===t.scope&&n?py(ew(t.path,n)):gQ(t.path),h=i.status,f=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,m=l?.starting===!0||gO(l);return(0,r.jsxs)(cY,{action:!f||m||o||a?void 0:(0,r.jsx)(c2,{size:"small",variant:"primary",onClick:()=>d(i),children:c("mcp.signIn.button")}),children:[void 0===t.trustedFolder?c("mcp.add.added",{name:u,path:p}):t.trustedFolder===n?c("mcp.add.addedTrustedHere",{name:u,path:p}):c("mcp.add.addedTrusted",{name:u,path:p,folder:gQ(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),f&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function g6(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:l}=(0,e0.s)(),o=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=l(p3[o]);return(0,r.jsxs)(cL,{ref:n?i:void 0,active:n,"aria-label":l("mcp.codemode.rowLabel",{state:a}),onClick:()=>s(pT),children:[(0,r.jsx)(c3,{...pH(p5(o))}),(0,r.jsx)(cz,{className:"is-grow",children:l("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${p5(o)}`,children:a})]})}function g9(e){var t;let n,i,{group:s,context:l,selected:o,selectedRowRef:a,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:f,onGroupSwitch:m}=e,{t:g}=(0,e0.s)(),{enabled:x,total:v}=pX(s.servers),b=(t=s.servers).some(e=>e.enabled&&hh(e))&&t.every(e=>e.enabled||!hf(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(pY)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),w=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${g("mcp.actionFailed")} ${g2(h.error,g)}`:h.failures.length>0?[g("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${py(t)}: ${g2(n,g)}`})].join("\n"):void 0,{...n?{note:n}:{},...i?{error:i}:{}}):void 0;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(cT,{aside:v>0?(0,r.jsx)(cR,{enabled:x,total:v,checked:b,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:gX(s.scope,g)}),onChange:e=>m(s.scope,s.servers,e)}):void 0,children:gX(s.scope,g)}),w&&(0,r.jsx)(cA,{note:w.note,error:w.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),s.servers.map(e=>{let t=pR(e),n=pz(e,l),i=pB(n),s=pD[n],d=py(e.name);return(0,r.jsxs)(cL,{ref:o===t?a:void 0,active:o===t,"aria-label":g("mcp.rowLabel",{name:d,state:g(pO(n,e.status))}),onClick:()=>f(t),children:[(0,r.jsx)(c3,{...pH(i)}),(0,r.jsx)(cz,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:g(s)})]},t)})]})}function g7(e){let{fields:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=pN(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function xe(e){let{names:t}=e;return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,r.jsx)("code",{className:"mcp-config-chip",children:py(e)},e))})}function xt(e){let{server:t,context:n,codemode:s,toolSearchDisabled:l,autoEnable:o,block:a,inProject:d,inProjectBlock:c,savedWhileOff:u,busy:p,controlsBusy:h,actionError:f,test:m,testBlock:g,signIn:x,signInBlock:v,signOutBlock:b,onSwitch:y,onSwitchInProject:w,onShowServer:j,onExposureChange:k,onRemove:S,onTest:C,onSignIn:N,onSignOut:$,onSignInPaste:E,onSignInCancel:I}=e,{t:M}=(0,e0.s)(),T=(0,i.useId)(),R=(0,i.useId)(),A=pz(t,n),L=pS(t),z=t.status,P=z?.origin==="test"&&"connected"===z.state&&z.toolCount>0?z:void 0,W=void 0===t.invalidError,O="http"===t.transport||void 0===t.transport&&void 0!==t.url,F=!O&&("stdio"===t.transport||void 0!==t.command),D=t.exposure?function(e,t,n){if("codemode"===e){var r;return r=t.codemode,"unavailable"===r.sandbox.state?{key:"mcp.exposure.sandboxUnavailable"}:r.builtinDisabled?{key:"mcp.exposure.builtinDisabled"}:n.value||"always"===p1(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:l},o):void 0,B=(0,i.useId)(),H=(0,i.useId)(),_=pR(t),U=py(t.name),q=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,V=a?M(`mcp.reason.${a}`):K?M("mcp.reason.entry-not-object"):q?M("mcp.reason.web-password"):u?M("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(cP,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(cW,{children:[(0,r.jsxs)(cO,{children:[(0,r.jsx)(cq,{scope:t.scope,children:gX(t.scope,M)}),(0,r.jsx)(cD,{children:U})]}),(0,r.jsxs)(cF,{children:[(0,r.jsx)(xa,{server:t,test:m,testBlock:g,describedBy:R,onTest:C}),(0,r.jsx)(c2,{variant:"danger",size:"small",disabled:h||void 0!==a,"aria-describedby":a?T:void 0,onClick:()=>S(t),children:p===`remove:${_}`?M("i18n.removing"):M("i18n.remove")}),(0,r.jsx)(c4,{checked:t.enabled,disabled:h||void 0!==a||K||q,loading:p===`switch:${_}`,describedBy:V?T:void 0,label:M(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:U}),onChange:e=>y(t,e)})]})]}),V&&(0,r.jsx)("div",{id:T,className:"config-detail-heading-note",children:V})]}),f&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[M("mcp.actionFailed")," ",g2(f,M)]}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(xd,{server:t,state:A,test:m,testBlock:g,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(cU,{label:M("mcp.detail.description"),tone:"plain",children:py(t.description)}),void 0!==L?(0,r.jsx)(cU,{label:O?M("mcp.detail.url"):M("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:L}):t.transport&&(0,r.jsx)(cU,{label:M("mcp.detail.transport"),children:M(`mcp.transport.${t.transport}`)}),F&&void 0!==t.cwd&&(0,r.jsx)(cU,{label:M("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:py(t.cwd)}),F&&t.envNames.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.env"),children:(0,r.jsx)(xe,{names:t.envNames})}),O&&t.headerNames.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.headers"),children:(0,r.jsx)(xe,{names:t.headerNames})}),W&&t.commandFields.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.shellCommands"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:M("mcp.server.commandFields")}),(0,r.jsx)(g7,{fields:t.commandFields})]})}),W&&t.variableReferences.length>0&&(0,r.jsx)(cU,{label:M("mcp.detail.variables"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:M(p$(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:pI(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=pN(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:M("mcp.server.variableIn",{variable:t,field:M(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),O&&W&&(0,r.jsx)(gJ,{server:t,run:x,block:v,signOutBlock:b,controlsBusy:h,signingOut:p===`sign-out:${_}`,onSignIn:N,onSignOut:$,onPaste:E,onCancel:I}),(t.exposure||P)&&(0,r.jsx)(cU,{label:M("mcp.detail.exposure"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,r.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":M("mcp.exposure.label",{name:U}),"aria-describedby":[B,a?T:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==a,onChange:e=>{let n=e.target.value;n!==t.exposure&&k(t,n)},children:pZ.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?M("mcp.exposure.optionDefault",{label:M(pJ[e])}):M(pJ[e])},e))}),p===`exposure:${_}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:M("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:M(pV[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:M("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),D&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(D,M)})]}),P&&(0,r.jsx)(xo,{status:P,serverExposure:t.exposure})]})}),d&&(0,r.jsx)(cU,{label:M("mcp.detail.inProject"),tone:"plain",children:(0,r.jsx)("span",{className:"mcp-config-lines",children:"override"===d.kind?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line",children:d.applies?M("mcp.inProject.overridden",{keys:d.keys.join(", ")}):M("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(c2,{size:"small",onClick:()=>j(d.key),children:M("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(c2,{size:"small",disabled:h||void 0!==c||q,"aria-describedby":[H,c||q?T:null].filter(Boolean).join(" "),onClick:()=>w(t,!t.enabled),children:p===`in-project:${_}`?M("i18n.saving"):M(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:H,className:"mcp-config-line is-dim",children:M("mcp.inProject.saved")})]})})}),(0,r.jsx)(cU,{label:M("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:gQ(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[pC(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:M("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:M("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:M("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:g0(pE(t.override.keys),M)}),t.shadowedByProject&&"replaced"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:M("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:M("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:M("mcp.server.masked")})]})]})}function xn(e){let{error:t,stderr:n}=e,{t:i}=(0,e0.s)();return(0,r.jsxs)(r.Fragment,{children:[t&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.test.error")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t)})]}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.stderr")}),(0,r.jsx)("pre",{className:"mcp-test-output",children:n.split(/\r?\n/).map(py).join("\n")})]})]})}function xr(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(xl,{status:t,showState:n}):(0,r.jsx)(xs,{status:t,showState:n,entryCwd:i})}function xi(e){let{view:t}=e,{t:n}=(0,e0.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function xs(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:l}=(0,e0.s)(),o=p_(t.testedAt,l),a=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(xi,{view:t.timedOut?{key:hy.timedOut,tone:"error"}:{key:hy[t.state],tone:pB(t.state)}}),s((t.afterSignIn?hj:hw)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:hk(t.durationMs),time:o})]}),(0,r.jsx)(xn,{error:t.error,stderr:t.stderr}),a&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:py(a.title??a.name),version:py(a.version)})}),t.resources&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.resources")}),void 0!==t.cwd&&t.cwd!==i&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.ranIn",{path:gQ(t.cwd)})}),void 0!==t.queuedMs&&t.queuedMs>=500&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.queued",{seconds:hk(t.queuedMs)})})]})}function xl(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,e0.s)(),l=p_(t.updatedAt,s),o=void 0===t.closedAt?void 0:p_(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(xi,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:pU[t.state],tone:pK[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":pq[t.state],{path:gQ(t.cwd),time:l,...void 0===o?{}:{closedTime:o}})]}),void 0!==t.conflict&&(0,r.jsxs)("span",{className:"mcp-config-line is-error",children:[i("mcp.session.conflictOwner")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:gQ(t.conflict)})]}),(0,r.jsx)(xn,{error:t.error,stderr:t.stderr})]})}function xo(e){let{status:t,serverExposure:n}=e,{t:i}=(0,e0.s)(),s=t.toolCount-t.tools.length;return(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("ul",{className:"mcp-test-tools",children:t.tools.map((e,t)=>(0,r.jsxs)("li",{className:"mcp-test-tool",children:[(0,r.jsxs)("span",{className:"mcp-config-chips",children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:py(e.name)}),e.readOnly&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i("mcp.test.readOnly")}),e.exposure!==(n??"codemode")&&(0,r.jsx)("span",{className:"mcp-test-tool-tag",children:i(pJ[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:py(e.description)})]},`${t}\0${e.name}`))}),s>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.moreTools",{count:s})})]})}function xa(e){let{server:t,test:n,testBlock:s,describedBy:l,onTest:o}=e,{t:a}=(0,e0.s)(),d=(0,i.useRef)(null),c=n?.running===!0,u=(0,i.useRef)(c);return(0,i.useEffect)(()=>{let e=u.current;u.current=c,e&&!c&&eI(document,d.current)},[c]),(0,r.jsx)(c2,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?l:void 0,onClick:()=>o(t),children:a(c?"mcp.test.testing":"mcp.test.button")})}function xd(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:l}=e,{t:o}=(0,e0.s)(),a=t.status,d=pF[n],c="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(cU,{label:o("i18n.status"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-lines",children:[(0,r.jsx)("span",{className:`mcp-config-state is-${pB(n)}`,children:o(pO(n,a))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===c?l:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===c?l:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.webPassword")," ",(0,r.jsx)(g7,{fields:[t.webPasswordField]})]}),a?(0,r.jsx)(xr,{status:a,showState:pL(a)!==n,entryCwd:t.cwd}):!s&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.never")}),d&&(0,r.jsx)("span",{className:"mcp-config-line",children:o(d)}),i?.queueTimedOut&&(0,r.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:o("mcp.test.queueTimedOut")}),i?.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?hb[e.reason]:void 0;return n?t(n):g1(e,t)}(i.error,o)]}),s&&!c&&(0,r.jsx)("span",{id:l,className:"mcp-config-line is-dim",children:o(hx[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.serial")})]})})}function xc(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:l,onModeChange:o,onInlineBudgetSave:a}=e,{t:d}=(0,e0.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},f=function(e,t){if("automatic"===p1(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),m="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,g=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:p2[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(cP,{children:[(0,r.jsx)(cW,{children:(0,r.jsx)(cO,{children:(0,r.jsx)(cD,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(c_,{children:[(0,r.jsx)(cU,{label:d("mcp.codemode.mode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[u?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cK,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(p3.automatic),disabled:p},{value:"always",label:d(p3.always),disabled:p||void 0!==m}],disabledReason:m?g0(m,d):null,onChange:e=>{e!==u&&l(e)},children:h.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(xu,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(x,d)}),f&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(f,d)})]})}),t.mode?(0,r.jsx)(xp,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:o}):void 0!==t.modeError&&(0,r.jsx)(cU,{label:d("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(xh,{budget:t.inlineBudget,save:i,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,r.jsx)(cU,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.preferenceError")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.inlineBudgetError)})]})}),(0,r.jsx)(cU,{label:d("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===c.state?(0,r.jsxs)("span",{className:"mcp-config-line is-warning",children:[d("mcp.codemode.sandbox.unavailable")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:py(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,r.jsx)(cU,{label:d("mcp.codemode.builtin"),tone:"error",children:g0(g,d)})]})]})}function xu(e){let{error:t}=e,{t:n}=(0,e0.s)();return t.timedOut?(0,r.jsx)(r.Fragment,{children:n("mcp.codemode.saveTimedOut")}):t.reason&&"internal"!==t.reason?(0,r.jsx)(r.Fragment,{children:n(`mcp.reason.${t.reason}`)}):(0,r.jsx)("code",{className:"mcp-config-chip",children:py(t.error)})}function xp(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:l}=e,{t:o}=(0,e0.s)(),a="mode"===i.target,d=function(e){let t=e.mode;if(!t)return[];let n=[];void 0!==t.invalid&&n.push({key:"mcp.codemode.toolMode.invalid",params:{path:t.settingsPath,value:t.invalid}});let r=t.projectOverride;return r&&n.push({key:p8[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===p1(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(cU,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(cK,{value:t.value,label:o("mcp.codemode.toolMode"),options:[{value:"on",label:o("mcp.codemode.toolMode.on"),disabled:s},{value:"only",label:o("mcp.codemode.toolMode.only"),disabled:s}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&l(e)},children:a&&i.saving&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:o("i18n.saving")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:o(p4[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(e,o)},e.key)),a&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(xu,{error:i.error})]})]})})}function xh(e){let t,n,{budget:s,save:l,waiting:o,onSave:a}=e,{t:d}=(0,e0.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,f]=(0,i.useState)(p);(0,i.useEffect)(()=>{f(p)},[p]);let m=function(e,t){let n=e.trim();if(""===n)return{ok:!0,value:null};if(!/^\d+$/.test(n))return{ok:!1};let r=Number(n);return r<=t?{ok:!0,value:r}:{ok:!1}}(h,s.max),g=!!m.ok&&(null===m.value?void 0!==s.value||void 0!==s.invalid:m.value!==s.value),x="inlineBudget"===l.target,v=x&&l.saving,b=(0,i.useRef)(v);(0,i.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&eI(document,c.current)},[v]);let y=(t=[],void 0!==s.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:s.settingsPath,value:s.invalid,default:String(s.default)}}),(n=s.projectOverride)&&t.push(void 0!==n.value?{key:"mcp.codemode.inlineBudget.projectOverride",params:{path:n.settingsPath,value:String(n.value)}}:{key:"mcp.codemode.inlineBudget.projectOverrideDefault",params:{path:n.settingsPath,default:String(s.default)}}),t);return(0,r.jsx)(cU,{label:d("mcp.codemode.inlineBudget"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),m.ok&&g&&!o&&a(m.value)},children:[(0,r.jsx)("input",{ref:c,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":d("mcp.codemode.inlineBudget"),"aria-describedby":u,"aria-invalid":!m.ok||void 0,value:h,placeholder:String(s.default),readOnly:o,autoComplete:"off",spellCheck:!1,onChange:e=>f(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(c2,{type:"submit",size:"small",disabled:!g||o,children:d("mcp.codemode.inlineBudget.save")}),v&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!m.ok&&(0,r.jsx)("span",{className:"mcp-config-line is-error",children:d("mcp.codemode.inlineBudget.invalidDraft",{max:String(s.max)})}),(0,r.jsx)("span",{id:u,className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.description",{default:String(s.default)})}),y.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:g0(e,d)},e.key)),x&&l.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(xu,{error:l.error})]})]})})}let xf=[{kind:"ui",label:"settings.uiFontFamily",placeholder:"settings.uiFontPlaceholder",reset:"settings.resetUiFont",weightLabel:"settings.uiFontWeight"},{kind:"mono",label:"settings.monoFontFamily",placeholder:"settings.monoFontPlaceholder",reset:"settings.resetMonoFont",weightLabel:"settings.monoFontWeight"}];function xm(){let{t:e}=(0,e0.s)(),t=oL();return(0,r.jsx)("div",{className:"settings-font-rows",children:xf.map(n=>{let{kind:i,label:s,placeholder:l,reset:o,weightLabel:a}=n,d=t[`${i}Weight`],c=of.findIndex(e=>e.value===d);return(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,r.jsx)("label",{htmlFor:`settings-font-${i}`,children:e(s)}),(0,r.jsx)("input",{id:`settings-font-${i}`,className:`settings-font-input${"mono"===i?" is-mono":""}`,type:"text",value:t[i],placeholder:e(l),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(i,e.target.value)}),(0,r.jsx)("output",{htmlFor:`settings-font-${i}-weight`,title:`${e(a)}: ${d}`,children:e(of[c].label)}),(0,r.jsx)(c2,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(o),"aria-label":e(o),disabled:!t[i]&&400===d,onClick:()=>t.resetFontPreference(i),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:`settings-font-${i}-weight`,type:"range",min:of[0].value,max:of[of.length-1].value,step:100,value:d,"aria-label":e(a),"aria-valuetext":`${d} ${e(of[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function xg(e){let{section:t,size:n=16,strokeWidth:i=1.8}=e,s={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"skills"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m12 2-10 5 10 5 10-5-10-5Z"}),(0,r.jsx)("path",{d:"m2 12 10 5 10-5M2 17l10 5 10-5"})]}):"agents"===t?(0,r.jsxs)("svg",{...s,className:"settings-section-icon is-agent",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"archives"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]}):"mcp"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"7",rx:"2"}),(0,r.jsx)("rect",{x:"3",y:"14",width:"18",height:"7",rx:"2"}),(0,r.jsx)("path",{d:"M7 6.5h.01M7 17.5h.01M11 6.5h6M11 17.5h6"})]}):(0,r.jsx)("svg",{...s,children:(0,r.jsx)("path",{d:"M9 7V2M15 7V2M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0ZM12 19v3"})})}function xx(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:l}=e,{locale:o,setLocale:a,supportedLocales:d,t:c}=(0,e0.s)(),{preference:u,setThemePreference:p}=i5(),{width:h,setWidth:f,fontSize:m,setFontSize:g}=oh(),x=l9(),v=eQ(),[b,y]=(0,i.useState)(null),[w,j]=(0,i.useState)(!1),[k,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[$,E]=(0,i.useState)(null),[I,M]=(0,i.useState)(!1),[T,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[W,O]=(0,i.useState)(!1),[F,D]=(0,i.useState)(!1),[B,H]=(0,i.useState)("");(0,i.useEffect)(()=>{N(sL()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>O(e?.enabled===!0)).catch(()=>{})},[]);let _=async()=>{D(!0),H("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{H(c("auth.logoutFailed"))}finally{D(!1)}};(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||y(n)}).catch(t=>{e||S(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||E(!0===n.enabled)}).catch(t=>{e||R(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let U=async e=>{M(!0),R(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);E(!0===i.enabled),t&&n()}catch(e){R(e instanceof Error?e.message:String(e))}finally{M(!1)}},q=async e=>{j(!0),S(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i),t&&(await aI(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{j(!1)}},K=async()=>{if(!A){L(!0),P(null);try{if(!("Notification"in window))throw Error("unsupported or not permitted");let e="default"===Notification.permission?await Notification.requestPermission():Notification.permission;if("granted"!==e||!await uB(o))throw Error("unsupported or not permitted");P({kind:"ok",message:c("settings.pushRegistered")})}catch(e){P({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{L(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("settings.appearance"),className:"settings-theme-options",children:i_.map(e=>{let t=u===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option","data-system":"auto"===e.id||void 0,"data-wide":"contrast-light"===e.id||"contrast-dark"===e.id||"zenburn"===e.id||void 0,children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),"auto"===e.id?(0,r.jsxs)("span",{className:"settings-theme-swatch settings-theme-system","aria-hidden":"true",children:[(0,r.jsx)("span",{"data-theme":"light",className:"settings-theme-chip"}),(0,r.jsx)("span",{"data-theme":"dark",className:"settings-theme-chip"}),(0,r.jsx)("span",{className:"settings-theme-system-name",children:c(e.label)})]}):(0,r.jsx)("span",{className:"settings-theme-swatch","aria-hidden":"true",children:(0,r.jsx)("span",{"data-theme":e.id,className:"settings-theme-fill",children:(0,r.jsx)("span",{className:"settings-theme-name",children:c(e.label)})})}),(0,r.jsx)("span",{className:"sr-only",children:c(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.typography")}),(0,r.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:c("settings.fontDescription")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsx)(xm,{}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:c("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[m,"px"]}),(0,r.jsx)(c2,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:14===m,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:m,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:c("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(c2,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>f(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>f(Number(e.target.value))})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.thinkingExpandedDefault")}),(0,r.jsx)(c4,{checked:C,label:c("settings.thinkingExpandedDefault"),onChange:e=>{!function(e){try{window.localStorage.setItem(sR,String(e))}catch{return}window.dispatchEvent(new Event(sA))}(e),N(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.quoteSelection")}),(0,r.jsx)(c4,{checked:s,label:c("settings.quoteSelection"),onChange:l})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.enterSendMode"),children:[(0,r.jsx)("span",{children:c("settings.enterSendMode")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"enter",checked:"enter"===x,onChange:()=>l6("enter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeEnter")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"enter-send-mode",value:"ctrlEnter",checked:"ctrlEnter"===x,onChange:()=>l6("ctrlEnter"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.enterSendModeCtrlEnter")})]})]})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.cacheMissNotices")}),(0,r.jsx)(c4,{checked:!0===$,loading:null===$&&!T||I,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void U(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),T&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:T})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.sidebar")}),(0,r.jsx)("div",{className:"settings-chat-options",children:(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":c("settings.filesPlacement"),"aria-describedby":"settings-files-placement-description",children:[(0,r.jsx)("span",{children:c("settings.filesPlacement")}),(0,r.jsxs)("div",{className:"settings-send-mode-options",children:[(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"below",checked:"below"===v,onChange:()=>eX("below"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementBelow")})]}),(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"radio",name:"files-placement",value:"tab",checked:"tab"===v,onChange:()=>eX("tab"),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:c("settings.filesPlacementTab")})]})]})]})}),(0,r.jsx)("p",{id:"settings-files-placement-description",className:"settings-general-description",children:c("settings.filesPlacementDescription")})]}),b?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.usePowerShell")}),(0,r.jsx)(c4,{checked:b.powerShellEnabled,loading:w,label:c("settings.usePowerShell"),onChange:e=>void q(e)})]}),k&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:k})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:c("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:c("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:A,onClick:()=>void K(),children:A?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),z&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===z.kind?{color:"var(--accent)"}:void 0,children:z.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":c("common.language"),className:"settings-language-options",children:d.map(e=>{let t=o===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>a(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),W&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(c2,{variant:"secondary",disabled:F,onClick:()=>void _(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),F?c("auth.loggingOut"):c("auth.logOut")]}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]})]})}let xv={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function xb(e){let{cwd:t,sessionId:n,initialSection:s,onClose:l,onSessionReloaded:o,quoteSelectionEnabled:a,onQuoteSelectionChange:d,projectTrust:c,onOpenTrustDialog:u,onProjectTrustChanged:p}=e,{t:h,locale:f}=(0,e0.s)(),[m,g]=(0,i.useState)(s),[x,v]=(0,i.useState)(()=>new Set([m])),b=[{id:"general",label:h("settings.general")},{id:"models",label:h("common.models")},{id:"archives",label:xv[f]??xv.en},{id:"skills",label:h("common.skills")},{id:"agents",label:h("common.agents")},{id:"plugins",label:h("common.plugins")},{id:"mcp",label:h("settings.mcp")}].map(e=>({...e,requiresProject:d7(e.id)})),y=d7(m);(0,i.useEffect)(()=>cr(s),[s]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eE(e)||(e.preventDefault(),l())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[l]);let w=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>(function(e,t){let{restoreTextEntry:n=!0}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.activeElement,i=!!(r&&t&&t.contains(r)),s=r&&r!==e.body&&!i?r:null;return t&&!i&&t.focus({preventScroll:!0}),()=>{if(!s||!s.isConnected||!n&&function(e){if(e.isContentEditable)return!0;let t=e.tagName?.toUpperCase();return"TEXTAREA"===t||"INPUT"===t&&!["button","checkbox","color","file","hidden","image","radio","range","reset","submit"].includes((e.type??"text").toLowerCase())}(s))return;let r=e.activeElement;r&&r!==e.body&&!(t&&t.contains(r))||"function"==typeof s.focus&&s.focus({preventScroll:!0})}})(document,w.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!t&&y&&(g("general"),v(e=>new Set(e).add("general")),cr("general"))},[t,y]);let j=e=>{v(t=>new Set(t).add(e)),g(e),cr(e)},k=(e,t)=>x.has(e)?(0,r.jsx)("div",{hidden:m!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:w,role:"dialog","aria-modal":"true","aria-label":h("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&l()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:h("settings.title")}),(0,r.jsx)("select",{"aria-label":h("settings.title"),value:m,onChange:e=>j(e.target.value),className:"settings-mobile-section-picker",children:b.map(e=>(0,r.jsx)("option",{value:e.id,disabled:e.requiresProject&&!t,children:e.label},e.id))}),(0,r.jsx)("nav",{"aria-label":h("settings.title"),className:"settings-section-tabs",children:b.map(e=>{let n=m===e.id,i=e.requiresProject&&!t;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?h("settings.projectRequired"):e.label,"aria-current":n?"page":void 0,onClick:()=>j(e.id),children:[(0,r.jsx)(xg,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:l,title:h("i18n.close"),"aria-label":h("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[k("general",(0,r.jsx)(xx,{sessionId:n,onSessionReloaded:o,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),k("models",(0,r.jsx)(uF,{embedded:!0,cwd:t,onClose:l})),k("archives",(0,r.jsx)(pg,{embedded:!0,onClose:l})),t&&k("skills",(0,r.jsx)(uY,{embedded:!0,cwd:t,trust:c,onClose:l},t)),t&&k("agents",(0,r.jsx)(u7,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:l,onReloaded:o},t)),t&&k("plugins",(0,r.jsx)(pp,{embedded:!0,cwd:t,sessionId:n,trust:c,onClose:l,onReloaded:o},t)),k("mcp",(0,r.jsx)(g8,{embedded:!0,cwd:t,trust:c,onTrustProject:u,onProjectTrustChanged:p,onClose:l},t??""))]})]})})}let xy="project-trust-mcp-status";function xw(e){let{cwd:t,busy:n,error:s,onCancel:l,onConfirm:o,onStatus:a}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(a);return(0,i.useEffect)(()=>{u.current=a},[a]),(0,i.useEffect)(()=>{let e=!0,n=!1;c({state:"loading"});let r=new AbortController,i=window.setTimeout(()=>{n=!0,r.abort()},1e4);return fetch(`/api/project-trust?cwd=${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"}).then(async t=>{let n=await t.json();if(!e)return;let r=function(e,t,n){let r=Array.isArray(n.mcpServers)?{mcpServers:n.mcpServers,...n.mcpFile?{mcpFile:n.mcpFile}:{},...void 0!==n.mcpError?{mcpError:n.mcpError}:{}}:void 0;if(e&&!n.error&&r&&"boolean"==typeof n.requiresTrust){let e;return{state:"loaded",listing:r,status:(e={requiresTrust:n.requiresTrust,trusted:n.trusted,decision:n.decision,inherited:n.inherited},void 0!==n.decisionPath&&(e.decisionPath=n.decisionPath),void 0!==n.decisionError&&(e.decisionError=n.decisionError),e)}}return"trust-unreadable"===n.reason&&r?{state:"loaded",listing:r,statusError:n.error??`HTTP ${t}`}:{state:"failed",error:n.error??`HTTP ${t}`,reason:n.reason}}(t.ok,t.status,n);c(r),"loaded"===r.state&&r.status&&u.current?.(r.status)}).catch(t=>{e&&c(n?{state:"failed",timedOut:!0}:{state:"failed",error:t instanceof Error?t.message:String(t)})}).finally(()=>window.clearTimeout(i)),()=>{e=!1,window.clearTimeout(i),r.abort()}},[t]),(0,r.jsx)(xj,{cwd:t,busy:n,error:s,listing:d,onCancel:l,onConfirm:o})}function xj(e){let{cwd:t,busy:n,error:s,listing:l,onCancel:o,onConfirm:a}=e,{t:d}=(0,e0.s)(),c="loading"===l.state,u="loaded"===l.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(l.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),f=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current=n,f.current=o},[n,o]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||f.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eE(e)||(e.preventDefault(),n()))},e.addEventListener("keydown",i,!0),s=()=>e.removeEventListener("keydown",i,!0),()=>{s(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,r.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-description",tabIndex:-1,className:"project-trust-dialog",children:[(0,r.jsxs)("div",{className:"project-trust-body",children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"project-trust-icon",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{className:"project-trust-content",children:[(0,r.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:d("trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:d("trust.dialogBody")}),(0,r.jsx)("code",{className:"project-trust-path",children:py(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===l.state&&void 0!==l.statusError&&(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:d("mcp.reason.trust-unreadable")}),(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:py(l.statusError)})]}),(0,r.jsx)(xS,{listing:l})]})]}),s&&(0,r.jsx)(xk,{error:s}),(0,r.jsxs)("div",{className:"project-trust-footer",children:[(0,r.jsx)("button",{type:"button",className:"project-trust-button",onClick:o,disabled:n,children:d(u?"trust.close":"trust.cancel")}),!u&&(0,r.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:a,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?xy:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function xk(e){let{error:t}=e,{t:n}=(0,e0.s)(),i=void 0!==t.reason&&"internal"!==t.reason;return(0,r.jsxs)("div",{role:"alert",className:"project-trust-error",children:[n(i?`mcp.reason.${t.reason}`:"trust.trustFailed"),!i&&(0,r.jsx)("code",{className:"project-trust-error-detail",children:py(t.error)})]})}function xS(e){let{listing:t}=e,{t:n}=(0,e0.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:xy,role:"status",className:"project-trust-mcp-status",children:n("trust.mcp.loading")});if("failed"===t.state||void 0!==t.listing.mcpError||!t.listing.mcpFile){let e;e="failed"===t.state?t.reason&&"internal"!==t.reason?n(`mcp.reason.${t.reason}`):t.error:t.listing.mcpError;let i="failed"===t.state&&t.timedOut;return(0,r.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(i?"trust.mcp.timedOut":"trust.mcp.loadFailed")}),e&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:py(e)})]})}let{mcpFile:i,mcpServers:s}=t.listing;return i.exists||0!==i.problems.length?(0,r.jsxs)("section",{className:"project-trust-mcp","aria-labelledby":"project-trust-mcp-title",children:[(0,r.jsx)("div",{id:"project-trust-mcp-title",className:"project-trust-mcp-title",children:n("trust.mcp.title")}),s.length>0&&(0,r.jsx)("p",{className:"project-trust-mcp-intro",children:n("trust.mcp.intro")}),(0,r.jsx)(xC,{file:i}),0===s.length&&0===i.problems.length&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.none")}),s.some(e=>!e.validated)&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.unchecked")}),s.length>0&&(0,r.jsx)("ul",{className:"project-trust-mcp-list",children:s.map(e=>(0,r.jsx)(xE,{server:e},e.name))})]}):null}function xC(e){let{file:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=pM(e,t.realPath);return(0,r.jsxs)("div",{className:"project-trust-mcp-problem",children:[(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(`mcp.fileProblem.${e.reason}`)}),i&&(0,r.jsx)("code",{className:"project-trust-mcp-detail",children:i})]},e.reason)})})}function xN(e){let{fields:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=pN(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function x$(e){let{server:t}=e,{t:n}=(0,e0.s)();return(0,r.jsx)(r.Fragment,{children:pI(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=pN(i);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n("mcp.server.variableIn",{variable:t,field:n(s.key,s.params)})},`${t}\0${i.kind}\0${i.name??""}`)})})}function xE(e){let t,{server:n}=e,{t:i}=(0,e0.s)(),s=pS(n),l=void 0===n.invalidError;return(0,r.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,r.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,r.jsx)("span",{className:"project-trust-mcp-server-name",children:py(n.name)}),n.transport&&(0,r.jsx)("span",{className:"project-trust-mcp-tag",children:i(`mcp.transport.${n.transport}`)})]}),void 0!==s&&(0,r.jsx)("code",{className:"project-trust-mcp-target",children:s}),void 0!==n.cwd&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("trust.mcp.cwd",{path:py(n.cwd)})}),pC(n)&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:py(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(xN,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),l&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(xN,{fields:n.commandFields})]}),l&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(p$(n))," ",(0,r.jsx)(x$,{server:n})]}),n.replacesGlobal&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i("mcp.server.replacesGlobal")}),n.override&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-warning",children:i((t=pE(n.override.keys)).key,t.params)}),n.masked&&(0,r.jsx)("p",{className:"project-trust-mcp-line is-dim",children:i("mcp.server.masked")})]})}function xI(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function xM(e){let t=e,n=t.branchPreview,r=xI(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&xI(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function xT(e){if(e.length>1)return!0;let t=[...e];for(;t.length>0;){let e=t.pop();if(e.children.length>1)return!0;for(let n of e.children)t.push(n)}return!1}function xR(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:l,onSelect:o}=e,{node:a,skipped:d,branchPreview:c,labelEntry:u}=xM(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),f=c?.text??function(e){if("message"===e.type&&xI(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(u),m=c?c.role??null:xI(u)?u.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:o?"pointer":"default"},onClick:o?()=>o(a.entry.id):void 0,children:[l.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:s?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:p?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:p?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),d>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",d]}),(0,r.jsx)("span",{style:{fontSize:11,color:p?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:p?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:f})]}),a.children.map((e,t)=>(0,r.jsx)(xR,{node:e,activePathIds:n,depth:i+1,isLast:t===a.children.length-1,parentLines:[...l,!s],onSelect:o},e.entry.id))]})}function xA(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:l,containerRef:o,open:a,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:f}=(0,e0.s)(),[m,g]=(0,i.useState)(!1),x=void 0!==a?a:m,v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!l)return;let e=o?.current??v.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,l,o]);let w=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(t,n),[t,n]),j=(0,i.useCallback)(e=>{s(e)},[s]),k=h?void 0:j,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:f("i18n.branchesLockedWhileRunning")}),C=c?xT(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=xM(e[0]).node;return t.children.length>1?t.children:[]}(t),$=!C&&N.length>0,E=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:$?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return l?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:v,onClick:()=>d?d():g(e=>!e),style:{display:p?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:x?"var(--bg-selected)":"none",border:"none",borderTop:x?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:x?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":x,children:[E,!u&&(0,r.jsx)("span",{children:f("i18n.branches")})]}),x&&b&&(0,r.jsx)("div",{style:{position:"fixed",top:b.top,left:b.left,width:b.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:$?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(xR,{node:e,activePathIds:w,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:k},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[E,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),I]}),x&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:$?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(xR,{node:e,activePathIds:w,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:k},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??f("i18n.noBranches")})})]})}function xL(e){let{loading:t,prompt:n,translate:i}=e;return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":i("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:n?(0,r.jsx)("div",{className:"system-prompt-text",children:n}):(0,r.jsx)("div",{className:"system-prompt-empty",children:i(""===n?"system.empty":t?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
12
12
  .system-prompt-panel {
13
13
  display: flex;
14
14
  height: min(600px, 75dvh);