@mcy2015/pi-web 0.16.1 → 0.16.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +10 -10
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/files/page_client-reference-manifest.js +1 -1
- package/.next/server/app/files.html +1 -1
- package/.next/server/app/files.rsc +2 -2
- package/.next/server/app/files.segments/_full.segment.rsc +2 -2
- package/.next/server/app/files.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/files.segments/files/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +3 -3
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +2 -2
- package/.next/server/app/login.segments/_full.segment.rsc +2 -2
- package/.next/server/app/login.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/page.js +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/share/[code]/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +10 -10
- package/.next/server/chunks/2243.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/preview-props.json +3 -3
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/app/{layout-758939af8df39e01.js → layout-e725924d5aadb8f5.js} +1 -1
- package/.next/static/chunks/app/{page-34a091a0f6b601f1.js → page-01ae0e9122c422bc.js} +2 -2
- package/.next/trace +206 -207
- package/.next/trace-build +1 -1
- package/package.json +1 -1
- package/public/provider-icons.svg +6 -0
- /package/.next/static/{wUQnhKVIClGFbOCYLjUUd → ycDiED0yO0fh3fNkTtVzf}/_buildManifest.js +0 -0
- /package/.next/static/{wUQnhKVIClGFbOCYLjUUd → ycDiED0yO0fh3fNkTtVzf}/_ssgManifest.js +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>h,getPresetFromTools:()=>p,kU:()=>a,kt:()=>d,sn:()=>u,xG:()=>m});let r="configured",i=["configured","none","read-only","default","full"],s=[],a=["read","grep","find","ls"],o=["read","bash","edit","write"],l=["bash","read","edit","write","grep","find","ls"],d=["read","grep","find","ls","edit","write","bash"],c=new Set([...l,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function p(e){return h(e.filter(e=>e.active).map(e=>e.name))}function h(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...a].sort().join(",")?"read-only":t===[...o].sort().join(",")?"default":t===[...l].sort().join(",")?"full":"default"}function m(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...a]:"full"===e?[...l]:[...o]}},76853:(e,t,n)=>{Promise.resolve().then(n.bind(n,81144)),Promise.resolve().then(n.bind(n,21278))},81144:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gh});var r=n(95155),i=n(12115),s=n(73321);let a=null;function o(e,t,n){if(e.name&&"Side chat"!==e.name)return e.name;let r=n.filter(e=>e.relation?.kind==="side").sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id)).findIndex(t=>t.id===e.id);return r<0?t:`${t} ${r+1}`}function l(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e){let t=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,a=null;for(;;){if(n.has(s)){a=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(!l(r.relation)){a=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,a)}return n}(e),n=new Map;for(let t of e)l(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!l(r.relation))continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}function c(e,t){return t?d(e).find(e=>e.root.id===t||e.subagents.some(e=>e.id===t))??null:null}function u(e,t){return e.filter(e=>t.has(e.id)).length}function p(e){return`?session=${encodeURIComponent(e)}`}let h="pi-web:last-open-by-workspace";function m(){try{return window.localStorage}catch{return null}}function g(e){let t=e.getItem(h);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:m();if(t)try{let n=g(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(h):t.setItem(h,JSON.stringify(n))}catch{}}function x(e){return e.projectKey??e.projectRoot??e.cwd}function b(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=x(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let v=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,y=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function k(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function j(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function w(e){return"string"==typeof e&&v.test(e)}function S(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let C=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function N(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?C.test(t)||[...t].length>80?void 0:t:null}let I=new TextEncoder;function $(e){return I.encode(JSON.stringify(e)).length+1}function E(e){let t=1;for(let n of e)t+=$(n);return t}function T(e,t){return e<=1e3&&t<=262144}function M(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=$(r);n+e>262144||(t.push(r),n+=e)}return t}function R(e,t){return I.encode(JSON.stringify(e)).length+I.encode(JSON.stringify(t)).length+2}function A(e,t){return e<=1e3&&t<=262144}function L(){return{version:1,revision:0,sessions:{},projects:{}}}function P(e){let t=Object.entries(e);return t.length<=2e3?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,2e3)))}function z(e,t,n){let r=y(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 O(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 W(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 F(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 D={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}},B="pinned";function _(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function H(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function U(e,t){return e===t?0:e>t?-1:1}function q(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function K(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function Z(e,t,n){let r=H(_(t,e.root.id)?.archivedAt);if(null===r||K(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function V(e,t,n){return null!==H(_(t,e.root.id)?.pinnedAt)&&!Z(e,t,n)}function J(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 G(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 Y(e,t){var n;return{running:K(e,t.runningIds),awaiting:!!t.awaitingIds&&K(e,t.awaitingIds),unread:K(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function X(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&K(s,t.awaitingIds)?r++:K(s,t.runningIds)&&n++,K(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function Q(e){return x(e.root)}function ee(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=Q(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,a=r.get(i);if(a)return a;let o=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,l=null!==t&&t.key===i,d=n.get(i)??(l?t.root:void 0)??o?.root??i,c=((s=e.projectNames)&&y(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??J(d),customName:c,pinned:void 0!==o,current:l};return r.set(i,u),u}}}function et(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:Y(e,r)}}function en(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=Y(e,r);return i.running||i.unread||i.selected}),s=t+n,a=0,o=e.filter((e,n)=>n<t||!!i[n]||n<s&&(a++,!0)),l=Math.max(t,Math.min(s,e.length));for(let t=0;l<e.length&&t<20;l++)!i[l]&&t++;return{visible:o,revealed:a,nextShown:l-t}}function er(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 ei(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function es(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function ea(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(Q(n)!==t||Z(n,e.uiState,e.runningIds)||V(n,e.uiState,e.runningIds))continue;let r=Y(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let a=Date.parse(n.latestModified);Number.isNaN(a)||a>=i||s.push(n.root.id)}return s}function eo(e,t){let n=[],r=0;for(let i of d(e.sessions))if(Q(i)===t&&!i.root.transient){if(K(i,e.runningIds)||e.awaitingIds&&K(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function el(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),a=i["up"===n?s-1:s+1];return a?{anchorKey:a.key,position:"up"===n?"before":"after"}:null}function ed(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],a=e[t+1];return"start"===i?s===n?null:s:s>=n&&a<=n+r?null:"nearest"===i&&a>n&&s<n+r?s<n||a-s>r?s:a-r:Math.max(0,s-Math.max(0,(r-(a-s))/2))}var ec=n(23579);async function eu(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 ep(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function eh(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:ep(e)}let em=/ · [0-9a-f]{4}$/;function eg(e){let t=em.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function ef(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function ex(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eb(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 ev(e){let t=e.map(e=>({choice:e,name:e.alias??J(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?J(t.slice(0,r)):null}})}let ey={awaiting:"#d97706",unread:"#0891b2"};function ek(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let ej=null,ew=null,eS=new Map;function eC(){return[...document.querySelectorAll('link[rel="icon"]')]}async function eN(e,t){let n=await (!ew&&(ew=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),ew);if(!n||ej!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,a=s?56:42,o=192-a-10,l=a+10;if(i.beginPath(),i.arc(o,l,a,0,2*Math.PI),i.fillStyle=ey[e.kind],i.fill(),i.lineWidth=10,i.strokeStyle="#ffffff",i.stroke(),s&&(i.fillStyle="#ffffff",i.font=`bold ${e.count>9?56:68}px system-ui, sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(e.count),o,l+4)),ej!==t)return;let d=r.toDataURL("image/png");for(let e of eC())e.href=d}function eI(e){return e.isComposing||229===e.keyCode}function e$(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}var eE=n(16913);let eT="pi-web:unread-session-ids";function eM(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function eR(e){let t,n=new Map;if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(Array.isArray(t))for(let e of t)"string"==typeof e&&n.set(e,0);else if("object"==typeof t&&null!==t)for(let[e,r]of Object.entries(t))eM(r)&&n.set(e,r);return n}function eA(e,t){if(!t||0===e.size)return e;let n=null;for(let[i,s]of e){var r;void 0!==(r=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0)&&r>=s&&(n??=new Map(e)).delete(i)}return n??e}let eL=["pointerdown","keydown","wheel","touchstart"],eP=null,ez=0,eO=null;function eW(){return"u">typeof document&&"visible"===document.visibilityState&&document.hasFocus()}function eF(){return eP??=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12e4,r=null,i=!1,s=new Set,a=e=>null!==r&&e-r<n,o=t=>{let n=e()&&a(t),r=n&&!i;if(i=n,r)for(let e of[...s])try{e()}catch(e){console.error(e)}};return{noteInput(){let e=t();a(e)||(i=!1),r=e,o(e)},notePageChange(){let e=t();a(e)||(i=!1),o(e)},isAttended:()=>e()&&a(t()),onAttended:e=>(s.add(e),()=>s.delete(e))}}(eW,()=>performance.now())}function eD(){return 0!==ez&&eF().isAttended()}let eB="pi-web:sidebar-files-placement",e_="below";function eH(){try{var e;return e=window.localStorage.getItem(eB),"tab"===e?"tab":e_}catch{return e_}}let eU=null,eq=new Set;function eK(){return null===eU&&(eU=eH()),eU}function eZ(){eq.forEach(e=>e())}function eV(e){if(null!==e.key&&e.key!==eB)return;let t=eH();t!==eU&&(eU=t,eZ())}function eJ(e){return 0===eq.size&&(window.addEventListener("storage",eV),eU=eH()),eq.add(e),()=>{eq.delete(e),0===eq.size&&window.removeEventListener("storage",eV)}}function eG(e){if(e!==eK()){eU=e;try{window.localStorage.setItem(eB,e)}catch{}eZ()}}function eY(){return(0,i.useSyncExternalStore)(eJ,eK,()=>e_)}var eX=n(21278),eQ=n(31590),e0=n(12545);function e1(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,a=()=>{null!==s&&(clearTimeout(s),s=null)},o=()=>{n&&(a(),n.classList.add("scrollbar-visible"))},l=()=>{n&&(a(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{o(),l()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",o),n.addEventListener("pointerleave",l),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",o),n?.removeEventListener("pointerleave",l),n?.removeEventListener("scroll",d),a(),n?.classList.remove("scrollbar-visible")}},[t,e])}let e2="/api/sessions/ui-state";async function e4(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 e8(e){return e instanceof Error?e.message:String(e)}async function e6(e){if(!e.ok)throw Error(await e4(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!k(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!k(e.sessions)||void 0!==e.projects&&!k(e.projects))return null;let t=L(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!w(r))continue;let e=function(e){if(!k(e))return null;let t={};return j(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),j(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(!S(n))continue;let e=k(r)&&j(r.pinnedAt)&&S(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=M(e.projectOrder.filter(e=>!(!S(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(k(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=N(s);if(!S(t)||"string"!=typeof e)continue;let a=R(t,e);A(r+1,i+a)&&(n[t]=e,r++,i+=a)}r>0&&(t.projectNames=n)}if(k(e.readAt)){let n={};for(let[t,r]of Object.entries(e.readAt))w(t)&&j(r)&&(n[t]=r);let r=P(n);Object.keys(r).length>0&&(t.readAt=r)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function e3(){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]),a=(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:a,end:s}}var e5=n(47650);let e9={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},e7={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},te={padding:"6px 16px",borderRadius:6,fontSize:13},tt={...te,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},tn={...te,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function tr(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 ti(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 ts(){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 ta(){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 to(e){let{onCancel:t,onSelect:n,initialPath:s,busy:a=!1,error:o}=e,{t:l}=(0,eX.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(s??""),[x,b]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(""),[E,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),P=(0,i.useRef)(null),z=(0,i.useRef)(!1),O=(0,i.useCallback)(async e=>{S(!0),j(null);try{let t=await tr(e),n=t.path??e??"/";return p(n),m(t.parentPath??null),f(n),b(t.directories??[]),y(t.drives??null),n}catch(e){return j(e instanceof Error?e.message:String(e)),null}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),O(s||void 0)},[s,O]),(0,i.useEffect)(()=>(z.current=!0,()=>{z.current=!1}),[]),(0,i.useEffect)(()=>{(k||o)&&P.current?.focus()},[k,o]);let W=()=>{M||(N(!1),$(""),T(null))},F=async()=>{let e=I.trim();if(u&&e&&!M){R(!0),T(null);try{let t=await ti(u,e);N(!1),$(""),await O(t)}catch(e){T(e instanceof Error?e.message:String(e))}finally{R(!1)}}},D=g.trim(),B=D!==u,_=!!D&&!a&&!w,H=!!u&&!B&&!a&&!w,U=!!h||/^[a-zA-Z]:[\\/]?$/.test(u),q=async()=>{let e=B?await O(D):u;e&&z.current&&n(e)};return d?(0,e5.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!a&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Escape"!==e.key||a||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:{...e9,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:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:a,title:l("i18n.close"),"aria-label":l("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:a?"default":"pointer",opacity:a?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&O(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 O(h??void 0),disabled:w||!U,title:l("directoryPicker.goToParent"),"aria-label":l("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:U?"pointer":"default",opacity:U?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:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{ref:P,className:"directory-picker-path",id:"directory-path",type:"text",value:g,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{f(e.target.value),j(null)},style:{...e7,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!g.trim(),title:l("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:w||!g.trim()?"default":"pointer",opacity:w||!g.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void O(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)(ta,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void O(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)(ts,{}),(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:l("directoryPicker.noSubdirectories")}),(k||o)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:k??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),T(null)},disabled:!H,style:{...tn,marginRight:"auto",opacity:H?1:.6,cursor:H?"pointer":"default"},children:l("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:a,style:{...tn,cursor:a?"default":"pointer"},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>void q(),disabled:!_,title:B&&D?l("directoryPicker.selectTypedPath",{path:D}):l("directoryPicker.selectCurrentDirectory"),style:{...tt,opacity:_?1:.6,cursor:_?"pointer":"default"},children:l(a?"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)"},onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let t=L.current;L.current=!1,t&&e.target===e.currentTarget&&W()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||"Escape"===e.key&&W()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),F()},style:{...e9,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:l("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:l("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:I,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:l("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),T(null)},disabled:M,className:"directory-picker-path",style:{...e7,width:"100%",boxSizing:"border-box"}}),E&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:E}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:M||!I.trim(),style:{...tt,flex:1,opacity:M?.65:1,cursor:M||!I.trim()?"default":"pointer"},children:l(M?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:W,disabled:M,style:{...tn,flex:1,cursor:M?"default":"pointer"},children:l("i18n.cancel")})]})]})]})})]})}),d):null}var tl=n(46599),td=n(65748),tc=n(7834);let tu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function tp(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:tu[Math.floor(n()*tu.length)]}return s}function th(e){let{onWidthChange:t}=e,{t:n}=(0,eX.s)(),[s,a]=(0,i.useState)(!1),o=(0,i.useRef)(null),l="0.16.1",d="1.5.2",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,a=()=>{n(tp(e,i+=1)),i<t&&(s=requestAnimationFrame(a))};return n(tp(e,0)),s=requestAnimationFrame(a),()=>cancelAnimationFrame(s)},[e]),t}(s?`${l??"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:l??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(o.current&&clearTimeout(o.current),o.current=null,s)?a(!1):(a(!0),o.current=setTimeout(()=>{o.current=null,a(!1)},3e3))},children:c})}var tm=n(2730),tg=n(1518);let tf={desktop:32,mobile:48};function tx(e,t,n,r){return Math.hypot(n-e,r-t)}function tb(e){return e.getClientRects().length>0}var tv=n(72451);function ty(e){let t=(0,tg.d)(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function tk(e){return e.nativeEvent.isComposing||229===e.keyCode}function tj(e){let{rows:t,layout:n,emptyLabel:s,loading:a,error:o,renamingRootId:l,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,eX.s)(),m=(0,i.useRef)(e);m.current=e;let g=(0,i.useRef)(null),f=(0,i.useRef)(null),x=(0,i.useRef)(null),b=(0,i.useRef)(null);e1(f);let[v,y]=(0,i.useState)(0),[k,j]=(0,i.useState)(0),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),I=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{null===I.current&&(I.current=requestAnimationFrame(()=>{I.current=null;let e=f.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=f.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!==I.current&&cancelAnimationFrame(I.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let E=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),T=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),M=(0,i.useMemo)(()=>(function(e,t){let n=D[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 a=(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 a=r;for(;a>0&&"spacer"===e[a-1].kind;)a--;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 l=o;for(;l<e.length&&"spacer"===e[l].kind;)l++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[o],gapAbove:t[r]-t[a],gapBelow:t[l]-t[o]}),r=o}return n})(t,n),[t,n]),o=(0,i.useRef)(a);o.current=a;let l=(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),a=i.filter(e=>e!==r);if(0===a.length)return null;let o=a.filter(e=>(e.top+e.bottom)/2<n).length;if(o===s)return null;let l=a[a.length-1],d=Math.max(3,o<a.length?a[o].top-a[o].gapAbove/2:l.bottom+l.gapBelow/2);return o>0?{anchorKey:a[o-1].key,position:"after",lineY:d}:{anchorKey:a[0].key,position:"before",lineY:d}}(o.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=l.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 a=n.getBoundingClientRect().top,o=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:a,maxTop:o}=e,l=Math.max(a,o),d=t-i-r,c=null!==n&&n>=a&&n<=l+r?n:null,u=e=>e>=a&&e<=l,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,a,t+i,l]:[d,c-s-r,a,t+i,c+s,l],m=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 m(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??m(e=>u(e)&&!p(e))??Math.min(l,Math.max(a,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-a}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=l.current;e&&(l.current=null,r(e),window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",b,!0),window.removeEventListener("pointerdown",v,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",k,!0),window.removeEventListener("blur",j),document.removeEventListener("visibilitychange",w),u(null))},a=()=>{let e=l.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=l.current;if(!o||"dragging"!==o.phase)return;let d=s.current.scrollRef.current;if(!d||!tb(d))return void a();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=l.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!tb(t))return void a();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,tf[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())}l.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},m=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!tb(t)||!e.element.isConnected)return void a();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)},g=()=>{let t=l.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 f(e){let t=l.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=tx(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&m(t):n>8&&i();break;case"armed":tx(t.armX,t.armY,e.clientX,e.clientY)>=4&&m(t);break;case"dragging":c()}}function x(e){let n=l.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 b(e){l.current&&e.pointerId===l.current.pointerId&&i()}function v(e){l.current&&e.pointerId!==l.current.pointerId&&a()}function y(e){let t=l.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),a())}function k(e){let t=l.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function j(){i()}function w(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||l.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};l.current=r,window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",b,!0),window.addEventListener("pointerdown",v,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",k,!0),window.addEventListener("blur",j),document.addEventListener("visibilitychange",w),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(g,350))},onTouchMove(e){let t=l.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:a,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=l.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 m=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),g=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?a.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,a]),handlers:p.handlers,onClickCapture:m,onPointerDownCapture:g}}({rows:t,offsets:M,layout:n,enabled:R&&!a,scrollRef:f,innerRef:x,treeRef:g,ghostRef:b,onMove:(e,t,n)=>m.current.onMoveGroup?.(e,t,n)}),P=L.view,z=P?`group:${P.projectKey}`:null,[O,W]=(0,i.useState)(null),F=p&&p.id!==O?p:null,_=F?.rowKey??null,H=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===w||t.key===u||t.key===_||t.key===z||"session"===t.kind&&(t.family.root.id===l||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,w,u,_,z,l,d,c]),U=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),a=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)&&n>0?n:600,l=Number.isFinite(r)&&r>0?r:0,d=a-l,c=a+o+l,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 m=u,g=[];for(let e=h;e<m;e++)g.push(e);if(0===i.length)return g;let f=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=m));return 0===f.length?g:[...new Set([...g,...f])].sort((e,t)=>e-t)}(M,v,k,240,H),[a,M,v,k,H]),q=(0,i.useRef)(null),K=(0,i.useRef)(null),Z=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");q.current={rowKey:e,fallbackKey:t===B?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?m.current.onShowMore(t):m.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;q.current=null;let n=f.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=ed(M,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,M]);let V=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!F)return;let e=t.findIndex(e=>e.key===F.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"}}(V.current,F,e>=0,Date.now());if(V.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=f.current;if(t&&t.getClientRects().length>0){let n=ed(M,e,t.scrollTop,t.clientHeight,F.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}F.takeFocusFrom&&(K.current={rowKey:F.rowKey,fallbackKey:F.rowKey,tries:0,takeFocusFrom:F.takeFocusFrom})}W(F.id),m.current.onRevealHandled?.(F.id)}},[F,t,M]),(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=f.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||"archive-group"===e.kind),G=!a&&!o&&null!==s&&!J,Y=P?.source??null,X=P?.drop?.lineY??null,Q=P?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===P.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:g,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[a&&(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}),G&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:f,className:"session-tree-scroll scrollbar-subtle",onScroll:$,onFocus:E,onBlur:T,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!a&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:M[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=M[e],a=M[e+1]-s,o=i.key===u;if("session"===i.kind)return(0,r.jsx)(tS,{row:i,layout:n,top:s,height:a,now:C,renaming:i.family.root.id===l,confirming:i.family.root.id===c,menuOpen:o,handlers:m},i.key);if("archive-group"===i.kind)return(0,r.jsx)(tT,{row:i,top:s,height:a,menuOpen:o,handlers:m},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(t$,{row:i,top:s,height:a,menuOpen:o,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:P?.projectKey===i.project.key?P.phase:null,drag:L.handlers,handlers:m},i.key)}return(0,r.jsx)(tE,{row:i,top:s,height:a,handlers:m,onMoreAction:Z},i.key)}),Y&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:Y.top,height:Y.bottom-Y.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:b,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function tw(e,t){return{top:e,height:t}}let tS=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:a,height:o,now:l,renaming:d,confirming:c,menuOpen:u,handlers:h}=e,{locale:m,t:g}=(0,eX.s)(),{family:f,context:x,status:b}=i,v=f.root,y=ty(v),k=new Date(l),j=["session-tree-row session-tree-session",b.selected?"is-selected":"",b.running?"is-running":"","archive"===x?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:j,style:tw(a,o),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||tk(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(tN,{label:g("sidebar.deleteSession",{title:e}),deleteLabel:g("sidebar.delete"),cancelLabel:g("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(f,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:j,style:tw(a,o),"data-row-key":i.key,children:(0,r.jsx)(tC,{initialValue:y,label:g("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(f,e),onCancel:()=>h.current.onRenameCancel()})});let w=v.isWorktree&&v.branch?v.branch:null,S=v.name&&v.relation?.kind==="fork"?eg(v.name):null,C=v.detailsPending?"…":g("sidebar.messagesCount",{count:v.messageCount}),N=`${y}
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>h,getPresetFromTools:()=>p,kU:()=>a,kt:()=>d,sn:()=>u,xG:()=>m});let r="configured",i=["configured","none","read-only","default","full"],s=[],a=["read","grep","find","ls"],o=["read","bash","edit","write"],l=["bash","read","edit","write","grep","find","ls"],d=["read","grep","find","ls","edit","write","bash"],c=new Set([...l,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function p(e){return h(e.filter(e=>e.active).map(e=>e.name))}function h(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...a].sort().join(",")?"read-only":t===[...o].sort().join(",")?"default":t===[...l].sort().join(",")?"full":"default"}function m(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...a]:"full"===e?[...l]:[...o]}},76853:(e,t,n)=>{Promise.resolve().then(n.bind(n,81144)),Promise.resolve().then(n.bind(n,21278))},81144:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gh});var r=n(95155),i=n(12115),s=n(73321);let a=null;function o(e,t,n){if(e.name&&"Side chat"!==e.name)return e.name;let r=n.filter(e=>e.relation?.kind==="side").sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id)).findIndex(t=>t.id===e.id);return r<0?t:`${t} ${r+1}`}function l(e){return e?.kind==="subagent"||e?.kind==="side"}function d(e){let t=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,a=null;for(;;){if(n.has(s)){a=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(!l(r.relation)){a=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,a)}return n}(e),n=new Map;for(let t of e)l(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!l(r.relation))continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}function c(e,t){return t?d(e).find(e=>e.root.id===t||e.subagents.some(e=>e.id===t))??null:null}function u(e,t){return e.filter(e=>t.has(e.id)).length}function p(e){return`?session=${encodeURIComponent(e)}`}let h="pi-web:last-open-by-workspace";function m(){try{return window.localStorage}catch{return null}}function g(e){let t=e.getItem(h);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function f(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:m();if(t)try{let n=g(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(h):t.setItem(h,JSON.stringify(n))}catch{}}function x(e){return e.projectKey??e.projectRoot??e.cwd}function b(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=x(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(e=>{let[t,{root:n}]=e;return{key:t,root:n}})}let v=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,y=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function k(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function j(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function w(e){return"string"==typeof e&&v.test(e)}function S(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let C=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function N(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?C.test(t)||[...t].length>80?void 0:t:null}let I=new TextEncoder;function $(e){return I.encode(JSON.stringify(e)).length+1}function E(e){let t=1;for(let n of e)t+=$(n);return t}function T(e,t){return e<=1e3&&t<=262144}function M(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=$(r);n+e>262144||(t.push(r),n+=e)}return t}function R(e,t){return I.encode(JSON.stringify(e)).length+I.encode(JSON.stringify(t)).length+2}function A(e,t){return e<=1e3&&t<=262144}function L(){return{version:1,revision:0,sessions:{},projects:{}}}function P(e){let t=Object.entries(e);return t.length<=2e3?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,2e3)))}function z(e,t,n){let r=y(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 O(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 W(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 F(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 D={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}},B="pinned";function _(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function H(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function U(e,t){return e===t?0:e>t?-1:1}function q(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function K(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function Z(e,t,n){let r=H(_(t,e.root.id)?.archivedAt);if(null===r||K(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function V(e,t,n){return null!==H(_(t,e.root.id)?.pinnedAt)&&!Z(e,t,n)}function J(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 G(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 Y(e,t){var n;return{running:K(e,t.runningIds),awaiting:!!t.awaitingIds&&K(e,t.awaitingIds),unread:K(e,t.unreadIds),selected:!!(n=t.selectedSessionId)&&(e.root.id===n||e.subagents.some(e=>e.id===n)),transient:!0===e.root.transient}}function X(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&K(s,t.awaitingIds)?r++:K(s,t.runningIds)&&n++,K(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function Q(e){return x(e.root)}function ee(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=Q(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s,a=r.get(i);if(a)return a;let o=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,l=null!==t&&t.key===i,d=n.get(i)??(l?t.root:void 0)??o?.root??i,c=((s=e.projectNames)&&y(s,i)?s[i]:void 0)??null,u={key:i,root:d,name:c??J(d),customName:c,pinned:void 0!==o,current:l};return r.set(i,u),u}}}function et(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:Y(e,r)}}function en(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=Y(e,r);return i.running||i.unread||i.selected}),s=t+n,a=0,o=e.filter((e,n)=>n<t||!!i[n]||n<s&&(a++,!0)),l=Math.max(t,Math.min(s,e.length));for(let t=0;l<e.length&&t<20;l++)!i[l]&&t++;return{visible:o,revealed:a,nextShown:l-t}}function er(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 ei(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function es(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function ea(e,t,n,r){let i=r-n,s=[];for(let n of d(e.sessions)){if(Q(n)!==t||Z(n,e.uiState,e.runningIds)||V(n,e.uiState,e.runningIds))continue;let r=Y(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let a=Date.parse(n.latestModified);Number.isNaN(a)||a>=i||s.push(n.root.id)}return s}function eo(e,t){let n=[],r=0;for(let i of d(e.sessions))if(Q(i)===t&&!i.root.transient){if(K(i,e.runningIds)||e.awaitingIds&&K(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function el(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),a=i["up"===n?s-1:s+1];return a?{anchorKey:a.key,position:"up"===n?"before":"after"}:null}function ed(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],a=e[t+1];return"start"===i?s===n?null:s:s>=n&&a<=n+r?null:"nearest"===i&&a>n&&s<n+r?s<n||a-s>r?s:a-r:Math.max(0,s-Math.max(0,(r-(a-s))/2))}var ec=n(23579);async function eu(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 ep(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function eh(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:ep(e)}let em=/ · [0-9a-f]{4}$/;function eg(e){let t=em.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function ef(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function ex(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function eb(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 ev(e){let t=e.map(e=>({choice:e,name:e.alias??J(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?J(t.slice(0,r)):null}})}let ey={awaiting:"#d97706",unread:"#0891b2"};function ek(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let ej=null,ew=null,eS=new Map;function eC(){return[...document.querySelectorAll('link[rel="icon"]')]}async function eN(e,t){let n=await (!ew&&(ew=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),ew);if(!n||ej!==t)return;let r=document.createElement("canvas");r.width=192,r.height=192;let i=r.getContext("2d");if(!i)return;i.clearRect(0,0,192,192),i.drawImage(n,0,0,192,192);let s=e.count>1,a=s?56:42,o=192-a-10,l=a+10;if(i.beginPath(),i.arc(o,l,a,0,2*Math.PI),i.fillStyle=ey[e.kind],i.fill(),i.lineWidth=10,i.strokeStyle="#ffffff",i.stroke(),s&&(i.fillStyle="#ffffff",i.font=`bold ${e.count>9?56:68}px system-ui, sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(e.count),o,l+4)),ej!==t)return;let d=r.toDataURL("image/png");for(let e of eC())e.href=d}function eI(e){return e.isComposing||229===e.keyCode}function e$(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}var eE=n(16913);let eT="pi-web:unread-session-ids";function eM(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function eR(e){let t,n=new Map;if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(Array.isArray(t))for(let e of t)"string"==typeof e&&n.set(e,0);else if("object"==typeof t&&null!==t)for(let[e,r]of Object.entries(t))eM(r)&&n.set(e,r);return n}function eA(e,t){if(!t||0===e.size)return e;let n=null;for(let[i,s]of e){var r;void 0!==(r=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0)&&r>=s&&(n??=new Map(e)).delete(i)}return n??e}let eL=["pointerdown","keydown","wheel","touchstart"],eP=null,ez=0,eO=null;function eW(){return"u">typeof document&&"visible"===document.visibilityState&&document.hasFocus()}function eF(){return eP??=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12e4,r=null,i=!1,s=new Set,a=e=>null!==r&&e-r<n,o=t=>{let n=e()&&a(t),r=n&&!i;if(i=n,r)for(let e of[...s])try{e()}catch(e){console.error(e)}};return{noteInput(){let e=t();a(e)||(i=!1),r=e,o(e)},notePageChange(){let e=t();a(e)||(i=!1),o(e)},isAttended:()=>e()&&a(t()),onAttended:e=>(s.add(e),()=>s.delete(e))}}(eW,()=>performance.now())}function eD(){return 0!==ez&&eF().isAttended()}let eB="pi-web:sidebar-files-placement",e_="below";function eH(){try{var e;return e=window.localStorage.getItem(eB),"tab"===e?"tab":e_}catch{return e_}}let eU=null,eq=new Set;function eK(){return null===eU&&(eU=eH()),eU}function eZ(){eq.forEach(e=>e())}function eV(e){if(null!==e.key&&e.key!==eB)return;let t=eH();t!==eU&&(eU=t,eZ())}function eJ(e){return 0===eq.size&&(window.addEventListener("storage",eV),eU=eH()),eq.add(e),()=>{eq.delete(e),0===eq.size&&window.removeEventListener("storage",eV)}}function eG(e){if(e!==eK()){eU=e;try{window.localStorage.setItem(eB,e)}catch{}eZ()}}function eY(){return(0,i.useSyncExternalStore)(eJ,eK,()=>e_)}var eX=n(21278),eQ=n(31590),e0=n(12545);function e1(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,a=()=>{null!==s&&(clearTimeout(s),s=null)},o=()=>{n&&(a(),n.classList.add("scrollbar-visible"))},l=()=>{n&&(a(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},d=()=>{o(),l()},c=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(c);return}n.addEventListener("pointerenter",o),n.addEventListener("pointerleave",l),n.addEventListener("scroll",d)}};return c(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",o),n?.removeEventListener("pointerleave",l),n?.removeEventListener("scroll",d),a(),n?.classList.remove("scrollbar-visible")}},[t,e])}let e2="/api/sessions/ui-state";async function e4(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 e8(e){return e instanceof Error?e.message:String(e)}async function e6(e){if(!e.ok)throw Error(await e4(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!k(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!k(e.sessions)||void 0!==e.projects&&!k(e.projects))return null;let t=L(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!w(r))continue;let e=function(e){if(!k(e))return null;let t={};return j(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),j(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(!S(n))continue;let e=k(r)&&j(r.pinnedAt)&&S(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(Array.isArray(e.projectOrder)){let n=new Set,r=M(e.projectOrder.filter(e=>!(!S(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(k(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=N(s);if(!S(t)||"string"!=typeof e)continue;let a=R(t,e);A(r+1,i+a)&&(n[t]=e,r++,i+=a)}r>0&&(t.projectNames=n)}if(k(e.readAt)){let n={};for(let[t,r]of Object.entries(e.readAt))w(t)&&j(r)&&(n[t]=r);let r=P(n);Object.keys(r).length>0&&(t.readAt=r)}return t}(t.state):null;if(!n)throw Error("Invalid session UI state response");return n}function e3(){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]),a=(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:a,end:s}}var e5=n(47650);let e9={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},e7={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},te={padding:"6px 16px",borderRadius:6,fontSize:13},tt={...te,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},tn={...te,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function tr(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 ti(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 ts(){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 ta(){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 to(e){let{onCancel:t,onSelect:n,initialPath:s,busy:a=!1,error:o}=e,{t:l}=(0,eX.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(s??""),[x,b]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(!0),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(""),[E,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(!1),A=(0,i.useRef)(!1),L=(0,i.useRef)(!1),P=(0,i.useRef)(null),z=(0,i.useRef)(!1),O=(0,i.useCallback)(async e=>{S(!0),j(null);try{let t=await tr(e),n=t.path??e??"/";return p(n),m(t.parentPath??null),f(n),b(t.directories??[]),y(t.drives??null),n}catch(e){return j(e instanceof Error?e.message:String(e)),null}finally{S(!1)}},[]);(0,i.useEffect)(()=>{c(document.body),O(s||void 0)},[s,O]),(0,i.useEffect)(()=>(z.current=!0,()=>{z.current=!1}),[]),(0,i.useEffect)(()=>{(k||o)&&P.current?.focus()},[k,o]);let W=()=>{M||(N(!1),$(""),T(null))},F=async()=>{let e=I.trim();if(u&&e&&!M){R(!0),T(null);try{let t=await ti(u,e);N(!1),$(""),await O(t)}catch(e){T(e instanceof Error?e.message:String(e))}finally{R(!1)}}},D=g.trim(),B=D!==u,_=!!D&&!a&&!w,H=!!u&&!B&&!a&&!w,U=!!h||/^[a-zA-Z]:[\\/]?$/.test(u),q=async()=>{let e=B?await O(D):u;e&&z.current&&n(e)};return d?(0,e5.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onPointerDown:e=>{A.current=e.target===e.currentTarget},onClick:e=>{let n=A.current;A.current=!1,n&&e.target===e.currentTarget&&!a&&t()},onPointerCancel:()=>{A.current=!1},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Escape"!==e.key||a||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:{...e9,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:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:t,disabled:a,title:l("i18n.close"),"aria-label":l("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:a?"default":"pointer",opacity:a?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&O(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 O(h??void 0),disabled:w||!U,title:l("directoryPicker.goToParent"),"aria-label":l("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:U?"pointer":"default",opacity:U?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:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{ref:P,className:"directory-picker-path",id:"directory-path",type:"text",value:g,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{f(e.target.value),j(null)},style:{...e7,minWidth:0,flex:1}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:w||!g.trim(),title:l("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:w||!g.trim()?"default":"pointer",opacity:w||!g.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void O(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)(ta,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void O(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)(ts,{}),(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:l("directoryPicker.noSubdirectories")}),(k||o)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:k??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),T(null)},disabled:!H,style:{...tn,marginRight:"auto",opacity:H?1:.6,cursor:H?"pointer":"default"},children:l("directoryPicker.newDirectory")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:a,style:{...tn,cursor:a?"default":"pointer"},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>void q(),disabled:!_,title:B&&D?l("directoryPicker.selectTypedPath",{path:D}):l("directoryPicker.selectCurrentDirectory"),style:{...tt,opacity:_?1:.6,cursor:_?"pointer":"default"},children:l(a?"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)"},onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let t=L.current;L.current=!1,t&&e.target===e.currentTarget&&W()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||"Escape"===e.key&&W()},children:(0,r.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),F()},style:{...e9,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:l("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:l("directoryPicker.directoryName")}),(0,r.jsx)("input",{id:"new-directory-name",value:I,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:l("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),T(null)},disabled:M,className:"directory-picker-path",style:{...e7,width:"100%",boxSizing:"border-box"}}),E&&(0,r.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:E}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:M||!I.trim(),style:{...tt,flex:1,opacity:M?.65:1,cursor:M||!I.trim()?"default":"pointer"},children:l(M?"directoryPicker.creating":"directoryPicker.create")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:W,disabled:M,style:{...tn,flex:1,cursor:M?"default":"pointer"},children:l("i18n.cancel")})]})]})]})})]})}),d):null}var tl=n(46599),td=n(65748),tc=n(7834);let tu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function tp(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:tu[Math.floor(n()*tu.length)]}return s}function th(e){let{onWidthChange:t}=e,{t:n}=(0,eX.s)(),[s,a]=(0,i.useState)(!1),o=(0,i.useRef)(null),l="0.16.2",d="1.5.2",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,a=()=>{n(tp(e,i+=1)),i<t&&(s=requestAnimationFrame(a))};return n(tp(e,0)),s=requestAnimationFrame(a),()=>cancelAnimationFrame(s)},[e]),t}(s?`${l??"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:l??"0.0.0",pi:d??"0.0.0"}),onClick:()=>{(o.current&&clearTimeout(o.current),o.current=null,s)?a(!1):(a(!0),o.current=setTimeout(()=>{o.current=null,a(!1)},3e3))},children:c})}var tm=n(2730),tg=n(1518);let tf={desktop:32,mobile:48};function tx(e,t,n,r){return Math.hypot(n-e,r-t)}function tb(e){return e.getClientRects().length>0}var tv=n(72451);function ty(e){let t=(0,tg.d)(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function tk(e){return e.nativeEvent.isComposing||229===e.keyCode}function tj(e){let{rows:t,layout:n,emptyLabel:s,loading:a,error:o,renamingRootId:l,renamingProjectKey:d,confirmDeleteRootId:c,activeMenuRowKey:u,reveal:p}=e,{t:h}=(0,eX.s)(),m=(0,i.useRef)(e);m.current=e;let g=(0,i.useRef)(null),f=(0,i.useRef)(null),x=(0,i.useRef)(null),b=(0,i.useRef)(null);e1(f);let[v,y]=(0,i.useState)(0),[k,j]=(0,i.useState)(0),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(()=>Date.now()),I=(0,i.useRef)(null),$=(0,i.useCallback)(()=>{null===I.current&&(I.current=requestAnimationFrame(()=>{I.current=null;let e=f.current;e&&y(e.scrollTop)}))},[]);(0,i.useLayoutEffect)(()=>{let e=f.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!==I.current&&cancelAnimationFrame(I.current)},[]),(0,i.useEffect)(()=>{let e=window.setInterval(()=>N(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let E=(0,i.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;S(t?.getAttribute("data-row-key")??null)},[]),T=(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||S(null)},[]),M=(0,i.useMemo)(()=>(function(e,t){let n=D[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 a=(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 a=r;for(;a>0&&"spacer"===e[a-1].kind;)a--;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 l=o;for(;l<e.length&&"spacer"===e[l].kind;)l++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[o],gapAbove:t[r]-t[a],gapBelow:t[l]-t[o]}),r=o}return n})(t,n),[t,n]),o=(0,i.useRef)(a);o.current=a;let l=(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),a=i.filter(e=>e!==r);if(0===a.length)return null;let o=a.filter(e=>(e.top+e.bottom)/2<n).length;if(o===s)return null;let l=a[a.length-1],d=Math.max(3,o<a.length?a[o].top-a[o].gapAbove/2:l.bottom+l.gapBelow/2);return o>0?{anchorKey:a[o-1].key,position:"after",lineY:d}:{anchorKey:a[0].key,position:"before",lineY:d}}(o.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=l.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 a=n.getBoundingClientRect().top,o=i.getBoundingClientRect(),d=t.offsetHeight,c=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:a,maxTop:o}=e,l=Math.max(a,o),d=t-i-r,c=null!==n&&n>=a&&n<=l+r?n:null,u=e=>e>=a&&e<=l,p=e=>null!==c&&e>c-s-r&&e<c+s,h=null===c?[d,a,t+i,l]:[d,c-s-r,a,t+i,c+s,l],m=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 m(e=>u(e)&&!(e>d&&e<t+i)&&!p(e))??m(e=>u(e)&&!p(e))??Math.min(l,Math.max(a,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-a}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=l.current;e&&(l.current=null,r(e),window.removeEventListener("pointermove",f,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",b,!0),window.removeEventListener("pointerdown",v,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",k,!0),window.removeEventListener("blur",j),document.removeEventListener("visibilitychange",w),u(null))},a=()=>{let e=l.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=l.current;if(!o||"dragging"!==o.phase)return;let d=s.current.scrollRef.current;if(!d||!tb(d))return void a();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=l.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=s.current.scrollRef.current;if(!t||!tb(t))return void a();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,tf[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())}l.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},m=e=>{let t=s.current.scrollRef.current,n=s.current.treeRef.current;if(!t||!n||!tb(t)||!e.element.isConnected)return void a();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)},g=()=>{let t=l.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 f(e){let t=l.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=tx(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&m(t):n>8&&i();break;case"armed":tx(t.armX,t.armY,e.clientX,e.clientY)>=4&&m(t);break;case"dragging":c()}}function x(e){let n=l.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 b(e){l.current&&e.pointerId===l.current.pointerId&&i()}function v(e){l.current&&e.pointerId!==l.current.pointerId&&a()}function y(e){let t=l.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),a())}function k(e){let t=l.current;if(t){if("pending"===t.phase)return void i();e.preventDefault(),e.stopPropagation()}}function j(){i()}function w(){"hidden"===document.visibilityState&&i()}return{handlers:{onPointerDown(e,t){if(!s.current.enabled||l.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};l.current=r,window.addEventListener("pointermove",f,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",b,!0),window.addEventListener("pointerdown",v,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",k,!0),window.addEventListener("blur",j),document.addEventListener("visibilitychange",w),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(g,350))},onTouchMove(e){let t=l.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:a,teardown:i,updateDrag:c,placeGhost:n}},[]);(0,i.useLayoutEffect)(()=>{let e=l.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 m=(0,i.useCallback)(e=>{let t=d.current;0===t||(d.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),g=(0,i.useCallback)(()=>{d.current=0},[]);return{view:(0,i.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?a.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,a]),handlers:p.handlers,onClickCapture:m,onPointerDownCapture:g}}({rows:t,offsets:M,layout:n,enabled:R&&!a,scrollRef:f,innerRef:x,treeRef:g,ghostRef:b,onMove:(e,t,n)=>m.current.onMoveGroup?.(e,t,n)}),P=L.view,z=P?`group:${P.projectKey}`:null,[O,W]=(0,i.useState)(null),F=p&&p.id!==O?p:null,_=F?.rowKey??null,H=(0,i.useMemo)(()=>{let e=[];return t.forEach((t,n)=>{t.key===w||t.key===u||t.key===_||t.key===z||"session"===t.kind&&(t.family.root.id===l||t.family.root.id===c)?e.push(n):"group"===t.kind&&t.project.key===d&&e.push(n)}),e},[t,w,u,_,z,l,d,c]),U=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),a=Number.isFinite(t)?Math.max(0,t):0,o=Number.isFinite(n)&&n>0?n:600,l=Number.isFinite(r)&&r>0?r:0,d=a-l,c=a+o+l,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 m=u,g=[];for(let e=h;e<m;e++)g.push(e);if(0===i.length)return g;let f=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=m));return 0===f.length?g:[...new Set([...g,...f])].sort((e,t)=>e-t)}(M,v,k,240,H),[a,M,v,k,H]),q=(0,i.useRef)(null),K=(0,i.useRef)(null),Z=(0,i.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");q.current={rowKey:e,fallbackKey:t===B?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?m.current.onShowMore(t):m.current.onShowLess(t)},[]);(0,i.useLayoutEffect)(()=>{let e=q.current;if(!e)return;q.current=null;let n=f.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=ed(M,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,M]);let V=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{if(!F)return;let e=t.findIndex(e=>e.key===F.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"}}(V.current,F,e>=0,Date.now());if(V.current=n.misses,"wait"!==n.action){if("reveal"===n.action){let t=f.current;if(t&&t.getClientRects().length>0){let n=ed(M,e,t.scrollTop,t.clientHeight,F.block);null!==n&&(t.scrollTop=n),y(t.scrollTop)}F.takeFocusFrom&&(K.current={rowKey:F.rowKey,fallbackKey:F.rowKey,tries:0,takeFocusFrom:F.takeFocusFrom})}W(F.id),m.current.onRevealHandled?.(F.id)}},[F,t,M]),(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=f.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||"archive-group"===e.kind),G=!a&&!o&&null!==s&&!J,Y=P?.source??null,X=P?.drop?.lineY??null,Q=P?.phase==="dragging"?t.find(e=>"group"===e.kind&&e.project.key===P.projectKey)?.project??null:null;return(0,r.jsxs)("div",{ref:g,className:`session-tree${"mobile"===n?" is-mobile":""}${Q?" is-group-dragging":""}`,children:[a&&(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}),G&&(0,r.jsx)("div",{className:"session-tree-message",children:s}),(0,r.jsx)("div",{ref:f,className:"session-tree-scroll scrollbar-subtle",onScroll:$,onFocus:E,onBlur:T,onPointerDownCapture:L.onPointerDownCapture,onClickCapture:L.onClickCapture,children:!a&&(0,r.jsxs)("div",{ref:x,className:"session-tree-inner",style:{height:M[t.length]},children:[U.map(e=>{let i=t[e];if("spacer"===i.kind)return null;let s=M[e],a=M[e+1]-s,o=i.key===u;if("session"===i.kind)return(0,r.jsx)(tS,{row:i,layout:n,top:s,height:a,now:C,renaming:i.family.root.id===l,confirming:i.family.root.id===c,menuOpen:o,handlers:m},i.key);if("archive-group"===i.kind)return(0,r.jsx)(tT,{row:i,top:s,height:a,menuOpen:o,handlers:m},i.key);if("group"===i.kind){let e=i.project.key===d;return(0,r.jsx)(t$,{row:i,top:s,height:a,menuOpen:o,renaming:e,canDrag:R&&!e&&A[i.project.pinned?"pinned":"other"]>1,dragPhase:P?.projectKey===i.project.key?P.phase:null,drag:L.handlers,handlers:m},i.key)}return(0,r.jsx)(tE,{row:i,top:s,height:a,handlers:m,onMoreAction:Z},i.key)}),Y&&(0,r.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:Y.top,height:Y.bottom-Y.top}}),null!==X&&(0,r.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:X}})]})}),Q&&(0,r.jsx)("div",{ref:b,className:"session-tree-drag-ghost","aria-hidden":"true",children:(0,r.jsx)("span",{className:"session-tree-group-name",children:Q.name})})]})}function tw(e,t){return{top:e,height:t}}let tS=(0,i.memo)(function(e){let t,n,{row:i,layout:s,top:a,height:o,now:l,renaming:d,confirming:c,menuOpen:u,handlers:h}=e,{locale:m,t:g}=(0,eX.s)(),{family:f,context:x,status:b}=i,v=f.root,y=ty(v),k=new Date(l),j=["session-tree-row session-tree-session",b.selected?"is-selected":"",b.running?"is-running":"","archive"===x?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",d?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=y.slice(0,22)+(y.length>22?"…":"");return(0,r.jsx)("div",{className:j,style:tw(a,o),"data-row-key":i.key,onKeyDown:e=>{"Escape"!==e.key||tk(e)||(e.preventDefault(),e.stopPropagation(),h.current.onDeleteCancel())},children:(0,r.jsx)(tN,{label:g("sidebar.deleteSession",{title:e}),deleteLabel:g("sidebar.delete"),cancelLabel:g("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),h.current.onDeleteConfirm(f,e)},onCancel:e=>{e.stopPropagation(),h.current.onDeleteCancel()}})})}if(d)return(0,r.jsx)("div",{className:j,style:tw(a,o),"data-row-key":i.key,children:(0,r.jsx)(tC,{initialValue:y,label:g("sidebar.rename"),onCommit:e=>h.current.onRenameCommit(f,e),onCancel:()=>h.current.onRenameCancel()})});let w=v.isWorktree&&v.branch?v.branch:null,S=v.name&&v.relation?.kind==="fork"?eg(v.name):null,C=v.detailsPending?"…":g("sidebar.messagesCount",{count:v.messageCount}),N=`${y}
|
|
2
2
|
${C} \xb7 ${(0,tm.fw)(v.modified,m,k)}${w?` \xb7 ⑂ ${w}`:""}`,I="";b.awaiting?(t=(0,r.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":g("sidebar.agentAwaitingInput")}),I=" is-awaiting",n=g("sidebar.agentAwaitingInput")):b.running?(t=(0,r.jsx)(tv.Nl,{size:12,label:g("sidebar.agentRunning")}),I=" is-running",n=g("sidebar.agentRunning")):b.unread?(t=(0,r.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":g("sidebar.newSessionActivity")}),I=" is-unread",n=g("sidebar.newActivity")):t="pinned"===x?(0,r.jsx)("span",{className:"session-tree-project",children:i.project.name}):(0,tm.Rg)(f.latestModified,m,k);let $="desktop"===s&&("archive"===x||!b.running),E=(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}),w&&(0,r.jsxs)("span",{className:"session-tree-branch",children:[(0,r.jsx)(tv.OK,{size:10,className:"session-tree-branch-icon"}),w]}),(0,r.jsx)("span",{className:`session-tree-meta${I}`,title:n,children:t})]});return(0,r.jsxs)("div",{className:j,style:tw(a,o),"data-row-key":i.key,onClick:()=>h.current.onSelectFamily(f),onContextMenu:e=>h.current.onRowContextMenu(i,e),children:[b.transient?(0,r.jsx)("button",{type:"button",className:"session-tree-main",title:N,"aria-current":b.selected?"true":void 0,children:E}):(0,r.jsx)("a",{className:"session-tree-main",href:p(v.id),title:N,"aria-current":b.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(f))},children:E}),!b.transient&&(0,r.jsxs)("span",{className:"session-tree-actions",children:[$&&("archive"===x?(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":g("sidebar.restore"),title:g("sidebar.restore"),onClick:e=>{e.stopPropagation(),h.current.onRestoreFamily(f)},children:(0,r.jsx)(tv.G2,{size:13})}):(0,r.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":g("sidebar.archive"),title:g("sidebar.archive"),onClick:e=>{e.stopPropagation(),h.current.onArchiveFamily(f)},children:(0,r.jsx)(tv.kb,{size:13})})),(0,r.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${u?" is-active":""}`,"aria-label":g("sidebar.moreActions"),title:g("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":u,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)(tv.Z4,{size:14})})]})]})});function tC(e){let{initialValue:t,label:n,maxLength:s,onCommit:a,onCancel:o}=e,[l,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,a(e))};return(0,r.jsx)("input",{ref:c,className:"session-tree-rename",value:l,"aria-label":n,maxLength:s,onChange:e=>d(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!tk(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 tN(e){let{label:t,deleteLabel:n,cancelLabel:s,onConfirm:a,onCancel:o}=e,l=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||l.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:a,children:[(0,r.jsx)(tv.uc,{size:12}),n]}),(0,r.jsx)("button",{ref:l,type:"button",className:"session-tree-confirm-cancel",onClick:o,children:s})]})}function tI(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)(tv.Nl,{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 t$=(0,i.memo)(function(e){let{row:t,top:n,height:s,menuOpen:a,renaming:o,canDrag:l,dragPhase:d,drag:c,handlers:u}=e,{t:p}=(0,eX.s)(),{project:h,expanded:m}=t,g=(0,i.useRef)(null),f=["session-tree-row session-tree-group",h.current?"is-current":"",a?"is-active":"","armed"===d?"is-drag-armed":""].filter(Boolean).join(" ");return((0,i.useEffect)(()=>{let e=g.current;if(!l||!e)return;let t=e=>c.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[l,c]),o)?(0,r.jsx)("div",{ref:g,className:`${f} is-renaming`,style:tw(n,s),"data-row-key":t.key,children:(0,r.jsx)(tC,{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:g,className:f,style:tw(n,s),"data-row-key":t.key,onPointerDown:l?e=>c.onPointerDown(e,h.key):void 0,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":m,title:h.root,onClick:e=>u.current.onToggleGroup(h.key,e.altKey),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${m?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:h.name}),h.pinned&&(0,r.jsx)(tv.ts,{size:10,className:"session-tree-group-pin",label:p("sidebar.pinnedProject")}),!m&&(0,r.jsx)(tI,{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)(tv.c1,{size:13})}),(0,r.jsx)("button",{type:"button",className:`session-tree-group-action${a?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":a,onClick:e=>{e.stopPropagation(),u.current.onGroupMenu(h,e.currentTarget)},children:(0,r.jsx)(tv.Z4,{size:13})})]})]})}),tE=(0,i.memo)(function(e){let{row:t,top:n,height:i,handlers:s,onMoreAction:a}=e,{t:o}=(0,eX.s)(),l=tw(n,i);switch(t.kind){case"pinned-header":return(0,r.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:l,"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)(tv.zp,{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?B:t.projectKey;return(0,r.jsxs)("div",{className:"session-tree-row session-tree-more",style:l,"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=>a(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=>a(t.key,e,"less",n.currentTarget),children:o("sidebar.showLess")})]})}case"group-empty":return(0,r.jsxs)("div",{className:"session-tree-row session-tree-group-empty",style:l,"data-row-key":t.key,children:[(0,r.jsx)("span",{className:"session-tree-group-empty-label",children:o("sidebar.noLiveSessions")}),!t.project.pinned&&(0,r.jsx)("button",{type:"button",className:"session-tree-more-toggle",onClick:()=>s.current.onPinEmptyGroup(t.project),children:o("sidebar.pinToKeep")})]});case"footer-open":return(0,r.jsx)("div",{className:"session-tree-row session-tree-footer",style:l,"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)(tv.YP,{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:l,"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)(tv.kb,{size:12}),(0,r.jsx)("span",{className:"session-tree-footer-label",children:o("sidebar.archivedCount",{count:t.count})}),(0,r.jsx)(tv.zp,{size:10,className:"session-tree-footer-chevron"})]})})}}),tT=(0,i.memo)(function(e){let{row:t,top:n,height:i,menuOpen:s,handlers:a}=e,{t:o}=(0,eX.s)(),{project:l,expanded:d}=t,c=["session-tree-row session-tree-group session-tree-archive-group",l.current?"is-current":"",s?"is-active":""].filter(Boolean).join(" ");return(0,r.jsxs)("div",{className:c,style:tw(n,i),"data-row-key":t.key,children:[(0,r.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":d,title:l.root,onClick:e=>a.current.onToggleArchiveGroup?.(l.key,e.altKey),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${d?" is-open":""}`}),(0,r.jsx)("span",{className:"session-tree-group-name",children:l.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:l.name}),title:o("sidebar.archivedProjectActions",{name:l.name}),"aria-haspopup":"menu","aria-expanded":s,onClick:e=>{e.stopPropagation(),a.current.onArchiveGroupMenu?.(l,e.currentTarget)},children:(0,r.jsx)(tv.Z4,{size:13})})})]})}),tM="[data-sidebar-menu-filter]",tR="[data-sidebar-menu-autofocus]",tA="button, input, textarea, select, a[href], [tabindex]";function tL(e){return i.Children.toArray(e).length>0}function tP(e){return"item"===e.type&&void 0!==e.checked}function tz(e){return e.getClientRects().length>0}function tO(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&tz(e)}function tW(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(tO)}function tF(e){let t=Array.from(e.querySelectorAll(tR)).find(tO);if(t)return t;let n=tW(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(tA)).filter(e=>e.tabIndex>=0&&tO(e))[0]??null}function tD(e){e.stopPropagation()}let tB={onClick:tD,onDoubleClick:tD,onMouseDown:tD,onMouseUp:tD,onPointerDown:tD,onPointerUp:tD,onKeyDown:tD,onKeyUp:tD,onFocus:tD,onBlur:tD,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function t_(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function tH(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(" "),a=["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 l=(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:t_(t,n),children:[(0,r.jsx)("span",{className:"sidebar-menu-icon",children:i?t.checked?(0,r.jsx)(tv.Sr,{size:13}):null:t.icon}),(0,r.jsx)("span",{className:a,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:[l,(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:t_(d,n),children:d.icon})]}):l}function tU(e){var t;let n,{sheet:i,ariaLabel:s,title:a,items:o,filter:l,filterQuery:d="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:m=208,classic:g=!1,footer:f,surfaceRef:x,onActivate:b,onClose:v}=e,y=tL(u),k=!y&&tL(f),j=void 0!==l&&!y&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(tP).length>=t}(o,l.minChoices),w=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=w.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)(tH,{item:e,onActivate:b},e.id)),C=y?u:j||k?(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:l.placeholder,"aria-label":l.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()&&!w.some(tP)&&(0,r.jsx)("div",{className:"sidebar-menu-empty",children:l.emptyLabel})}),(0,r.jsx)("div",{role:"menu","aria-label":s,children:S}),k&&f]}):S,N=y||j||k?void 0:"menu";return i?(0,r.jsxs)("div",{className:"sidebar-sheet-layer",...tB,children:[(0,r.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>v("outside")}),(0,r.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":s,children:[a?(0,r.jsx)("div",{className:"sidebar-sheet-title",children:a}):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:()=>v("cancel"),children:p})]})]}):(0,r.jsx)("div",{ref:x,className:g?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":s,style:{width:m},...tB,children:C})}function tq(e){let{open:t,anchor:n,sheet:s,ariaLabel:a,title:o,items:l,filter:d,children:c,cancelLabel:u,focusCancel:p,onClose:h,returnFocusTo:m,width:g,classic:f=!1,footer:x,focusKey:b=""}=e,[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(""),w=(0,i.useRef)(k);w.current=k;let S=(0,i.useRef)(null),C=(0,i.useRef)(h);C.current=h;let N=(0,i.useRef)(l);N.current=l;let I=(0,i.useRef)(m??null);I.current=m??null;let $=(0,i.useRef)(n);$.current=n,(0,i.useEffect)(()=>{y(document.body)},[]);let E=t&&null!==v&&(s||null!==n),T=tL(c),M=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(!E||s||!e)return;let t=window.visualViewport,n=()=>{let n=$.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,a=n.left+s,o=n.top+s,l=n.left+n.width-s,d=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>l&&e.x-t.width>=a?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,a=n.top-4-t.height;i=s+t.height>d&&a>=o?a:s}return{left:Math.max(a,Math.min(r,l-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)}},[E,s,M,T]),(0,i.useEffect)(()=>{j("")},[E,T]);let L=(0,i.useRef)(!1);return((0,i.useLayoutEffect)(()=>{let e=S.current;if(!E||!e){L.current=!1;return}let t=!L.current;L.current=!0,(t?tF(e):Array.from(e.querySelectorAll(tR)).filter(e=>!e.matches(tM)&&tO(e))[0]??tF(e))?.focus({preventScroll:!0})},[E,s,T,b]),(0,i.useLayoutEffect)(()=>{let e=S.current;if(!E||!e)return;let t=I.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(tz(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(tA)))if(e.tabIndex>=0&&tO(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&tz(t)&&t.focus({preventScroll:!0}))}},[E,s]),(0,i.useEffect)(()=>{if(!E)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(tM);if(n&&w.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,a;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(tA)).filter(e=>e!==n&&e.tabIndex>=0&&tO(e)),a=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&a)!=0))||C.current("outside");return}let a=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(tM);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)&&!a)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=tW(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&&!T&&(e.preventDefault(),e.stopPropagation(),A.current(o,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[E,T]),(0,i.useEffect)(()=>{if(!E||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=I.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)},[E,s]),E&&v)?(0,e5.createPortal)((0,r.jsx)(tU,{sheet:s,ariaLabel:a,title:o,items:l,filter:d,filterQuery:k,onFilterQueryChange:j,cancelLabel:u,focusCancel:p,width:g,classic:f,footer:x,surfaceRef:S,onActivate:(e,t)=>A.current(e,t),onClose:e=>C.current(e),children:c}),v):null}function tK(e){let{heading:t,busy:n,error:s,showCancel:a,onCreate:o,onCancel:l}=e,{t:d}=(0,eX.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")}),a&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:l,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function tZ(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function tV(e){return e.branch??J(e.path)}function tJ(e){let{heading:t,dirty:n,busy:i,error:s,showCancel:a,onForce:o,onCancel:l}=e,{t:d}=(0,eX.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||a)&&(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")}),a&&(0,r.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:d("sidebar.cancel")})]}),s&&(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:s})]})}function tG(e){let{busy:t,onForce:n,onCancel:s}=e,{t:a}=(0,eX.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:a("sidebar.forceRemoveCheckout"),children:a("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:a("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:a("sidebar.cancel")})]})}function tY(e){let t,n,{layout:s,context:a,mobile:o,label:l,placeholder:d="",homeDir:c,projectActivity:u,worktreeHint:p=null,newWorktreeTitle:h,handleRef:m,onPick:g,onUseDefaultDirectory:f,onOpenFolder:x,onRefreshWorktrees:b,onCreateWorktree:v,onRemoveWorktree:y}=e,{t:k}=(0,eX.s)(),[j,w]=(0,i.useState)(null),S=(0,i.useRef)(j);S.current=j;let C=(0,i.useRef)(0),N=(0,i.useRef)(null),I=(0,i.useRef)(null),$=(0,i.useRef)(!1),E=(0,i.useRef)(g);E.current=g;let T="inline"!==s,M=!T,R=!o,{project:A,worktrees:L}=a,P=(t=a.worktrees??[]).find(e=>e.path===a.currentWorktreePath)??t.find(e=>e.isMain)??null,z=M&&A?ev(ex(a)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,i.useEffect)(()=>($.current=!0,()=>{$.current=!1}),[]);let O=()=>(C.current+=1,C.current),W=()=>w(null),F=(e,t)=>{let n=t.getBoundingClientRect(),r=Math.max(T?220:"project"===e?260:240,Math.round(n.width));w({id:O(),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&&b()},D=(0,i.useRef)(F);D.current=F,(0,i.useImperativeHandle)(m,()=>({button:e=>("worktree"===e?I:N).current,openMenu:e=>{let t=("worktree"===e?I:N).current;t&&D.current(e,t)}}),[]);let B=(e,t)=>{w(n=>n?.id===e?t(n):n)},_=e=>{let t=O();w(n=>n?.kind==="worktree"?{...n,id:t,body:e,removing:!1}:n)},H=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 v(A,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}$.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(w(null),E.current({cwd:t.path,projectKey:A.key,projectRoot:A.root},"worktree")))},U=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)}}$.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}}})},q=()=>[...(L??[]).map(e=>R&&K?.kind==="remove"&&K.dirty&&K.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,r.jsx)(tG,{busy:K.busy,onForce:()=>{U(e,!0)},onCancel:()=>_(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??tZ(e.path,c):tV(e),mono:R,path:R,note:e.isMain?k("sidebar.main"):void 0,title:e.path,checked:e.path===P?.path,secondary:y&&!e.isMain?{label:k("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,r.jsx)(tv.uc,{size:12}),danger:!0,disabled:j?.removing,onSelect:t=>{let{keepOpen:n}=t;n(),U(e,!1)}}:void 0,onSelect:()=>{A&&e.path!==P?.path&&g({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&K?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:k("sidebar.newWorktree"),icon:(0,r.jsx)(tv.c1,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),_({kind:"create",busy:!1,error:null})}}]],K=j?.kind==="worktree"?j.body:null,Z="",V=null,G=null;if(R&&j?.kind==="worktree")Z=k("sidebar.switchWorktree"),n=q(),K?.kind==="create"?G=(0,r.jsx)(tK,{heading:null,busy:K.busy,error:K.error,showCancel:!0,onCreate:e=>{H(e)},onCancel:()=>_(null)}):K?.kind==="remove"&&K.error&&(G=(0,r.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:K.error}));else if(K?.kind==="create")Z=h,V=(0,r.jsx)(tK,{heading:o?null:Z,busy:K.busy,error:K.error,showCancel:!o,onCreate:e=>{H(e)},onCancel:W});else if(K?.kind==="remove")Z=k("sidebar.removeWorktreeHeading",{name:tV(K.worktree)}),V=(0,r.jsx)(tJ,{heading:o?null:Z,dirty:K.dirty,busy:K.busy,error:K.error,showCancel:!o,onForce:()=>{U(K.worktree,!0)},onCancel:W});else if(j?.kind==="project"){let e,t;Z=k("workspace.project"),t=(e=ev(ex(a)).map(e=>{let{choice:t,name:n,note:i}=e,s=u?.get(t.key),a=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:a?tZ(t.root,c):n,note:a?void 0:i??void 0,mono:R,path:a,title:t.root,checked:t.key===A?.key,badge:s?(0,r.jsx)(tI,{running:s.running,unread:s.unread,t:k}):void 0,onSelect:()=>{t.key===A?.key&&L||g({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:k("sidebar.useDefaultDirectory"),icon:(0,r.jsx)(tv.sj,{size:13}),onSelect:()=>f()},{type:"item",id:"open-folder",label:k(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,r.jsx)(tv.c1,{size:13}):(0,r.jsx)(tv.YP,{size:13}),onSelect:()=>x(j?.opener??null)}]}else j?.kind==="worktree"&&(Z=k("sidebar.switchWorktree"),n=q());let Y=j?.kind==="project"?{placeholder:k("sidebar.filterProjects"),emptyLabel:k("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:k("sidebar.filterWorktrees"),emptyLabel:k("sidebar.noMatchingWorktrees")},X=T&&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":l,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:[M&&(0,r.jsx)(tv.sj,{size:12,className:"project-picker-icon"}),M&&A?(0,r.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&z?.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"project-picker-parent",children:z.note}),"/"]}),(0,r.jsx)("span",{className:"project-picker-leaf",children:A.alias??z?.name??J(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:tZ(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:k("sidebar.newActivity"),"aria-label":k("sidebar.newActivity")}),M&&(0,r.jsx)(tv.zp,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,r.jsxs)("button",{ref:I,type:"button",className:"project-picker-button",title:P?k("sidebar.worktreePath",{path:P.path}):k("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":j?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,r.jsx)(tv.OK,{size:11,className:P&&!P.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-path",children:(0,r.jsx)("span",{children:P?P.branch??tZ(P.path,c):"…"})}),P?.isMain&&"stacked"===s&&(0,r.jsx)("span",{className:"project-picker-note",children:k("sidebar.main")}),T&&L.length>1&&(0,r.jsx)("span",{className:"project-picker-note",children:L.length}),(0,r.jsx)(tv.zp,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&T&&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)(tv.OK,{size:11,className:"project-picker-icon"}),(0,r.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,r.jsx)(tq,{open:null!==j,anchor:j?.anchor??null,sheet:o,ariaLabel:Z,title:Z,items:n,filter:Y,cancelLabel:k("sidebar.cancel"),focusCancel:K?.kind==="remove",onClose:W,returnFocusTo:j?.opener??null,width:j?.width,classic:R,footer:G,focusKey:K?`${K.kind}:${"remove"===K.kind&&K.dirty}`:"list",children:V})]})}function tX(e){let{open:t,query:n,children:s,selectedSessionId:a,onSelectSession:o,archivedSessionIds:l,projectNames:d}=e,{t:c,locale:u}=(0,eX.s)(),[p,h]=(0,i.useState)({query:""}),m=n.trim(),g=p.query===m?p.response:void 0,f=p.query===m&&p.failed;return(0,i.useEffect)(()=>{if(!t||!m)return;let e=new AbortController;h({query:m});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:m})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||h({query:m,response:n})}catch{e.signal.aborted||h({query:m,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,m]),t&&m?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!g&&!f,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:f?c("sidebar.sessionSearchFailed"):g?0===g.results.length?c("sidebar.sessionSearchEmpty"):c("sidebar.sessionSearchCount",{count:g.results.length}):c("sidebar.sessionSearching")}),g?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:c("sidebar.sessionSearchPartial")}),g?.results.map(e=>{let t,n,{session:i,entryId:s,blockIndex:p,titleMatch:h,before:m,match:g,after:f}=e;return(0,r.jsxs)("button",{type:"button",onClick:()=>o(i,s,p),"aria-current":i.id===a?"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 ${i.id===a?"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:h?(0,r.jsxs)(r.Fragment,{children:[m,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:g}),f]}):i.name||i.firstMessage}),l?.has(i.id)&&(0,r.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:c("sidebar.archived")})]}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsxs)("span",{className:"min-w-0 flex-1 truncate",title:i.cwd,children:[(0,r.jsx)("span",{className:"font-medium text-text-muted",children:(t=x(i),n=i.projectRoot??i.cwd,d&&Object.hasOwn(d,t)?d[t]:J(n))}),i.cwd!==(i.projectRoot??i.cwd)&&` \xb7 ${i.cwd}`]}),(0,r.jsx)("span",{className:"shrink-0",children:(0,tm.fw)(i.modified,u)})]}),!h&&(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[m,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:g}),f]})]},i.id)})]}):s}function tQ(e,t){return`${e}/share/${t}`}function t0(e){return e instanceof Error?e.message:String(e)}function t1(e){let{sessionId:t,origin:n,fetchImpl:s,onCopied:a,onStopped:o}=e,{t:l}=(0,eX.s)(),[d,c]=(0,i.useState)({status:"loading"}),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),[x,b]=(0,i.useState)(null),v=s??fetch,y=n??window.location.origin,k=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!0;return c({status:"loading"}),m(null),f(!1),v(`/api/sessions/${encodeURIComponent(t)}/share`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));if(e){if(!t.ok)return void c({status:"load-failed",error:n.error??`HTTP ${t.status}`});c(n.share?{status:"shared",share:n.share}:{status:"unshared"})}}).catch(t=>{e&&c({status:"load-failed",error:t0(t)})}),()=>{e=!1}},[v,t]),(0,i.useEffect)(()=>{let e=!0;return v(`/api/sessions/${encodeURIComponent(t)}`,{cache:"no-store"}).then(async t=>{let n=await t.json().catch(()=>({}));e&&t.ok&&"number"==typeof n.info?.messageCount&&b(n.info.messageCount)}).catch(()=>{}),()=>{e=!1}},[v,t]);let j=(0,i.useCallback)(()=>{k.current||(k.current=!0,p("create"),m(null),v(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}).then(async e=>{var t,n;let r=await e.json().catch(()=>({}));if("string"!=typeof(t=r).code||"string"!=typeof t.createdAt||"string"!=typeof t.title){let{key:t,params:i}=(n=e.status,"too_large"===r.code||"too_large"===r.error?{key:"share.tooLarge"}:{key:"share.createError",params:{error:r.error??`HTTP ${n}`}});m(l(t,i));return}c({status:"shared",share:{code:r.code,createdAt:r.createdAt,title:r.title}}),f(!1)}).catch(e=>{m(l("share.createError",{error:t0(e)}))}).finally(()=>{k.current=!1,p(null)}))},[v,t,l]),w=(0,i.useCallback)(()=>{if(!k.current){if(!g)return void f(!0);k.current=!0,p("stop"),m(null),v(`/api/sessions/${encodeURIComponent(t)}/share`,{method:"DELETE"}).then(async e=>{let t=await e.json().catch(()=>({}));e.ok&&!0===t.ok?(c({status:"unshared"}),f(!1),b(null),o()):m(l("share.stopError",{error:t.error??`HTTP ${e.status}`}))}).catch(e=>{m(l("share.stopError",{error:t0(e)}))}).finally(()=>{k.current=!1,p(null)})}},[o,v,t,g,l]),S=(0,i.useCallback)(()=>{c(e=>("shared"===e.status&&(0,tc.D)(tQ(y,e.share.code)).then(()=>a(),()=>{}),e))},[a,y]);return(0,r.jsx)(t2,{state:d,messageCount:x,busy:u,error:h,stopArmed:g,origin:y,onCopy:S,onCreate:j,onRefresh:j,onStop:w})}function t2(e){let{state:t,messageCount:n,busy:i,error:s,stopArmed:a,origin:o,onCopy:l,onCreate:d,onRefresh:c,onStop:u}=e,{t:p}=(0,eX.s)();return(0,r.jsxs)("div",{className:"sidebar-share-panel",children:[(0,r.jsx)("div",{className:"sidebar-menu-header",children:p("share.title")}),"loading"===t.status&&(0,r.jsx)("p",{role:"status",className:"sidebar-share-status",children:p("sidebar.loading")}),"load-failed"===t.status&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:p("share.loadError",{error:t.error})}),"unshared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"sidebar-share-text",children:p("share.description")}),null!==n&&(0,r.jsx)("p",{className:"sidebar-share-note",children:p("share.summary",{count:n})}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:"sidebar-share-create",disabled:null!==i,"data-sidebar-menu-autofocus":"",onClick:d,children:p("create"===i?"share.creating":"share.create")})})]}),"shared"===t.status&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"sidebar-share-link-label",children:p("share.linkLabel")}),(0,r.jsx)("code",{className:"sidebar-share-link",children:tQ(o,t.share.code)}),(0,r.jsxs)("div",{className:"sidebar-share-buttons",children:[(0,r.jsx)("button",{type:"button",className:"sidebar-share-copy","data-sidebar-menu-autofocus":"",onClick:l,children:p("share.copy")}),(0,r.jsx)("button",{type:"button",className:"sidebar-share-refresh",disabled:null!==i,onClick:c,children:p("create"===i?"share.creating":"share.refresh")})]}),(0,r.jsx)("div",{className:"sidebar-share-buttons",children:(0,r.jsx)("button",{type:"button",className:`sidebar-share-stop${a?" is-armed":""}`,disabled:null!==i,onClick:u,children:p(a?"share.confirmStop":"share.stop")})})]}),s&&(0,r.jsx)("div",{role:"alert",className:"sidebar-share-error",children:s})]})}function t4(e){let{toast:t,dismissLabel:n,durationMs:s,onDismissRef:a}=e,o=(0,i.useRef)(null),[l,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=l||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(()=>a.current(),s);return()=>window.clearTimeout(e)},[p,s,a]),(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:()=>{a.current(),e.onClick()},children:e.label},e.id)),(0,r.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>a.current(),children:(0,r.jsx)(tv.US,{size:12})})]})}function t8(e){let{toast:t,onDismiss:n,dismissLabel:s,durationMs:a=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)(t4,{toast:t,dismissLabel:s,durationMs:a,onDismissRef:o},t.id):null})}let t6={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function t3(e){let{ref:t,onClick:n,title:i,disabled:s,pressed:a,expanded:o,controls:l,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":a,"aria-expanded":o,"aria-controls":l,className:`sidebar-tool-button${a||o?" is-active":""}${d?" is-done":""}${c?` ${c}`:""}`,children:u})}let t5="pi-web:last-custom-cwd",t9={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename",fork:"sidebar.fork",share:"sidebar.sessionShare","copy-session-id":"sidebar.copySessionId","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function t7(){try{return window.localStorage.getItem(t5)??""}catch{return""}}function ne(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 nt(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function nn(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):e$(document,e)}function nr(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 ni(e){var t,n,s;let a,o,u,h,m,g,f,v,{selectedSessionId:k,onSelectSession:j,onNewSession:w,controlRef:S,onNewSessionContextChange:C,initialSessionId:I,initialSessionLinked:D,skipInitialProjectSelection:K,onInitialRestoreDone:Y,refreshKey:ed,onSessionDeleted:eh,selectedCwd:em,onCwdChange:ex,onOpenFile:ev,onOpenTerminal:ey,onOpenGitGraph:ew,explorerRefreshKey:eI,onExplorerRefresh:eP,onAtMention:eW,onAtMentions:eB,onBackgroundTaskDone:e_,hiddenFinishedSessionIds:eH,onRunningSessionIdsChange:eU,onSessionsChange:eq}=e,{t:eK}=(0,eX.s)(),eZ=(0,eQ.a)(),[eV,eJ]=(0,i.useState)([]),eG=(0,i.useRef)(null),e4=(0,i.useRef)(0),[e5,e9]=(0,i.useState)(!0),[e7,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(null),[ts,ta]=(0,i.useState)(""),[tu,tp]=(0,i.useState)(!1),[tm,tg]=(0,i.useState)(t7),[tf,tx]=(0,i.useState)(null),[tb,tk]=(0,i.useState)(!1),[tw,tS]=(0,i.useState)(null),tC=(0,i.useRef)(null),[tN,tI]=(0,i.useState)(null),[t$,tE]=(0,i.useState)(null),tT=(0,i.useRef)(null);tT.current??=new Set((0,ec.PS)());let[tM,tR]=(0,i.useState)(0),[tA,tL]=(0,i.useState)(!1),[tP,tz]=(0,i.useState)(!1),[tO,tW]=(0,i.useState)(!1),[tF,tD]=(0,i.useState)(""),[tB,t_]=(0,i.useState)(0),[tH,tU]=(0,i.useState)(!0),[tK,tZ]=(0,i.useState)(!1),[tV,tJ]=(0,i.useState)(!1),[tG,tQ]=(0,i.useState)(null),[t0,t2]=(0,i.useState)(null),[t4,ni]=(0,i.useState)(()=>new Set),[ns,na]=(0,i.useState)(()=>new Set),[no,nl]=(0,i.useState)(()=>new Set),[nd,nc]=(0,i.useState)(()=>(function(){try{return eR(window.localStorage.getItem(eT))}catch{return new Map}})()),nu=(0,i.useRef)(new Set),np=(0,i.useRef)(new Set),nh=(0,i.useRef)({latest:null,before:null}),nm=(0,i.useRef)(null);nm.current??=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now,t=0;return{note(e,n,r){eM(e)&&Number.isFinite(n)&&Number.isFinite(r)&&(t=e-(n+r)/2)},toServer(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:e();return n+t}}}();let ng=(0,i.useRef)(new Set),nf=(0,i.useRef)(new Set),nx=(0,i.useRef)(new Set),nb=(0,i.useRef)(new Set),nv=(0,i.useRef)(!1),ny=(0,i.useRef)(null),nk=(0,i.useRef)(null),nj=(0,i.useRef)(null),nw=eY(),nS=!eZ&&"below"===nw,[nC,nN]=(0,i.useState)("sessions"),[nI,n$]=(0,i.useState)(!1),nE=(0,i.useRef)(null),nT=(0,i.useRef)(null),nM=(0,i.useRef)(null),nR=(0,i.useRef)(null),nA=(0,i.useRef)(new WeakMap),[nL,nP]=(0,i.useState)({}),[nz,nO]=(0,i.useState)(()=>new Set),[nW,nF]=(0,i.useState)({}),[nD,nB]=(0,i.useState)(!1),[n_,nH]=(0,i.useState)(!1),[nU,nq]=(0,i.useState)([]),[nK,nZ]=(0,i.useState)(!1),{phase:nV,start:nJ,end:nG}=e3(),{phase:nY,start:nX,end:nQ}=e3(),n0=(0,i.useRef)(nI);n0.current=nI;let n1=(0,i.useRef)(nK);n1.current=nK;let n2=(0,i.useCallback)(e=>{e!==n1.current&&nX(e?"in":"out"),nZ(e)},[nX]),n4=(a=nI&&"out"===nV,o=!nI&&"in"===nV,{bodyHidden:nI&&!a,bodyInert:a,moving:a||o,open:!nI&&!o}),n8=(u=nK&&"in"===nY,h=!nK&&"out"===nY,{mainHidden:nK&&!u,mainInert:u,archiveMounted:nK||h,archiveInert:h,archiveClass:u?"is-entering":h?"is-leaving":null}),[n6,n3]=(0,i.useState)(null),[n5,n9]=(0,i.useState)(null),[n7,re]=(0,i.useState)(null),[rt,rn]=(0,i.useState)(null),[rr,ri]=(0,i.useState)(null),rs=(0,i.useRef)(0),ra=(0,i.useCallback)(e=>{ri(t=>t?.id===e?null:t)},[]),[ro,rl]=(0,i.useState)(null),rd=(0,i.useCallback)(e=>{rl(t=>t?.id===e?null:t)},[]),rc=(0,i.useRef)(k);rc.current=k;let[ru,rp]=(0,i.useState)(null),rh=(0,i.useRef)(0),rm=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;rh.current+=1,rp({id:rh.current,message:e,...n?{tail:n}:{},actions:t})},[]),[rg,rf]=(0,i.useState)(0),rx=(0,i.useRef)(0),rb=(0,i.useRef)(null),[rv,ry]=(0,i.useState)(0),rk=(0,i.useRef)(null),rj=(0,i.useRef)(null),rw=(0,i.useRef)(null),rS=(0,i.useRef)(null),[rC,rN]=(0,i.useState)(0),rI=(0,i.useCallback)(e=>{rS.current=e,rN(e=>e+1)},[]);(0,i.useEffect)(()=>{let e=rS.current;rS.current=null,e&&e$(document,e())},[rC]);let{state:r$,loaded:rE,synced:rT,error:rM,apply:rR,snapshot:rA,noteRevision:rL}=function(){let[e,t]=(0,i.useState)(L),[n,r]=(0,i.useState)(!1),[s,a]=(0,i.useState)(!1),[o,l]=(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),m=(0,i.useRef)(null),g=(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,a;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}),e.readAt&&(r.readAt={...e.readAt}),r}(e),l=!1;switch(t.action){case"set":for(let e of t.ids){let r=y(o.sessions,e)?o.sessions[e]:void 0;z(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))&&(l=!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),z(o.sessions,e.id,t)&&(l=!0)}break;case"pin-project":{let{projectKey:e,root:a}=t,d=y(o.projects,e)?o.projects[e]:void 0;if(t.pinned?d?.root!==a&&(o.projects[e]={pinnedAt:n,root:a},l=!0):d&&(delete o.projects[e],l=!0),(t.pinned?void 0===d:void 0!==d)&&o.projectOrder){let n,a,d=(r=o.projectOrder,i=o.projects,s=t.pinned,a=r.filter(t=>t!==e),s?(n=0,a.forEach((e,t)=>{y(i,e)&&(n=t+1)})):(n=a.findIndex(e=>!y(i,e)))<0&&(n=a.length),a.splice(n,0,e),a);T(d.length,E(d))&&O(o,d)&&(l=!0)}break}case"add-projects":O(o,function(e,t){let n=W(e,t),r=e.length,i=E(e),s=n.length;for(;s>0;){let e=$(n[s-1]);if(!T(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(o.projectOrder??[],t.keys))&&(l=!0);break;case"move-project":{let e,n,{projectKey:r,anchorKey:i,position:s,add:d}=t,c=o.projectOrder??[];O(o,function(e,t){let n=e.length,r=E(e);if(T(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!T(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=$(e[s]));let s=e.filter((e,t)=>!i.has(t));return T(n,r)?s:M(s)}((a=[...W(c,d),...c],(e=a.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])))&&(l=!0);break}case"rename-project":{let e=N(t.name);void 0!==e&&function(e,t,n){let r={...e.projectNames};if((y(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!A(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=R(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}(o,t.projectKey,e)&&(l=!0);break}case"read":{let e={...o.readAt};for(let r of t.ids){let t=y(e,r)?e[r]:void 0;void 0!==t&&t>=n||(e[r]=n,l=!0)}l&&(o.readAt=P(e))}}return{state:o,changed:l}}(e,t,n).state;c.current=e,t(e)},[]),f=(0,i.useCallback)(async e=>{let t=++h.current;m.current=t;try{let n=await fetch(e2,{cache:"no-store"}),i=await e6(n);if(t!==h.current)return;d.current=i,g(),e||l(null),r(!0),a(!0)}catch(e){if(t!==h.current)return;l(e8(e)),r(!0)}finally{m.current===t&&(m.current=null)}},[g]),x=(0,i.useCallback)(()=>f(!1),[f]),b=(0,i.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||u.current.length>0||e===d.current.revision||(null===m.current||m.current!==h.current)&&x()},[x]),v=(0,i.useCallback)(e=>{let t={request:e,now:Date.now()};u.current=[...u.current,t],g();let n=async()=>{let n=!1;try{let t=await fetch(e2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await e6(t);h.current++,d.current=i,l(null),r(!0),a(!0),n=!0}catch(e){l(e8(e))}return u.current=u.current.filter(e=>e!==t),g(),n||await f(!0),n},i=p.current.then(n,n);return p.current=i,i},[f,g]),k=(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=y(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)(()=>{x()},[x]),(0,i.useMemo)(()=>({state:e,loaded:n,synced:s,error:o,refresh:x,noteRevision:b,apply:v,snapshot:k}),[e,n,s,o,x,b,v,k])}(),rP=r$.readAt,rz=(0,i.useMemo)(()=>new Set(eA(nd,rP).keys()),[nd,rP]);(0,i.useEffect)(()=>{nc(e=>eA(e,rP))},[rP,nd]);let rO=(0,i.useRef)({allSessions:eV,readAt:rP,unreadMarks:nd,runningSessionIds:t4,subagentsActiveSessionIds:no});rO.current={allSessions:eV,readAt:rP,unreadMarks:nd,runningSessionIds:t4,subagentsActiveSessionIds:no};let rW=(0,i.useCallback)(e=>{let t=nf.current,n=[...new Set(e)].filter(e=>!t.has(e));if(0!==n.length){for(let e of n)t.add(e);rR({action:"read",ids:n}).then(e=>{for(let r of n)t.delete(r),e&&ng.current.delete(r)})}},[rR]),rF=(0,i.useCallback)((e,t)=>{var n;let r=rO.current;if(r.runningSessionIds.has(e)||r.subagentsActiveSessionIds.has(e))return;if(!eD()){t&&ng.current.add(e);return}let i=r.allSessions.find(t=>t.id===e),s=i?Date.parse(i.modified):0/0;((n={readAt:r.readAt&&Object.prototype.hasOwnProperty.call(r.readAt,e)?r.readAt[e]:void 0,modifiedMs:Number.isFinite(s)?s:void 0,marked:t,pending:ng.current.has(e)}).marked||n.pending||void 0===n.readAt||void 0!==n.modifiedMs&&n.modifiedMs>n.readAt)&&rW([e])},[rW]);(0,i.useEffect)(()=>{var e;let t,n;return e=()=>{let e=rc.current;e&&rF(e,!1)},t=eF().onAttended(e),0==ez++&&(eO=function(){let e=eF(),t=()=>e.noteInput(),n=()=>e.notePageChange(),r={capture:!0,passive:!0};for(let e of eL)window.addEventListener(e,t,r);return window.addEventListener("focus",n),window.addEventListener("blur",n),document.addEventListener("visibilitychange",n),()=>{for(let e of eL)window.removeEventListener(e,t,r);window.removeEventListener("focus",n),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",n)}}()),n=!1,()=>{n||(n=!0,t(),0==--ez&&(eO?.(),eO=null))}},[rF]);let rD=(0,i.useRef)(null),rB=(0,i.useRef)(null);e1(rB);let r_=(0,i.useRef)(null),rH=(0,i.useRef)(null),rU=(0,i.useRef)(320),rq=(0,i.useCallback)(()=>{let e=rH.current,t=rD.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),rK=(0,i.useCallback)(()=>Math.round(.45*rq()),[rq]),rZ=(0,i.useCallback)(()=>rq()-120,[rq]),rV=(0,e0.T)({ariaLabel:eK("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:rK,getMaxWidth:rZ,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:rU}),rJ=rV.panelRef,rG=(0,i.useCallback)(e=>{rH.current=e,rJ.current=e},[rJ]),rY=rV.reclampWidth;(0,i.useEffect)(()=>{let e=rH.current;if(!nS||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>rY());return t.observe(e),()=>t.disconnect()},[rY,nS]),(0,i.useEffect)(()=>{let e=(0,ec.K$)();"sessions"!==e&&nN(e);let t=(0,ec.$$)();Object.keys(t).length>0&&nP(t),(0,ec.iw)()&&nB(!0);let n=(0,ec.cA)();n.length>0&&nq(n),(0,ec.bj)()&&n$(!0),(0,ec.hS)()&&tZ(!0),nH(!0),(0,ec.vK)()},[]);let rX=(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=++e4.current;try{e&&e9(!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!==e4.current)return;eG.current=s.sessionListVersion,eJ(s.sessions),n||te(!0),nv.current||(nx.current=new Set(s.completionNotificationSuppressedSessionIds??[]),nh.current={latest:Date.now(),before:nh.current.latest},ni(e=>ne(e,s.runningSessionIds??[])),na(e=>ne(e,s.awaitingInputSessionIds??[])));let a=new Set(s.sessions.filter(e=>!l(e.relation)).map(e=>e.id));nc(e=>{if(0===e.size)return e;let t=new Map([...e].filter(e=>{let[t]=e;return a.has(t)}));return t.size===e.size?e:t}),tn(null)}catch(e){r===e4.current&&tn(String(e))}finally{r===e4.current&&e9(!1)}},[]),rQ=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!rQ.current;rQ.current=!0;let t=!0;return e?rX(!0,!1,!0).then(()=>{t&&(ny.current=setTimeout(()=>{ny.current=null,t&&rX(!1,!0)},750))}):rX(),()=>{t=!1,ny.current&&(clearTimeout(ny.current),ny.current=null)}},[rX,ed]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&tQ(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{t2(null)},[tr,em]);let r0=(0,i.useCallback)(async()=>{let e=tr??em;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 t2(null),!1;let n=await t.json().catch(()=>({}));t2(n.error??`HTTP ${t.status}`)}catch(e){t2(e instanceof Error?e.message:String(e))}return!0},[tr,em]),r1=eK(tG?.platform==="darwin"?"sidebar.openInFinder":tG?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),r2=tG?.supported===!1,r4=t0?eK(t6[t0]??t0):null;(0,i.useEffect)(()=>{try{let e=0===nd.size?null:JSON.stringify(Object.fromEntries(nd));null===e?window.localStorage.removeItem(eT):window.localStorage.setItem(eT,e)}catch{}},[nd]),(0,i.useEffect)(()=>{let e=e=>{(null===e.key||e.key===eT)&&nc(t=>(function(e,t){if(e.size!==t.size)return t;for(let[n,r]of t)if(e.get(n)!==r)return t;return e})(t,eR(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 a=Date.now(),o=null,l="error",d=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(d=t.status,!t.ok)return;l="ok";let r=await t.json();if(o=Date.now(),e||n!==s)return;nv.current=!0,"number"==typeof r.serverNow&&nm.current?.note(r.serverNow,a,o),nh.current={latest:a,before:nh.current.latest},nx.current=new Set(r.completionNotificationSuppressedSessionIds??[]),ni(e=>ne(e,r.runningSessionIds??[])),na(e=>ne(e,r.awaitingInputSessionIds??[])),nl(e=>ne(e,r.subagentsActiveSessionIds??[])),rL(r.sessionUiStateRevision),r.sessionListVersion!==eG.current&&await rX()}catch{l=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),(0,eE.tK)(a,l,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)}},[rX,rL]),(0,i.useEffect)(()=>{eU?.(t4)},[eU,t4]),(0,i.useEffect)(()=>{eq?.(eV)},[eV,eq]),(0,i.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=ek(e.awaiting))+ek(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==ej){if(ej=i,!r){for(let[e,t]of eS)e.href=t;return}for(let e of eC())eS.has(e)||eS.set(e,e.href);eN(r,i)}}({awaiting:ns.size,unread:function(e,t){if(!t||0===t.size)return e.size;let n=0;for(let r of t)e.has(r)||(n+=1);return e.size+n}(rz,eH)})},[ns,rz,eH]),(0,i.useEffect)(()=>{let e=nu.current,t=[...e].filter(e=>!t4.has(e)&&e!==k),n=new Set([...t4,...no]),r=[...np.current].filter(e=>!n.has(e)&&e!==k),i=new Set(eV.filter(e=>l(e.relation)).map(e=>e.id)),s=r.filter(e=>!nb.current.has(e)&&!i.has(e)),a=[...t4].filter(t=>!e.has(t));if(s.length>0||a.length>0){let e=nh.current.before,t=nm.current.toServer(e??void 0);nc(e=>{let n=new Map(e);return t4.forEach(e=>n.delete(e)),s.forEach(e=>n.set(e,t)),n})}k&&np.current.has(k)&&!n.has(k)&&(eD()?rW([k]):ng.current.add(k));let o=a.some(e=>!eV.some(t=>t.id===e));(t.length>0||o)&&rX(),s.length>0&&e_?.(),nu.current=t4,np.current=n;let d=nb.current;nb.current=new Set([...n].filter(e=>nx.current.has(e)||i.has(e)||d.has(e)&&!t4.has(e)))},[t4,no,k,eV,rX,e_,rW]),(0,i.useEffect)(()=>{if(!k)return;let e=rO.current.unreadMarks.has(k);rF(k,e),e&&nc(e=>{if(!e.has(k))return e;let t=new Map(e);return t.delete(k),t})},[k,rF]),(0,i.useEffect)(()=>{void 0!==eI&&tR(e=>e+1)},[eI]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&ta(e.home)}).catch(()=>{})},[]);let r8=(0,i.useRef)(!1),r6=(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:x(s)}:{root:e,key:e}}(e,{validated:tw,listing:tN,sessions:eV}):null,[tw,tN,eV]),r3=(0,i.useMemo)(()=>r6(tr),[r6,tr]),r5=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=r6(tr),t=r5.current;(t?.cwd!==tr||t.key!==(e?.key??null))&&(r5.current={cwd:tr,key:e?.key??null},ex?.(tr,e?.root??null,e?.key??null))},[tr,ex,r6]);let r9=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!em){r9.current=null;return}em!==r9.current&&(r9.current=em,ti(em))},[em]);let[r7,ie]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!tr){tI(null),tE(null);return}let e=!1;return tE(tr),fetch(`/api/worktrees?cwd=${encodeURIComponent(tr)}`).then(e=>e.json()).then(t=>{if(!e){if(tE(null),t.error||!t.projectRoot)return void tI(null);t.isGit?tT.current?.delete(tr):tT.current?.add(tr),(0,ec._N)(tr,!!t.isGit),tI({forCwd:tr,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||(tE(null),tI(null))}),()=>{e=!0}},[tr,r7,ed]),(0,i.useEffect)(()=>{if(0!==eV.length&&!K&&null===tr){if(I&&!r8.current){r8.current=!0;let e=eV.find(e=>e.id===I);if(e){ti(e.cwd),j(e,!0);return}Y?.(),D&&rm(eK("sidebar.sessionNotFound"))}let e=b(eV);e.length>0&&ti(e[0].root)}},[eV,tr,I,D,K,j,Y,rm,eK]);let it=tN?tN.worktrees.find(e=>e.path===tr)??(tN.forCwd===tr&&tN.currentWorktreePath?tN.worktrees.find(e=>e.path===tN.currentWorktreePath):void 0)??tN.worktrees.find(e=>e.isMain):void 0,ir=it?.path??null,ii=(0,i.useCallback)(async function(e){let{remember:t=!0,purpose:n=tu}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??tm).trim();if(r&&!tb){tk(!0),tx(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 tx(s.error??`HTTP ${e.status}`);if(t){var i=s.cwd;try{window.localStorage.setItem(t5,i)}catch{}tg(s.cwd)}if(tp(!1),"new-session"===n){let e=rj.current,t=rw.current;rj.current=null,rw.current=null,e?.({cwd:s.cwd,projectKey:s.projectKey,projectRoot:s.projectRoot}),rI(()=>t?.isConnected?t:null);return}tS({cwd:s.cwd,root:s.projectRoot,key:s.projectKey}),ti(s.cwd)}catch(e){tx(e instanceof Error?e.message:String(e))}finally{tk(!1)}}},[tu,tm,tb,rI]),is=(0,i.useCallback)(()=>{tp("files"),tx(null)},[]),ia=(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 ii(n.cwd,{remember:!1,purpose:e})}catch{}},[ii]),io=(0,i.useRef)(ia);io.current=ia;let il=(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:eK(t.key,{...t.params,path:ep(t.params.path)})}:t}let s=i.path;return tI(n=>n&&n.projectKey===e.key&&!n.worktrees.some(e=>e.path===s)?{...n,worktrees:[...n.worktrees,{path:s,branch:t,isMain:!1}]}:n),ie(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[eK]),id=(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 ir===t&&ti(e.root),ie(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[ir]),ic=(0,i.useCallback)(()=>ie(e=>e+1),[]),iu=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&tS({cwd:t,root:r,key:n}),ti(t)},[]),ip=(0,i.useCallback)((e,t,n,r)=>{eJ(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&ti(e.cwd),j(e,!1,t,n,r)},[j]),ih=(0,i.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&tS({cwd:t,root:r,key:n}),ti(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]),im=(0,i.useRef)(ih);im.current=ih,(0,i.useImperativeHandle)(S,()=>({startNewSessionIn:e=>im.current(e),openFolderForNewSession:(e,t)=>{rj.current=e,rw.current=t,tx(null),tp("new-session")},openDefaultDirectoryForNewSession:e=>{rj.current=e,rw.current=null,io.current("new-session")},refreshWorktrees:ic,createWorktree:il}),[il,ic]);let ig=(0,i.useCallback)(()=>{tr&&ih({cwd:tr})},[tr,ih]),ix=(0,i.useMemo)(()=>b(eV),[eV]),ib=(0,i.useMemo)(()=>d(eV),[eV]),iv=(0,i.useMemo)(()=>new Map(ib.map(e=>[e.root.id,e])),[ib]),iy=(0,i.useMemo)(()=>{let e=new Set,t=new Map;for(let n of ib){if(!Z(n,r$,t4))continue;for(let t of q(n))e.add(t);let r=x(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[ib,r$,t4]),ik=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=x(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===iy.ids.size?eV:eV.filter(e=>!iy.ids.has(e.id)),t4,rz),[eV,iy,t4,rz]),ij=!!(tN?.isGit&&tN.isTopLevel&&tr&&r3?.key===tN.projectKey),iw=tr&&tN?.isGit&&r3?.key===tN.projectKey&&!ij?{label:eK("sidebar.openRepoRoot"),title:eK("sidebar.openRepoRootTitle")}:null,iS=!!(tr&&t$===tr),iC=iw??(!iS||ij||tr&&tT.current?.has(tr)?null:{label:eK("sidebar.worktrees"),title:eK("sidebar.checkingWorktrees")}),iN=r3?.key??null,iI=r3?.root??null,i$=(0,i.useMemo)(()=>iN&&iI?{key:iN,root:iI}:null,[iN,iI]),iE=(0,i.useMemo)(()=>0===nz.size?nL:Object.fromEntries([...[...nz].filter(e=>!Object.hasOwn(nL,e)).map(e=>[e,!0]),...Object.entries(nL)]),[nL,nz]),iT=(0,i.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=d(e.sessions),s=ee(t,r),a=0,o=[],l=new Map,c=new Map,u=new Set;for(let e of i){if(Z(e,t,n)){a++;continue}s.noteFamily(e);let r=Q(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),V(e,t,n)){o.push(e);continue}let d=l.get(r);d?d.push(e):l.set(r,[e])}let p=[{kind:"spacer",key:"top-spacer"}];if(o.length>0){let n=e=>H(_(t,e.root.id)?.pinnedAt)??0,r=o.map((e,t)=>({family:e,index:t})).sort((e,t)=>U(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:a,unread:l}=X(r,e);if(p.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:a,unread:l}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=en(r,8,er(e.moreShown,B),e);for(let n of t)p.push(et(n,"pinned",s.get(Q(n)),e));let a=es(r.length,t.length,n);a&&p.push({kind:"pinned-more",key:"pinned-more",...a,nextShown:i})}p.push({kind:"spacer",key:"pinned-spacer"})}let h=[...l.keys()],m=new Set(h),g=e=>{m.has(e)||(m.add(e),h.push(e))};for(let e of(r&&g(r.key),Object.keys(t.projects)))g(e);let f=h.map(e=>s.get(e)),x=new Map;(t.projectOrder??[]).forEach((e,t)=>{x.has(e)||x.set(e,t)});let b=e=>e.pinned||u.has(e.key),v=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!x.has(t.key)}).sort((e,n)=>Number(b(e.project))-Number(b(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),k=e=>H(t.projects[e.key]?.pinnedAt)??0,j=f.map((e,t)=>({project:e,index:t})),w=v(j.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>U(k(t.project),k(e.project))||e.index-t.index),S=v(j.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>U(y(e.project),y(t.project))||e.index-t.index),C=[...w,...S],N=e=>e.filter(e=>!x.has(e.key)).map(e=>e.key),I={pinned:N(w),other:N(S)},$=C.filter(e=>!x.has(e.key)&&b(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=l.get(n.key)??[],i=G(n,e.groupExpansion),{running:s,awaiting:a,unread:o}=X(r,e);if(p.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:a,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}=en(r,6,er(e.moreShown,n.key),e);for(let r of t)p.push(et(r,"group",n,e));let a=es(r.length,t.length,i);a&&p.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...a,nextShown:s})}}return C.length>0&&p.push({kind:"spacer",key:"footer-spacer"}),p.push({kind:"footer-open",key:"footer-open"}),a>0&&p.push({kind:"footer-archived",key:"footer-archived",count:a}),{rows:p,projects:C,archivedCount:a,unorderedKeysByBand:I,projectKeysToRecord:$}})({sessions:eV,uiState:r$,runningIds:t4,awaitingIds:ns,unreadIds:rz,selectedSessionId:k,currentProject:i$,groupExpansion:iE,moreShown:nW,pinnedCollapsed:nD}),[eV,r$,t4,ns,rz,k,i$,iE,nW,nD]),iM=n8.archiveMounted,iR=(0,i.useMemo)(()=>new Set(nU),[nU]),iA=(0,i.useMemo)(()=>iM?function(e){let{uiState:t,runningIds:n}=e,r=ee(t,e.currentProject),i=new Map;for(let s of d(e.sessions)){if(!Z(s,t,n))continue;r.noteFamily(s);let e=H(_(t,s.root.id)?.archivedAt)??0,a=Q(s),o=i.get(a);o?(o.families.push({family:s,archivedAt:e}),o.newest=Math.max(o.newest,e)):i.set(a,{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)=>U(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),a=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:a}),a)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>U(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(et(t,"archive",i,e))}return s}({sessions:eV,uiState:r$,runningIds:t4,awaitingIds:ns,unreadIds:rz,selectedSessionId:k,currentProject:i$,collapsed:iR}):[],[iM,eV,r$,t4,ns,rz,k,i$,iR]),iL=(0,i.useMemo)(()=>iA.flatMap(e=>"archive-group"===e.kind?[e]:[]),[iA]),iP=(0,i.useMemo)(()=>new Map(iT.projects.map(e=>[e.key,e])),[iT.projects]),iz=(0,i.useRef)(new Set),iO=iT.projectKeysToRecord,iW=r$.projectOrder?.length??0;(0,i.useEffect)(()=>{if(e5||!rT||!e7||iW>=1e3)return;let e=iz.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)}(iO,e);if(0!==t.length){for(let n of t)e.add(n);rR({action:"add-projects",keys:t})}},[rR,e5,iO,e7,iW,rT]);let iF=r$.projectNames,iD=(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(eb(s,n)));return i})(iT.projects,ix,iF),[iT.projects,ix,iF]),iB=(0,i.useMemo)(()=>{if(!tr||!r3)return null;let e=ij&&null!==tN;return{cwd:tr,project:eb(r3,iF),worktrees:e?tN.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?ir:null,projects:iD}},[tr,r3,ij,tN,ir,iD,iF]),i_=(0,i.useRef)(iB);i_.current=iB;let iH=iB?JSON.stringify([iB.cwd,iB.project.key,iB.project.root,iB.project.alias??null,iB.currentWorktreePath,iB.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,iB.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,i.useEffect)(()=>{C?.(i_.current)},[iH,C]);let iU=(0,i.useRef)(iN);(0,i.useLayoutEffect)(()=>{let e=iU.current;if(iU.current=iN,null===e||e===iN)return;let t=iP.get(e);nO(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(nL,t.key)?e:new Set(e).add(t.key))},[iN,nL,iP]);let iq=(0,i.useCallback)((e,t)=>{nP(e),(0,ec.wL)(e),nO(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)),nF(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))},[]),iK=(0,i.useCallback)(()=>(nM.current?.hidden?nT:nE).current??r_.current,[]),iZ=(0,i.useCallback)(e=>{let t=nM.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 iK()},[iK]),iV=(0,i.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=nM.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:iK()},[iK]),iJ=(0,i.useCallback)(async e=>{let t=await rR(e);return t||rf(e=>e+1),t},[rR]);(0,i.useEffect)(()=>{rg!==rx.current&&(rx.current=rg,rm(eK("sidebar.uiStateFailed",{error:rM??""})))},[rg,rM,rm,eK]);let iG=(0,i.useCallback)((e,t,n)=>{let r=iP.get(e),i=iP.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(iJ({action:"move-project",projectKey:e,anchorKey:t,position:n,add:iT.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rs.current+=1,ri({id:rs.current,at:Date.now(),rowKey:`group:${e}`}))},[iJ,iT.unorderedKeysByBand,iP]),iY=(0,i.useCallback)(e=>{nS||(nN(e),(0,ec.d9)(e))},[nS]),iX=(0,i.useCallback)(e=>{e!==n0.current&&nJ(e?"out":"in"),n$(e),(0,ec.oh)(e)},[nJ]),iQ=(0,i.useCallback)(e=>{let t=e.target;t instanceof Element&&nA.current.set(t,t.scrollTop)},[]);(0,i.useLayoutEffect)(()=>{for(let e of[nM.current,nR.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=nA.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[nC,nK,nS,nI]);let i0=(0,i.useCallback)(e=>{if(rn(null),n2(!0),tW(!1),iY("sessions"),void 0!==e){if(nU.includes(e)){let t=nU.filter(t=>t!==e);nq(t),(0,ec.zY)(t)}rs.current+=1,rl({id:rs.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[nU,n2,iY]),i1=(0,i.useRef)(null),i2=(0,i.useRef)(nK),i4=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(i2.current===nK)return;if(i2.current=nK,nK)return void nn(i1.current);let e=nM.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:iK();nn(t),t&&document.activeElement===t&&(i4.current=t)},[nK,iK]);let i8=(0,i.useRef)(null),i6=(0,i.useRef)(nS);(0,i.useLayoutEffect)(()=>{if(i6.current===nS)return;i6.current=nS;let e=i8.current;e&&(!e.isConnected||0===e.getClientRects().length)&&nn(iK())},[nS,iK]);let i3=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"===nC?"files":"sessions";iY(t),("sessions"===t?nE:nT).current?.focus()},i5=(0,i.useCallback)((e,t)=>{iJ({action:"set",ids:[e.root.id],pinned:t})},[iJ]),i9=(0,i.useCallback)((e,t)=>{var n;if(t){let t=rO.current.unreadMarks;rW([e.root.id,...q(e).filter(e=>t.has(e))])}let r=rO.current.readAt,i=r&&Object.prototype.hasOwnProperty.call(r,e.root.id)?r[e.root.id]:void 0,s=(n=nm.current.toServer(),void 0===i?n:Math.max(n,i+1));nc(n=>{let r=new Map(n);if(t)for(let t of q(e))r.delete(t);else r.set(e.root.id,s);return r})},[rW]),i7=(0,i.useCallback)(e=>{0!==e.length&&nc(t=>{let n=new Map(t);for(let[t,r]of e)t===rc.current||n.has(t)||n.set(t,r);return n.size===t.size?t:n})},[]),se=(0,i.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=rA(t.map(e=>e.root.id)),r=t.flatMap(e=>q(e)),i=r.flatMap(e=>{let t=nd.get(e);return void 0!==t&&rz.has(e)?[[e,t]]:[]});for(let e of F(t))iJ({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=>q(e)));i7(i.filter(e=>{let[t]=e;return n.has(t)}))});i.length>0&&nc(e=>{let t=new Map(e);for(let e of r)t.delete(e);return t}),rm(1===t.length?eK("sidebar.archivedToast",{title:nt(ty(t[0].root),28)}):eK("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:eK("sidebar.undo"),onClick:()=>{for(let e of F(n))iJ({action:"restore",entries:e});i7(i),rI(()=>iZ(t[0].root.id))}},{id:"view",label:eK("sidebar.viewArchive"),onClick:()=>i0()}])},[iJ,rI,iZ,i0,i7,rm,rA,eK,nd,rz]),st=(0,i.useCallback)(e=>{q(e).some(e=>t4.has(e))||se([e])},[se,t4]),sn=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=rA(t);for(let e of F(t))iJ({action:"set",ids:e,archived:!1});rm(1===e.length?eK("sidebar.restoredToast",{title:nt(ty(e[0].root),28)}):eK("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:eK("sidebar.undo"),onClick:()=>{for(let e of F(n))iJ({action:"restore",entries:e});rI(()=>iZ(e[0].root.id))}}])},[iJ,iZ,rI,rm,rA,eK]),sr=(0,i.useCallback)(e=>sn([e]),[sn]),si=(0,i.useCallback)(e=>{e.root.transient||(re(null),n3(e.root.id))},[]),ss=(0,i.useCallback)(async(e,t)=>{let n=e.root,r=ty(n),i=t.trim();if(n3(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})}),rX()}catch{}},[rX]),sa=(0,i.useCallback)(e=>{n9(e.key)},[]),so=(0,i.useCallback)(e=>{n9(t=>t===e?null:t),rI(()=>iV(e))},[rI,iV]),sl=(0,i.useCallback)((e,t)=>{so(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===J(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&iJ(n)},[iJ,so]),sd=(0,i.useCallback)(async e=>{let t=e.root;if(!t.transient){re(e=>e===t.id?null:e);try{await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"}),eh?.(t.id),rX()}catch{}}},[rX,eh]),sc=(0,i.useCallback)((e,t)=>{t?sd(e):(n3(null),re(e.root.id))},[sd]),su=(nS||"sessions"===nC)&&!nK&&!(tO&&""!==tF.trim()),sp=(0,i.useRef)(null),sh=(0,i.useRef)(null),sm=(0,i.useRef)(null);(0,i.useEffect)(()=>{k!==sh.current&&(sh.current=k,sp.current=k);let e=sp.current;if(!e||e5||!rE||!n_||!su)return;sp.current=null;let t=sm.current;sm.current=null;let n=function(e,t){let n=c(e.sessions,t);if(!n||Z(n,e.uiState,e.runningIds))return null;let r=Q(n);if(V(n,e.uiState,e.runningIds))return{rowKey:`session:pinned:${n.root.id}`,projectKey:r,unfoldPinned:e.pinnedCollapsed,unfoldGroup:!1};let i=Object.hasOwn(e.groupExpansion,r)&&!1===e.groupExpansion[r];return{rowKey:`session:group:${n.root.id}`,projectKey:r,unfoldPinned:!1,unfoldGroup:i}}({sessions:eV,uiState:r$,runningIds:t4,groupExpansion:iE,pinnedCollapsed:nD},e);if(n){if(n.unfoldPinned&&(nB(!1),(0,ec.Lc)(!1)),n.unfoldGroup){let e={...nL};delete e[n.projectKey],e[n.projectKey]=!0,iq(e,[n.projectKey])}rs.current+=1,ri({id:rs.current,at:Date.now(),rowKey:n.rowKey,block:"nearest",...t?.sessionId===e?{takeFocusFrom:t.takeFocusFrom}:{}})}},[k,eV,r$,t4,iE,nL,nD,e5,rE,n_,su,iq]);let sg=(e,t)=>{if(i4.current=null,nK){let e=nM.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&nA.current.delete(e),n2(!1)}let n=t?`[data-row-key="${CSS.escape(t)}"]`:null;sm.current={sessionId:e.id,takeFocusFrom:e=>null!==n&&null!==e.closest(n)||e===i4.current},ip(e,void 0,void 0,{keepSidebarOpen:null!==t}),rX()},sf=(0,i.useRef)(sg);sf.current=sg;let sx=(0,i.useRef)(new Set),sb=(0,i.useCallback)(async e=>{let t=e.family.root;if(t.transient||sx.current.has(t.id))return;sx.current.add(t.id);let n=rc.current;try{var r;let i,s,a=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),o=await a.json().catch(()=>({}));if(!a.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 ${a.status}`);rm(eK(e,t)),"not_found"===o.code&&rX();return}let l=o.session,d=ty(l),{head:c,tail:u}=(r=eK("sidebar.forkedToast",{title:d}),((s=(i=eg(d)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:eK("sidebar.forkedToast",{title:nt(d,28)}),tail:void 0});if(rc.current!==n){eJ(e=>e.some(e=>e.id===l.id)?e:[l,...e]);let e=nm.current.toServer();nc(t=>new Map(t).set(l.id,e)),rX(),rm(c,[{id:"open",label:eK("sidebar.open"),onClick:()=>sf.current(l,null)}],u);return}sf.current(l,e.key),rm(c,[],u)}catch(e){rm(eK("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{sx.current.delete(t.id)}},[rX,rm,eK]),sv=(0,i.useCallback)(e=>{e.root.transient||window.open(p(e.root.id),"_blank","noopener,noreferrer")},[]),sy=(0,i.useCallback)((e,t,n)=>{e.status.transient||rn({kind:"row",row:e,anchor:t,opener:n})},[]),sk=(0,i.useCallback)((e,t)=>{let n=e.family.root;if(n.id===n6||n.id===n7)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:()=>{rX()}})){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?nr(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,a=s instanceof HTMLElement&&null!==r&&r.contains(s);rk.current=!a&&s instanceof HTMLElement&&s!==document.body?s:null,sy(e,i,a?s:null)},[n7,rX,sy,n6]),sj=(0,i.useMemo)(()=>({sessions:eV,uiState:r$,runningIds:t4,awaitingIds:ns,unreadIds:rz,selectedSessionId:k}),[eV,r$,t4,ns,rz,k]),sw=(0,i.useCallback)((e,t)=>{let n=ea(sj,e.key,6048e5,Date.now()).length;rn({kind:"group",project:e,olderCount:n,anchor:nr(t,"end"),opener:t})},[sj]),sS=(0,i.useCallback)(e=>{se(ea(sj,e.key,6048e5,Date.now()).flatMap(e=>{let t=iv.get(e);return t?[t]:[]}))},[se,iv,sj]),sC=(0,i.useCallback)((e,t)=>{rn(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),sN=(0,i.useRef)(new Set),sI=(0,i.useCallback)(async(e,t,n)=>{if(rn(null),!(0===t.length||sN.current.has(e))){sN.current.add(e),rm(eK("sidebar.deletingSessions"));try{let e=await eu(t,fetch);for(let t of e.deleted)eh?.(t);if(rX().then(()=>rI(n)),null!==e.error)return void rm(eK("sidebar.deleteFailed",{error:e.error}));let r=e.deletedRoots.length,i=[1===r?eK("sidebar.deletedOneToast"):eK("sidebar.deletedManyToast",{count:r})];e.running.length>0&&i.push(eK("sidebar.keptRunningToast",{count:e.running.length})),rm(i.join(" \xb7 "))}finally{sN.current.delete(e)}}},[rI,rX,eh,rm,eK]),s$=(0,i.useCallback)(e=>{let{ids:t}=eo(sj,e.key);sI(`project:${e.key}`,t,()=>iV(e.key))},[sI,iV,sj]),sE=(0,i.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:nM.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=i1.current;return r&&r.getClientRects().length>0?r:iK()},[iK]),sT=(0,i.useCallback)(e=>e.flatMap(e=>{let t=iv.get(e);return t?[t]:[]}),[iv]),sM=(0,i.useCallback)((e,t)=>{rn({kind:"archive-group",project:e,anchor:nr(t,"end"),opener:t})},[]),sR=(0,i.useCallback)(e=>{rn(t=>t?.kind==="archive"?null:{kind:"archive",anchor:nr(e,"end"),opener:e})},[]),sA=(0,i.useCallback)(e=>{rn(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),sL=(0,i.useCallback)(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];for(let r of d(e.sessions))if((void 0===t.projectKey||Q(r)===t.projectKey)&&Z(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=H(_(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(sj,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[sj]),sP=(0,i.useCallback)(e=>{let t=sL(e);sI("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?sE(null):sE(e.projectKey))},[sL,sE,sI]),sz=(0,i.useCallback)(e=>{nq(e),(0,ec.zY)(e)},[]),sO=(0,i.useCallback)(e=>{let t=iL.map(e=>e.project.key),n=nU.filter(e=>!t.includes(e));sz(e?n:[...n,...t])},[nU,iL,sz]),sW=(0,i.useCallback)((e,t)=>{let n=nU.includes(e);if(t)return void sO(n);let r=nU.filter(t=>t!==e);sz(n?r:[...r,e])},[nU,sz,sO]),sF=(0,i.useCallback)(e=>{rn(null),ih(ef(e,tr))},[tr,ih]),sD=(0,i.useCallback)(()=>rn(null),[]);(0,i.useEffect)(()=>{if(null!==rt)return;let e=rk.current;if(rk.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rt]);let sB=nK?iA:iT.rows;(0,i.useEffect)(()=>{rt?.kind!=="row"||sB.some(e=>e.key===rt.row.key)||rn(null),rt?.kind!=="archive-group"||sB.some(e=>e.key===`archive:${rt.project.key}`)||rn(null)},[rt,sB]);let s_=rt?.kind==="row"?sB.find(e=>"session"===e.kind&&e.key===rt.row.key)??rt.row:null,sH=(0,i.useCallback)(e=>{ip(e.root)},[ip]),sU=(0,i.useCallback)(e=>{let t={...nL};for(let n of iT.projects)delete t[n.key],t[n.key]=e(n);iq(t,null)},[nL,iT.projects,iq]),sq=(0,i.useCallback)((e,t)=>{let n=iP.get(e);if(!n)return;let r=!G(n,iE);if(t)return void sU(()=>r);let i={...nL};delete i[e],i[e]=r,iq(i,[e])},[nL,iP,iq,sU,iE]),sK=(0,i.useCallback)(e=>{let t=iT.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===B);(t?.kind==="group-more"||t?.kind==="pinned-more")&&nF(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(er(n,e),Math.floor(r))}})},[iT.rows]),sZ=(0,i.useCallback)(e=>{nF(t=>ei(t,e))},[]),sV=(0,i.useCallback)(e=>{rb.current=e,ry(e=>e+1),nS?iX(!1):iY("files")},[iX,nS,iY]),sJ=nS?n4.open:"files"===nC;(0,i.useEffect)(()=>{let e=rb.current;e&&sJ&&(rb.current=null,"project-list"===e?tC.current?.openMenu("project"):"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tC.current?.button("project")?.focus({preventScroll:!0}))},[sJ,rv]);let sG=e=>{let{heading:t,headingTitle:n,notes:i,count:s,onConfirm:a,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:a,children:eK("sidebar.deleteCount",{count:s})}),!eZ&&(0,r.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:o,children:eK("sidebar.cancel")})]})]})},sY=(e,t)=>sG({heading:t?eK("sidebar.deleteArchivedInProjectHeading",{name:t.name}):eK("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[eK("sidebar.deleteArchivedMessage")],count:sL(e).length,onConfirm:()=>sP(e),onCancel:()=>sA(void 0)}),sX="",sQ=null;if(rt?.kind==="row"&&s_)g=ty(s_.family.root),sX=eK("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"},{kind:"action",id:"share",shortcut:"S"},{kind:"action",id:"copy-session-id",shortcut:"I"},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:"share",shortcut:"S"},{kind:"action",id:"copy-session-id",shortcut:"I"},{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"}]})(s_.context,s_.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=eK(t9[e.id]);return{type:"item",id:e.id,label:"delete"===e.id||"share"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,r.jsx)(tv.Gb,{});case"pin":return(0,r.jsx)(tv.ts,{});case"unpin":return(0,r.jsx)(tv.UT,{});case"rename":return(0,r.jsx)(tv.R2,{});case"fork":return(0,r.jsx)(tv.o5,{});case"share":return(0,r.jsx)(tv.li,{});case"copy-session-id":return(0,r.jsx)(tv.Td,{});case"mark-read":return(0,r.jsx)(tv.TA,{});case"mark-unread":return(0,r.jsx)(tv.Zy,{});case"archive":return(0,r.jsx)(tv.kb,{});case"unarchive":return(0,r.jsx)(tv.G2,{});case"delete":return(0,r.jsx)(tv.uc,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?eK("sidebar.cannotArchiveRunning"):void 0,onSelect:t=>{let{shiftKey:n,keepOpen:r}=t;return((e,t,n,r)=>{let{family:i}=t;switch(e){case"open-new-tab":sv(i);break;case"pin":i5(i,!0);break;case"unpin":i5(i,!1);break;case"rename":si(i);break;case"fork":sb(t);break;case"share":r?.(),rn(e=>e?.kind==="row"&&e.row.key===t.key?{...e,share:!0}:e);break;case"copy-session-id":(0,tc.D)(i.root.id).then(()=>rm(eK("sidebar.sessionIdCopied")),()=>{});break;case"mark-read":i9(i,!0);break;case"mark-unread":i9(i,!1);break;case"archive":st(i);break;case"unarchive":sr(i);break;case"delete":sc(i,n)}})(e.id,s_,n,r)}}}),rt.share&&(v=void 0,sQ=(0,r.jsx)(t1,{sessionId:s_.family.root.id,onCopied:()=>rm(eK("share.copiedToast")),onStopped:()=>rm(eK("share.stoppedToast"))}),f=320);else if(rt?.kind==="group"){let e,t,i,a,o,l=iP.get(rt.project.key)??rt.project;g=l.name,sX=eK("sidebar.projectActions",{name:l.name}),n=l,s=rt.olderCount,e=iy.countByProject.get(n.key)??0,t=eo(sj,n.key),i=el(iT.projects,n.key,"up"),a=el(iT.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:eK("sidebar.renameProject"),icon:(0,r.jsx)(tv.R2,{}),onSelect:()=>sa(n)}:{type:"item",id:e,label:eK("sidebar.resetProjectName"),icon:(0,r.jsx)(tv.G2,{}),onSelect:()=>{iJ({action:"rename-project",projectKey:n.key,name:null})}}),v=[{type:"item",id:"pin-project",label:eK(n.pinned?"sidebar.unpinProject":"sidebar.pinProject"),icon:n.pinned?(0,r.jsx)(tv.UT,{}):(0,r.jsx)(tv.ts,{}),onSelect:()=>{iJ({action:"pin-project",projectKey:n.key,root:n.root,pinned:!n.pinned})}},...o,{type:"item",id:"open-in-files",label:eK("sidebar.openInFilesTab"),icon:(0,r.jsx)(tv.sj,{}),onSelect:()=>{n.current||ti(n.root),sV("project-button")}},{type:"item",id:"open-new-tab",label:eK("sidebar.openInNewTab"),icon:(0,r.jsx)(tv.Gb,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=ef(e,tr);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:eK("sidebar.moveProjectUp"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&iG(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:eK("sidebar.moveProjectDown"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-down"}),disabled:null===a,onSelect:()=>{a&&iG(n.key,a.anchorKey,a.position)}},{type:"item",id:"collapse-others",label:eK("sidebar.collapseOtherGroups"),icon:(0,r.jsx)(tv.zp,{}),disabled:iT.projects.every(e=>G(e,iE)===(e.key===n.key)),onSelect:()=>sU(e=>e.key===n.key)},{type:"item",id:"expand-all",label:eK("sidebar.expandAllGroups"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-down"}),disabled:iT.projects.every(e=>G(e,iE)),onSelect:()=>sU(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:eK("sidebar.archiveOlderThanWeek",{count:s}),icon:(0,r.jsx)(tv.kb,{}),disabled:0===s,onSelect:()=>sS(n)},{type:"item",id:"view-archived",label:eK("sidebar.viewArchived",{count:e}),icon:(0,r.jsx)(tv.kb,{}),disabled:0===e,onSelect:()=>i0(n.key)},{type:"item",id:"delete-all",label:eK("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),sC(n.key,!0)}}],rt.askDelete&&(sQ=(e=>{let{ids:t,running:n}=eo(sj,e.key);return sG({heading:eK("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[eK("sidebar.deleteProjectSessionsMessage"),...n>0?[eK("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>s$(e),onCancel:()=>sC(e.key,!1)})})(l)),f=264}else if(rt?.kind==="archive-group"){let e,t=iL.find(e=>e.project.key===rt.project.key)?.project??rt.project;g=t.name,sX=eK("sidebar.archivedProjectActions",{name:t.name}),v=[{type:"item",id:"restore-all",label:eK("sidebar.restoreAllArchived",{count:(e=sL({projectKey:t.key})).length}),icon:(0,r.jsx)(tv.G2,{}),disabled:0===e.length,onSelect:()=>sn(sT(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:eK("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sA("all")}}],rt.askDelete&&(sQ=sY({projectKey:t.key},t)),f=248}else if(rt?.kind==="archive"){let e,t,n;g=eK("sidebar.archived"),sX=eK("sidebar.archiveActions"),e=sL("all"),t=sL("old"),n=iL.filter(e=>!e.expanded).length,v=[{type:"item",id:"collapse-all",label:eK("sidebar.collapseAllGroups"),icon:(0,r.jsx)(tv.zp,{}),disabled:n===iL.length,onSelect:()=>sO(!1)},{type:"item",id:"expand-all",label:eK("sidebar.expandAllGroups"),icon:(0,r.jsx)(tv.zp,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>sO(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:eK("sidebar.restoreAllArchived",{count:e.length}),icon:(0,r.jsx)(tv.G2,{}),disabled:0===e.length,onSelect:()=>sn(sT(e))},{type:"item",id:"delete-old",label:eK("sidebar.deleteOldArchived",{count:t.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),sA("old")}},{type:"item",id:"delete-all",label:eK("sidebar.deleteAllArchived",{count:e.length}),icon:(0,r.jsx)(tv.uc,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),sA("all")}}],rt.askDelete&&(sQ=sY(rt.askDelete,null)),f=280}let s0={layout:eZ?"mobile":"desktop",loading:e5||!rE,error:tt,renamingRootId:n6,renamingProjectKey:n5,confirmDeleteRootId:n7,activeMenuRowKey:rt?.kind==="row"?rt.row.key:rt?.kind==="group"?`group:${rt.project.key}`:rt?.kind==="archive-group"?`archive:${rt.project.key}`:null,onSelectFamily:sH,onToggleGroup:sq,onShowMore:sK,onShowLess:sZ,onTogglePinned:()=>{let e=!nD;nB(e),(0,ec.Lc)(e),e&&nF(e=>ei(e,B))},onArchiveFamily:st,onRestoreFamily:sr,onOpenRowMenu:sy,onRowContextMenu:sk,onRenameCommit:(e,t)=>{ss(e,t)},onRenameCancel:()=>n3(null),onRenameProjectCommit:sl,onRenameProjectCancel:()=>{n5&&so(n5)},onDeleteConfirm:e=>{sd(e)},onDeleteCancel:()=>{re(null),n7&&rI(()=>iZ(n7))},onGroupNew:sF,onGroupMenu:sw,onPinEmptyGroup:e=>{iJ({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),rI(()=>iV(e.key))},onToggleArchiveGroup:sW,onArchiveGroupMenu:sM,onOpenOtherProject:()=>{sV("project-list")},onOpenArchive:()=>i0(),onMoveGroup:iG},s1=tr??em??null,s2=s1&&tB>0?eK("sidebar.changedFiles",{count:tB}):void 0,s4=(0,i.useRef)(null),s8=!s1||0===tB;(0,i.useLayoutEffect)(()=>{let e=s4.current;if(s8&&e&&i8.current===e){var t,n;let r;t=document,n=iK(),(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}):e$(t,r)}},[s8,iK]);let s6=nS||"sessions"===nC,s3=!nS&&"files"===nC&&null!==s1,s5=(t=(nS?["below",eK("sidebar.new")]:["tabs",eK("sidebar.tabSessions"),eK("sidebar.tabFiles"),eK("sidebar.new"),s1&&tB>0?tB:"",nC]).join("\n"),m=(0,i.useCallback)(()=>{let e=rD.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[rD]),(0,i.useLayoutEffect)(()=>{let e=rD.current;if(!e)return;m();let t=new ResizeObserver(m);return t.observe(e),()=>t.disconnect()},[rD,m,t]),m),s9=iT.archivedCount,s7=nS?13:14,ae=(0,r.jsx)(t3,{onClick:()=>{s1&&ey?.(s1)},disabled:!s1||!ey,title:eK("terminal.open"),children:(0,r.jsx)(tv.k3,{size:s7})}),at=(0,r.jsx)(t3,{onClick:()=>{r0().then(e=>{e&&nS&&iX(!1)})},disabled:!s1||r2,title:r2?eK(tG?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):r1,children:(0,r.jsx)(tv.sj,{size:s7})}),an=(0,r.jsx)(t3,{onClick:()=>{nS&&nI&&iX(!1),nj.current?.openUploadPicker()},disabled:!s1||tA,title:eK("sidebar.uploadFilesTitle"),children:(0,r.jsx)(tv.JM,{size:s7})}),ar=(0,r.jsx)(t3,{onClick:()=>{eP?eP():tR(e=>e+1),tJ(!0),nk.current&&clearTimeout(nk.current),nk.current=setTimeout(()=>tJ(!1),2e3)},disabled:!s1,title:eK("sidebar.refreshExplorer"),done:tV,children:tV?(0,r.jsx)(tv.Sr,{size:s7}):(0,r.jsx)(tv.fN,{size:s7})}),ai=e=>(0,r.jsx)(t3,{onClick:()=>{let e=!tK;tZ(e),(0,ec.qM)(e)},disabled:!s1,title:eK("sidebar.showIgnoredFiles"),pressed:tK,className:e,children:(0,r.jsx)(tv.bM,{size:s7})}),as=(0,r.jsx)(t3,{ref:s4,onClick:()=>{if(nS&&nI){iX(!1),tU(!1);return}tU(e=>!e)},disabled:s8,title:eK("sidebar.changedFiles",{count:tB}),pressed:!s8&&!tH,children:(0,r.jsx)(tv.Vz,{size:s7})}),aa=(0,r.jsx)(t3,{onClick:()=>{s1&&ew?.(s1)},disabled:!s1||!ew,title:eK("sidebar.openGitGraph"),children:(0,r.jsx)(tv.WQ,{size:s7})});return(0,r.jsxs)("div",{ref:rG,className:`session-sidebar${nS?" is-files-below":""}${nS&&nI?" is-files-collapsed":""}${nS&&n4.moving?" is-files-folding":""}${ru?" has-toast":""}`,style:{"--sidebar-files-height":`${rV.width}px`},onFocus:e=>{i8.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(i8.current=null))},children:[tu&&(0,r.jsx)(to,{initialPath:tm,busy:tb,error:tf,onCancel:()=>{let e="new-session"===tu?rw.current:null;rj.current=null,rw.current=null,tp(!1),tx(null),e&&rI(()=>e.isConnected?e:null)},onSelect:e=>void ii(e)}),(0,r.jsxs)("div",{ref:rD,className:"sidebar-header",children:[nS&&(0,r.jsx)(th,{onWidthChange:s5}),!nS&&(0,r.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":eK("sidebar.tabsLabel"),children:[(0,r.jsxs)("button",{ref:nE,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===nC,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===nC?0:-1,className:`sidebar-tab${"sessions"===nC?" is-selected":""}`,onClick:()=>iY("sessions"),onKeyDown:i3,children:[(0,r.jsx)(tv.b1,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eK("sidebar.tabSessions")})]}),(0,r.jsxs)("button",{ref:nT,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===nC,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===nC?0:-1,title:s2,className:`sidebar-tab${"files"===nC?" is-selected":""}`,onClick:()=>iY("files"),onKeyDown:i3,children:[(0,r.jsx)(tv.sj,{size:13,className:"sidebar-tab-icon"}),(0,r.jsx)("span",{className:"sidebar-tab-label",children:eK("sidebar.tabFiles")}),s1&&tB>0&&(0,r.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tB})]})]}),(0,r.jsx)("span",{className:"sidebar-header-spacer"}),(0,r.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:ig,disabled:!tr,title:tr?eK("sidebar.newSessionTitle",{path:tr}):eK("sidebar.selectProject"),children:[(0,r.jsx)(tv.c1,{size:12}),(0,r.jsx)("span",{className:"sidebar-new-label",children:eK("sidebar.new")})]}),(0,r.jsx)("button",{ref:r_,type:"button",onClick:()=>{if(s3)return void tz(e=>!e);if(!s6){iY("sessions"),tW(!0);return}tW(e=>!e)},title:s3?eK("sidebar.searchFiles"):eK("sidebar.toggleSessionSearch"),"aria-label":s3?eK("sidebar.searchFiles"):eK("sidebar.toggleSessionSearch"),"aria-expanded":s3?tP:tO,"aria-controls":s3?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(s3?tP:tO)?" is-active":""}`,children:(0,r.jsx)(tv.WI,{size:16})})]}),(0,r.jsxs)("div",{ref:nM,id:"session-sidebar-panel-sessions",role:nS?"region":"tabpanel","aria-label":nS?eK("sidebar.tabSessions"):void 0,"aria-labelledby":nS?void 0:"session-sidebar-tab-sessions",hidden:!nS&&"sessions"!==nC,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:iQ,children:[tO&&(0,r.jsx)("div",{className:"sidebar-search",children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tF,maxLength:200,"aria-label":eK("sidebar.searchSessions"),placeholder:eK("sidebar.searchSessions"),onChange:e=>tD(e.target.value),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.stopPropagation(),tD(""))},className:"sidebar-search-input"})}),(0,r.jsx)(tX,{open:tO,query:tF,selectedSessionId:k,onSelectSession:ip,archivedSessionIds:iy.ids,projectNames:iF,children:(0,r.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,r.jsx)("div",{className:"sidebar-sessions-view",hidden:n8.mainHidden,inert:n8.mainInert,children:(0,r.jsx)(tj,{...s0,rows:iT.rows,emptyLabel:eK("sidebar.noSessions"),reveal:rr,onRevealHandled:ra})}),n8.archiveMounted&&(0,r.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${n8.archiveClass?` ${n8.archiveClass}`:""}`,inert:n8.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&nQ()},children:[(0,r.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,r.jsxs)("button",{ref:i1,type:"button",className:"sidebar-archive-back",title:eK("sidebar.backToSessions"),"aria-label":`${eK("sidebar.backToSessions")}: ${eK("sidebar.archivedCount",{count:s9})}`,onClick:()=>n2(!1),children:[(0,r.jsx)(tv.zp,{size:13,className:"sidebar-icon-back"}),(0,r.jsx)("span",{children:eK("sidebar.archived")}),(0,r.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",s9]})]}),(0,r.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rt?.kind==="archive"?" is-active":""}`,title:eK("sidebar.archiveActions"),"aria-label":eK("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rt?.kind==="archive",disabled:0===iL.length,onClick:e=>sR(e.currentTarget),children:(0,r.jsx)(tv.Z4,{size:13})})]}),(0,r.jsx)(tj,{...s0,rows:iA,emptyLabel:eK("sidebar.noArchived"),reveal:ro,onRevealHandled:rd})]})]})})]}),nS&&n4.open&&(0,r.jsx)("div",{...rV.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${rV.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${eK("sidebar.resizeFiles")}: ${eK("sidebar.resizeFilesHint")}`}),(0,r.jsxs)("div",{ref:nR,id:"session-sidebar-panel-files",role:nS?"region":"tabpanel","aria-label":nS?eK("sidebar.tabFiles"):void 0,"aria-labelledby":nS?void 0:"session-sidebar-tab-files",hidden:!nS&&"files"!==nC,className:"sidebar-panel sidebar-files-panel",onScrollCapture:iQ,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&nG()},children:[nS&&(0,r.jsxs)("div",{className:"sidebar-files-section",children:[(0,r.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nI,"aria-controls":"session-sidebar-files-body",title:s2,onClick:()=>iX(!nI),children:[(0,r.jsx)(tv.zp,{size:12,strokeWidth:3,className:`session-tree-chevron${nI?"":" is-open"}`}),(0,r.jsx)("span",{className:"sidebar-files-section-label",children:eK("sidebar.tabFiles")}),s2&&(0,r.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tB]})]}),(0,r.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":eK("sidebar.fileActions"),children:[ae,at,an,ar,ai(),as,aa,(0,r.jsx)(t3,{onClick:()=>{if(nI){tz(!0),sV("file-search");return}tz(e=>!e)},disabled:!s1,title:eK("sidebar.searchFiles"),expanded:tP,controls:"file-search-input",children:(0,r.jsx)(tv.WI,{size:13})})]})]}),(0,r.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nS&&n4.bodyHidden,inert:nS&&n4.bodyInert,children:[(0,r.jsxs)("div",{className:"sidebar-files-head",children:[(0,r.jsx)(tY,{handleRef:tC,layout:nS?"row":"stacked",context:iB??{project:null,worktrees:null,currentWorktreePath:null,projects:iD},mobile:eZ,label:eK("sidebar.projectAndWorktree"),placeholder:I&&!r8.current?"":eK("sidebar.selectProject"),homeDir:ts,projectActivity:ik,worktreeHint:iC,newWorktreeTitle:eK("sidebar.createWorktreeTitle"),onPick:iu,onUseDefaultDirectory:()=>{ia()},onOpenFolder:is,onRefreshWorktrees:ic,onCreateWorktree:il,onRemoveWorktree:id}),!nS&&s1&&(0,r.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":eK("sidebar.fileActions"),children:[ey&&ae,at,an,ar,ai("sidebar-files-views-start"),as,aa]})]}),s1&&r4&&(0,r.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,r.jsx)("span",{className:"sidebar-files-error-text",children:r4}),(0,r.jsx)(tl.R,{onClick:()=>t2(null),title:eK("files.dismissError")})]}),(0,r.jsx)("div",{ref:rB,className:"sidebar-files-scroll scrollbar-subtle",children:s1&&(0,r.jsx)(td.I,{ref:nj,cwd:s1,onOpenFile:ev??(()=>{}),refreshKey:tM,onAtMention:eW,onAtMentions:eB,onUploadBusyChange:tL,changesCollapsed:tH,onChangesCountChange:t_,fileSearchOpen:tP,onFileSearchOpenChange:tz,showHidden:tK})})]})]}),(0,r.jsx)(tq,{open:null!==rt,anchor:rt?.anchor??null,sheet:eZ,ariaLabel:sX,title:g,items:v,cancelLabel:eK("sidebar.cancel"),focusCancel:null!==sQ,onClose:sD,returnFocusTo:rt?.opener??null,width:f,children:sQ}),(0,r.jsx)(t8,{toast:ru,onDismiss:()=>rp(null),dismissLabel:eK("sidebar.dismiss")})]})}var ns=n(5772);let na=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,no=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,nl=/\x1B_pi:[^\x07\x1B\n]*(?:\x07|\x1B\\)/g;function nd(e){return e.replace(nl,"").replace(na,"")}function nc(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(no);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 nu(e,t){let n=nc(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function np(e){return nc(e)[0]?.char}let nh=/[▀-▟]/,nm=/https?:\/\/(?:\[[0-9A-Fa-f:.]+\])?[^\s<>"'`\]}。,、;:!?)」』】]*/g,ng=/^[.,;:!?]$/,nf={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:""},nx={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};var nb=n(48656),nv=n(19870),ny=n(14667);function nk(e,t){let n,r=t.shortWithArg??new Set,i=t.longWithArg??new Set,s=t.inPlace??new Set,a=[],o=!1,l=!1,d=e=>{t.targetDir&&(n=e)};for(let c=1;c<e.length;c++){let u=e[c],p=u.text;if(!u.quoted&&"--"===p){for(let t=c+1;t<e.length;t++)a.push(e[t].text);break}if(!u.quoted&&p.startsWith("--")){let r=p.indexOf("=");if(-1!==r){let e=p.slice(0,r);s.has(e)?o=!0:t.expression&&("--expression"===e||"--file"===e)?l=!0:"--target-directory"===e&&t.targetDir&&(n=p.slice(r+1));continue}if(s.has(p)){o=!0;continue}t.expression&&("--expression"===p||"--file"===p)&&(l=!0),i.has(p)&&c+1<e.length&&("--target-directory"===p&&d(e[c+1].text),c+=1);continue}if(!u.quoted&&p.startsWith("-")&&p.length>1&&!/^\d/.test(p.slice(1))){let n=p.slice(1);for(let i=0;i<n.length;i++){let a=`-${n[i]}`;if(s.has(a)&&(o=!0),t.expression&&("-e"===a||"-f"===a)&&(l=!0),r.has(a)){let t=n.slice(i+1);t.length>0?"-t"===a&&d(t):c+1<e.length&&("-t"===a&&d(e[c+1].text),c+=1);break}}continue}a.push(p)}return{operands:a,targetDirectory:n,inPlace:o,expressionSeen:l}}var nj=n(83236),nw=n(67803);function nS(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function nC(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function nN(e,t,n){let r=new Set,i=[],s=e=>{let t=(0,nv.XK)(e,n);!t||r.has(t)||(r.add(t),i.push({filePath:t}))};for(let n of e){var a;let e;if("toolCall"!==n.type||(a=n.toolName,!((0,ny.V4)(a)||(0,ny.iG)(a))&&!(0,ny.aP)(n.toolName)&&!(0,ny.Y2)(n.toolName)&&n.toolName!==nj.sp))continue;let r=t?.get(n.toolCallId);if(r&&!r.isError){if((0,ny.aP)(n.toolName))e=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(0,nw.IN)(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=(0,nw.dc)(n);if(i)return i.filter(e=>!r.has(e));if((0,nw.FK)(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=nC((0,nw.ND)(n.preview));if(e.length>0)return e}return nC((0,nw.oC)((0,nw.IN)(e)))}(n.input,r);else if((0,ny.Y2)(n.toolName)){let t=function(e){if(!e)return null;let t=e.command??e.cmd??e.script;return"string"==typeof t&&t.length>0?t:null}(n.input);e=t?function(e){if("string"!=typeof e||0===e.length||e.length>2e5)return[];let t=new Set,n=[];for(let r of function(e){let t=[],n=[],r="",i=!1,s="",a=()=>{(r.length>0||i)&&n.push({text:r,quoted:i}),r="",i=!1},o=()=>{a(),n.length>0&&t.push(n),n=[]};for(let t=0;t<e.length;t++){let n=e[t];if(s){if("\\"===n&&'"'===s&&e[t+1]){r+=e[t+1],t+=1;continue}if(n===s){s="";continue}r+=n;continue}if("'"===n||'"'===n){s=n,i=!0;continue}if("\\"===n){e[t+1]&&(r+=e[t+1],i=i||/[^\w./-]/.test(e[t+1]),t+=1);continue}if(";"===n||"|"===n||"&"===n||"\n"===n){("|"===e[t+1]||"&"===e[t+1])&&(t+=1),o();continue}if("#"===n&&0===r.length){let n=e.indexOf("\n",t);t=-1===n?e.length-1:n-1,o();continue}if(/\s/.test(n)){a();continue}r+=n}return o(),t}(e)){let e=function(e){let t=function(e){let t=0;for(;t<e.length;){let n=e[t].text,r=n.slice(n.lastIndexOf("/")+1);if("sudo"===r||"nohup"===r||"env"===r||"command"===r||"exec"===r||/^[\w]+=/.test(n)&&t+1<e.length){t+=1;continue}break}return e.slice(t)}(e);if(0===t.length)return null;let n=t[0].text,r=n.slice(n.lastIndexOf("/")+1),i=[];for(let e=0;e<t.length;e++){let n=t[e];if(n.quoted)continue;if(">"===n.text||">>"===n.text||"&>"===n.text||"&>>"===n.text){let n=t[e+1];n&&!n.text.startsWith("&")&&i.push(n.text),e+=1;continue}let r=n.text.match(/^(?:\d*>>|\d*>|&>>|&>|>&)(.+)$/);if(r){let e=r[1];e.startsWith("&")||i.push(e);continue}}let s=[];switch(r){case"tee":s=nk(t,{}).operands;break;case"touch":s=nk(t,{shortWithArg:new Set(["-d","-t","-r"]),longWithArg:new Set(["--date","--reference","--time"])}).operands;break;case"mv":case"cp":s=function(e){if(e.targetDirectory)return e.operands.map(t=>{let n=t.slice(t.lastIndexOf("/")+1)||t;return`${e.targetDirectory.replace(/\/+$/,"")}/${n}`});if(e.operands.length<2)return[];let t=e.operands[e.operands.length-1];return t.endsWith("/")?e.operands.slice(0,-1).map(e=>{let n=e.slice(e.lastIndexOf("/")+1)||e;return`${t.replace(/\/+$/,"")}/${n}`}):[t]}(nk(t,{shortWithArg:new Set(["-t","-S","-Z"]),longWithArg:new Set(["--target-directory","--suffix","--context"]),targetDir:!0}));break;case"sed":{let e=nk(t,{shortWithArg:new Set(["-e","-f"]),longWithArg:new Set(["--expression","--file"]),inPlace:new Set(["-i","--in-place"]),expression:!0});e.inPlace&&(s=e.expressionSeen?e.operands:e.operands.slice(1));break}case"truncate":s=nk(t,{shortWithArg:new Set(["-s","-r"]),longWithArg:new Set(["--size","--reference"])}).operands;break;case"dd":s=t.slice(1).flatMap(e=>{let t=e.text.match(/^of=(.+)$/);return t?[t[1]]:[]})}let a=[...i,...s].filter(e=>!(0===e.length||/[\$`]/.test(e)||/[*?\[]/.test(e)||e.startsWith("-")||e.startsWith("~")||e.startsWith("/dev/")));return a.length>0?a:null}(r);if(e){for(let r of e)if(!t.has(r)&&(t.add(r),n.push(r),n.length>=100))return n}}return n}(t):[]}else e=n.toolName===nj.sp?function(e){let{calls:t}=(0,nj.or)(e?.details),n=[];for(let e of t){if("ok"!==e.status||!(0,ny.V4)(e.name)&&!(0,ny.iG)(e.name))continue;let t=function(e){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return nS(t);return null}catch{let t=e.match(/"(?:file_path|path)"\s*:\s*"((?:[^"\\]|\\.)*)"/);return t?t[1].replace(/\\(.)/g,(e,t)=>"n"===t?"\n":"t"===t?" ":"r"===t?"\r":t):null}}(e.args);t&&n.push(t)}return n}(r):[nS(n.input)];for(let t of e)t&&s(t)}}return i}var nI=n(11316),n$=n(6483);function nE(e,t){let n=[],r=new Set;for(let i of e)if("assistant"===i.role)for(let e of i.content??[]){if("toolCall"!==e.type)continue;let i=t.get(e.toolCallId),s=(0,n$.G)(i?.details)?i?.details:null;s&&"starting"!==s.status&&"queued"!==s.status&&"running"!==s.status&&(r.has(s.sessionId)||(r.add(s.sessionId),n.push({sessionId:s.sessionId,cwd:s.worktreePath})))}return n}async function nT(e,t){let n,r=[],i=null;for(let s=0;s<t;s++){let t=new URLSearchParams({tail:"1000",deferThinking:"",deferMedia:""});n&&t.set("before",n);let s=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${t}`,{cache:"no-store"});if(!s.ok)throw Error(`context ${s.status}`);let a=await s.json();i??=a.cwd??null;let o=a.context??{},l=Array.isArray(o.messages)?o.messages:[];if(r.unshift(...l),!o.hasMore||!o.oldestEntryId)break;n=o.oldestEntryId}return{messages:r,cwd:i}}let nM=new Map,nR=new Map;function nA(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={...e,content:t};return n.omitUsage&&(r.usage=void 0),n.omitStop&&(r.stopReason=void 0,r.errorMessage=void 0),r}var nL=n(56038);function nP(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
3
3
|
|
|
4
4
|
`}function nz(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}var nO=n(2836),nW=n(64600),nF=n(2849);function nD(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 nB=new Map;function n_(e){return`parked-new:${e}`}function nH(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function nU(e){return!e.value&&0===e.images.length}function nq(e){let t=nB.get(e);return t?nH(t):null}function nK(e,t){nU(t)?nB.delete(e):nB.set(e,nH(t))}function nZ(e){nB.delete(e)}function nV(e,t){return e.trim()?t.trim()?`${e}
|
|
5
5
|
|
|
6
6
|
${t}`:e:t}function nJ(e,t,n,r){let i=[...t??[],...r].filter(nD).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:nV(e,n),images:i}}function nG(e,t,n){let r=nq(e)??{value:"",images:[]},i=nJ(t,n,r.value,r.images);return nK(e,i),i}function nY(e,t,n){if(e===t)return n?nH(n):nq(t);let r=nq(e),i=n&&!nU(n)?nH(n):r??(n?nH(n):null),s=nq(t);if(nZ(e),!i)return s;let a=s?nJ(s.value,s.images,i.value,i.images):i;return nK(t,a),nH(a)}var nX=n(3099);let nQ=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,n0=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,n1=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,n2=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,n4=/^[ \t]{0,3}(`{3,}|~{3,})/;function n8(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function n6(e){return"/mcp"===e.trim()}var n3=n(30527),n5=n(8436);let n9="pi-enter-send-mode",n7="enter",re=null,rt=new Set;function rn(){return null===re&&(re=function(){try{let e=window.localStorage.getItem(n9);return"ctrlEnter"===e?"ctrlEnter":"enter"}catch{return n7}}()),re}function rr(e){return rt.add(e),()=>{rt.delete(e)}}function ri(e){re=e;try{window.localStorage.setItem(n9,e)}catch{}rt.forEach(e=>e())}function rs(){return(0,i.useSyncExternalStore)(rr,rn,()=>n7)}var ra=n(23584),ro=n(74761);function rl(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 rd(e){let{active:t,onSelect:n,star:s,gutter:a=!!s,children:o}=e,l=(0,eQ.a)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=!!(s&&!s.isDefault),m=h&&(d||u||l);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:a?"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)(rl,{filled:!0,size:10})}),s&&h&&(0,r.jsx)("button",{type:"button",title:s.saveLabel,"aria-label":s.saveLabel,tabIndex:m?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:+!!m,pointerEvents:m?"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)(rl,{filled:!1,size:12})})]})}function rc(e){var t;let n,s,a,o,l,d,c,u,p,h,m,{options:g,value:f,onChange:x,onReselect:b,onClear:v,emptyLabel:y,selectedLabel:k,disabled:j=!1,busy:w=!1,isAutoSelection:S=!1,ariaLabel:C,variant:N="toolbar",placement:I="up",defaultValue:$,onSetDefault:E,allOptions:T,onShowAll:M}=e,{t:R}=(0,eX.s)(),A=(0,eQ.a)(),L=(0,i.useRef)(null),P=(0,i.useRef)(null),[z,O]=(0,i.useState)(!1),[W,F]=(0,i.useState)(null),[D,B]=(0,i.useState)(""),[_,H]=(0,i.useState)(!1),U=j||w,q=_?T:g,K=(t=q??[],(n=D.trim().toLocaleLowerCase())?t.filter(e=>`${e.name} ${e.providerName??""} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(n)):t),Z=!!M||g.length>8,V=(e,t)=>e?.find(e=>e.modelId===t.modelId&&e.provider===t.provider),J=()=>{_||M?.(),H(!_)},G=function(e){let t=[];for(let n of e){let e=t.find(e=>e.provider===n.provider);e?(e.options.push(n),e.providerName===e.provider&&n.providerName?.trim()&&(e.providerName=n.providerName.trim())):t.push({provider:n.provider,providerName:n.providerName?.trim()||n.provider,options:[n]})}return t}(K),Y=k??(f?(V(g,f)??V(T,f))?.name??f.modelId:y??(g.length>0?R("chat.selectModel"):R("chat.noModels")));(0,i.useEffect)(()=>{let e=e=>{L.current&&!L.current.contains(e.target)&&P.current&&!P.current.contains(e.target)&&(O(!1),B(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{if(!z)return;let e=()=>{let e=L.current?.querySelector("button")?.getBoundingClientRect();e?.height&&F({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)}},[z]),(0,i.useEffect)(()=>{U&&(O(!1),B(""))},[U]);let X="field"===N?{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:U?"var(--bg-panel)":"var(--bg)",color:U?"var(--text-dim)":"var(--text)",cursor:U?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:A?"flex-start":void 0,gap:6,width:A?"100%":void 0,maxWidth:A?"100%":220,height:A?44:32,padding:A?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:z?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:U?"not-allowed":"pointer",fontSize:12,opacity:U?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:L,className:`model-selector is-${N}${U?" is-disabled":""}`,style:{position:"relative",width:"field"===N||A?"100%":void 0,minWidth:0,flex:"toolbar"===N&&A?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&z&&(e.preventDefault(),e.stopPropagation(),B(""),O(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":C,"aria-haspopup":"listbox","aria-expanded":z,"aria-busy":w||void 0,disabled:U,title:w?R("chat.switchingModel"):U?Y:g.length>0||v?R("chat.changeModel"):R("chat.noAvailableModels"),style:X,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();F({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),O(e=>(e?B(""):H(!1),!e))},onMouseEnter:e=>{U||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(U){e.currentTarget.style.background="field"===N?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===N?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=z?"var(--bg-hover)":"field"===N?"var(--bg)":"none",e.currentTarget.style.color="field"===N?"var(--text)":"var(--text-muted)"},children:[w?(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:Y}),"field"===N&&(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"})})]}),z&&W&&(s=window.visualViewport?.offsetTop??0,a=window.visualViewport?.height??window.innerHeight,o=window.visualViewport?.width??window.innerWidth,d=(l=Math.min(W.top-6,s+a-8))-s-8,c=s+a-W.bottom-6-8,p=Math.max(120,Math.min((u="up"===I||d>c)?d:c,.6*a)),h=u?{top:l,transform:"translateY(-100%)"}:{top:W.bottom+6},m=A?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:W.left,width:"max-content",minWidth:W.width,maxWidth:Math.max(W.width,o-W.left-8)},(0,r.jsxs)("div",{ref:P,role:"listbox","aria-label":C,style:{position:"fixed",...h,...m,zIndex:500,display:"flex",flexDirection:"column",maxHeight:p,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:u?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[M&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px 0",fontSize:11},children:[[!1,!0].map(e=>(0,r.jsx)("button",{type:"button","aria-pressed":_===e,onClick:()=>{_!==e&&J()},style:{padding:"2px 7px",border:"1px solid",borderColor:_===e?"var(--border)":"transparent",borderRadius:4,background:_===e?"var(--bg-hover)":"none",color:_===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11},children:R(e?"chat.modelScopeAll":"chat.modelScopeScoped")},String(e))),!A&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:"Tab"})]}),Z&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:D,onChange:e=>B(e.target.value),onKeyDown:e=>{M&&"Tab"===e.key&&(e.preventDefault(),J())},placeholder:R("chat.filterModels"),"aria-label":R("chat.filterModels"),autoFocus:!A,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!A,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&&!D.trim()&&(0,r.jsx)(rd,{active:!f,gutter:!!E,onSelect:()=>{O(!1),B(""),v()},children:(0,r.jsx)(ru,{label:y??R("i18n.default")})}),0===G.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:q?D.trim()?R("chat.noMatchingModels"):R("chat.noAvailableModels"):R("agents.modelsLoading")}):G.map((e,t)=>(0,r.jsxs)("div",{children:[G.length>1&&(0,r.jsx)("div",{title:e.providerName===e.provider?void 0:e.provider,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:e.providerName===e.provider?"uppercase":"none"},children:e.providerName}),e.options.map(e=>(0,r.jsx)(rd,{active:e.modelId===f?.modelId&&e.provider===f?.provider,onSelect:()=>{let t;return t=e.modelId===f?.modelId&&e.provider===f?.provider,void(O(!1),B(""),!t||S?x(e.provider,e.modelId):b?.(e.provider,e.modelId))},star:E&&(!_||V(g,e))?{isDefault:e.modelId===$?.modelId&&e.provider===$?.provider,saveLabel:R("chat.saveDefaultModel"),defaultLabel:R("chat.defaultModel"),onSave:()=>{O(!1),B(""),E?.(e.provider,e.modelId)}}:void 0,children:(0,r.jsx)(ru,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function ru(e){let{label:t}=e;return(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let rp=["configured","chat-only","read-only","default","full"],rh={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},rm=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rg(e,t,n){return t<=0?0:((e+n)%t+t)%t}function rf(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function rx(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,a=e.selectionEnd;if(e.focus(),s===a&&t<=s&&n>=a){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-a;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else rf(e,t,e.selectionStart+(n-a),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||rf(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function rb(e){let t=e.scrollTop;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",e.scrollTop=t}function rv(e){e.selectionEnd===e.value.length&&(e.scrollTop=e.scrollHeight)}function ry(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,a=s?.parentElement,o="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&o?.observe(s),a&&o?.observe(a);let l=window.visualViewport;return l?.addEventListener("resize",i),l?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{o?.disconnect(),l?.removeEventListener("resize",i),l?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let rk=["auto","off","minimal","low","medium","high","xhigh","max"],rj={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 rw(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rS=[{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"},{name:"side",description:"chat.commandSide",source:"builtin",availableWhileStreaming:!0}];function rC(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return rS.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let rN=["builtin","extension","prompt","skill"],rI={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},r$={builtin:0,extension:1,prompt:2,skill:3};function rE(e,t){return"builtin"===e.source?t(e.description):e.description??""}function rT(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function rM(e){return{data:e.data,mimeType:e.mimeType}}function rR(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function rA(e){return(e??[]).filter(nD).slice(0,10).map(rR)}function rL(e){return"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rP(e){return"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 nD(r)?[r]:[]})}function rz(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function rO(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 rW(e){let{tone:t,title:n,body:i,onClose:s}=e,{t:a}=(0,eX.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":a("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 rF(e){let{cwd:t}=e,{t:n}=(0,eX.s)();return t?(0,r.jsx)(rW,{tone:"error",title:n("chat.cwdMissingTitle"),body:n("chat.cwdMissingBody",{cwd:t})}):null}function rD(e){let{error:t}=e,{t:n}=(0,eX.s)();return t?(0,r.jsx)(rW,{tone:"error",title:n("chat.modelError"),body:t}):null}function rB(e){let{warnings:t}=e,{t:n}=(0,eX.s)();return t&&0!==t.length?(0,r.jsx)(rW,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let r_=(0,i.memo)((0,i.forwardRef)(function(e,t){let n,s,a,o,l,{onSend:d,onAbort:c,onSteer:u,onSideChat:p,onFollowUp:h,isStreaming:m,model:g,isAutoModelSelection:f,modelNames:x,modelList:b,modelError:v,missingCwd:y,modelScopeWarnings:k,allModelList:j,onLoadAllModels:w,onModelChange:S,modelSwitching:C,defaultModel:N,onSetDefaultModel:I,onCompact:$,onAbortCompaction:E,isCompacting:T,compactError:M,onDismissCompactError:R,compactResult:A,toolPreset:L,onToolPresetChange:P,thinkingLevel:z,isAutoThinkingSelection:O=!1,onThinkingLevelChange:W,availableThinkingLevels:F,thinkingLevelMap:D,savedDefaultThinkingLevel:B,onSetDefaultThinkingLevel:_,retryInfo:H,queuedMessages:U,inputHistory:q=[],onRecallQueue:K,slashCommands:Z,slashCommandsLoading:V,onLoadSlashCommands:J,onBuiltinCommand:G,soundEnabled:Y,onSoundToggle:X,onAudioUnlock:Q,onPromptWithStreamingBehavior:ee,draftKey:et,cwd:en,onAttachFiles:er,compact:ei=!1}=e,{t:es}=(0,eX.s)(),{fontSize:ea}=(0,ra.Uh)(),{ui:eo,uiWeight:el}=(0,ro.VE)(),ed=(0,eQ.a)(),ec=ed?44:32,eu=rs(),[ep,eh]=(0,i.useState)(()=>et?nq(et)?.value??"":""),[em,eg]=(0,i.useState)(!1),[ef,ex]=(0,i.useState)(!1),[eb,ev]=(0,i.useState)(!1),[ey,ek]=(0,i.useState)(()=>et?rA(nq(et)?.images):[]),ej=ep.trimStart(),ew=0===ey.length&&ej.startsWith("!"),eS=ew&&ej.startsWith("!!"),[eC,eN]=(0,i.useState)(!1),[eI,e$]=(0,i.useState)(0),[eE,eT]=(0,i.useState)(null),[eM,eR]=(0,i.useState)(null),[eA,eL]=(0,i.useState)(!1),[eP,ez]=(0,i.useState)(null),[eO,eW]=(0,i.useState)(0),[eF,eD]=(0,i.useState)(!1),[eB,e_]=(0,i.useState)(!1),[eH,eU]=(0,i.useState)(0),[eq,eK]=(0,i.useState)(!1),eZ=(0,i.useRef)(!1),eV=(0,i.useRef)(null),[eJ,eG]=(0,i.useState)(null),[eY,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(null),e6=en&&e4?.cwd===en?e4.values:{},e3=(0,i.useRef)(null),e5=(0,i.useRef)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(0),ti=(0,i.useRef)(null),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(null),to=(0,i.useRef)([]),td=(0,i.useRef)(null),tc=(0,i.useRef)([]),tu=(0,i.useRef)([]),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tm=(0,i.useRef)(et),tg=(0,i.useRef)(ep),tf=(0,i.useRef)(ey),tx=(0,i.useRef)(0);tg.current=ep,tf.current=ey,(0,i.useImperativeHandle)(t,()=>({setText(e){let t=e3.current;if(!t){tg.current=e,eh(e);return}t.setSelectionRange(0,t.value.length),rx(t,0,t.value.length,e),eR(null),requestAnimationFrame(()=>rb(t))},pasteText(e){if(!e)return;let t=e3.current;t?(rx(t,t.selectionStart??t.value.length,t.selectionEnd??t.value.length,e),eR(null),requestAnimationFrame(()=>rb(t))):eh(t=>t+e)},insertIfEmpty(e){let t=e3.current;(t?t.value:ep).trim()||(tg.current=e,eh(e),eR(null),requestAnimationFrame(()=>{t&&(t.focus(),rb(t),rv(t))}))},replaceMessage(e){var t,n,r;let i=e3.current;if(t=i?i.value:ep,n=tf.current.length,r=tx.current,t.trim()||0!==n||0!==r)return;let s=rL(e),a=rA(rP(e));tg.current=s,tf.current=a,eh(s),eR(null),e_(!1),ek(e=>(e.forEach(rz),a)),requestAnimationFrame(()=>{i&&(i.focus(),rb(i),rv(i))})},prependText(e){if(!e.trim())return;let t=e3.current,n=[e,t?t.value:ep].filter(e=>e.trim()).join("\n\n");tg.current=n,eh(n),eR(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),rb(t),rv(t))})},rekeyDraft(e,t){if(e===t)return;if(tm.current!==e)return void nY(e,t);let n={value:tg.current,images:tf.current.map(rM)},r=nY(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(tm.current=t,i)return;let s=rA(r.images);tg.current=r.value,tf.current=s,eh(r.value),ek(e=>(e.forEach(rz),s)),eR(null),e_(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tm.current,i=n??r,s=i===r,a=!s&&i?nq(i):null,o=nJ(e,t,s?tg.current:a?.value??"",s?tf.current.map(rM):a?.images??[]);if(i&&nK(i,o),!s)return;let l=t?.length?[...rA(t).slice(0,Math.max(0,10-tf.current.length)),...tf.current].slice(0,10):tf.current;tg.current=o.value,tf.current=l,eh(t=>{let n=nV(e,t);return tg.current=n,n}),eR(null),e_(!1),t?.length&&ek(e=>{let n=Math.max(0,10-e.length),r=rA(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tf.current=i,i}),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),rb(e),rv(e))})},focus(){let e=e3.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=e3.current;if(!t)return void eh(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);rx(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),eR(null)},insertQuote(e){let t=e3.current;if(!t)return void eh(t=>t+nz(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;rx(t,n,r,nz(t.value.slice(0,n))+e),eR(null)},addImages(e){tb(e)}}));let tb=(0,i.useCallback)(async e=>{if(ei)return;let t=Math.max(0,10-tf.current.length-tx.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tx.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)}}));ek(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(rz);let r=[...t,...n];return tf.current=r,r})}finally{tx.current-=n.length}}},[ei]),tv=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",er?er(t):tb(t)},[er,tb]),ty=(0,i.useCallback)(e=>{ek(t=>{let n=[...t],[r]=n.splice(e,1);return r&&rz(r),tf.current=n,n})},[]),tk=(0,i.useCallback)(()=>{tf.current=[],ek(e=>(e.forEach(rz),[]))},[]),tj=(0,i.useCallback)(()=>{tg.current="",eh(""),eR(null),e_(!1),et&&nZ(et),tm.current&&tm.current!==et&&nZ(tm.current),tk(),e3.current&&(e3.current.style.height="auto")},[tk,et]);(0,i.useEffect)(()=>{et&&tm.current===et&&nK(et,{value:ep,images:ey.map(rM)})},[ey,et,ep]),(0,i.useEffect)(()=>{let e=tm.current;if(e===et)return;e&&nK(e,{value:tg.current,images:tf.current.map(rM)});let t=et?nq(et):null;tm.current=et;let n=t?.value??"",r=rA(t?.images);tg.current=n,tf.current=r,eh(n),eR(null),e_(!1),ek(e=>(e.forEach(rz),r))},[et]);let tw=(0,i.useCallback)(()=>{let e=e3.current;e&&(e.value?rb(e):(e.style.height="auto",e.style.overflowY="hidden"))},[]);(0,i.useLayoutEffect)(tw,[ep,ea,eo,el,tw]),(0,i.useEffect)(()=>{let e=e3.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tw())});return n.observe(e),()=>n.disconnect()},[tw]),(0,i.useEffect)(()=>{let e=e3.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),a=-1===s?e.length:s,o=e.slice(i,a),l=function(e){if(n2.test(e))return null;let t=nQ.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=n0.exec(e)??n1.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!l||t-i<l.length||function(e){let t=null;for(let n of e.split("\n")){let e=n4.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(l.length).trim()?{start:i,end:a,text:""}:{start:t,end:t,text:`
|
|
7
|
-
${r=null===l.number?l.marker:`${String(Number(l.number)+1).padStart(l.number.length,"0")}${l.delimiter}`,`${l.indent}${r}${l.spacing}${l.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)(()=>()=>{tf.current.forEach(rz)},[]),(0,i.useLayoutEffect)(()=>{if(eq){let e=e=>{e.target!==eV.current&&(eV.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=eV.current;eV.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[eq]);let tS=(0,i.useCallback)(async e=>{if(ey.length||!e.startsWith("/")||!G)return!1;if(eZ.current)return!0;eV.current=document.activeElement===e3.current?e3.current:null,eZ.current=!0,eK(!0);try{var t,n;let r=await G(e);if(!r.handled)return!1;return r.error||(t=tg.current,n=tf.current.length,0!==n||t.trim()!==e)||tj(),!0}finally{eZ.current=!1,eK(!1)}},[ey.length,tj,G]),tC=(0,i.useCallback)(async()=>{var e;let t=ep.trim();(t||ey.length)&&(Q?.(),(!m||rC(e=t)||n6(e))&&await tS(t)||(!m||t.startsWith("!")&&!ey.length)&&(tj(),d(t,ey.length?ey:void 0)))},[ep,ey,m,tS,d,tj,Q]),tN=!ei&&ep.startsWith("/")&&!/\s/.test(ep.slice(1))?ep.slice(1).toLowerCase():null,tI=(()=>{var e;let t,n;return null===tN?[]:(e=[...m?rS.filter(e=>e.availableWhileStreaming):rS,...Z??[]],((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)===tN||t===tN?0:n.startsWith(tN)||t.startsWith(tN)?1:t.includes(tN)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return rE(t,es).toLowerCase().includes(tN)})).sort((e,t)=>e.rank-t.rank||r$[e.command.source]-r$[t.command.source]||rm.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:t$,groups:tE}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=rN.map(i=>{let s=e.filter(e=>e.source===i),a="skill"!==i||n?s:[...s.filter(e=>!rT(e,t)),...s.filter(e=>rT(e,t))];return{source:i,items:a.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tI,e6,tN??""),tT=1===tI.length?es(tN?"chat.match":"chat.command"):es(tN?"chat.matches":"chat.commands",{count:tI.length}),tM=!!ep.trim()||ey.length>0,tR=ei||ed&&m,tA=ey.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)&&!eF;(0,i.useEffect)(()=>{0===ey.length&&eD(!1)},[ey.length]);let tL=(0,i.useCallback)((e,t)=>{if(!en)return void eR(null);let n=t??e.length;eR((0,nX.RO)(e.slice(0,n)))},[en]),tP=eM?.query??null,tz=i.useMemo(()=>null!==tP&&eJ&&eJ.cwd===en?(0,nX.R7)(eJ.entries,tP):[],[tP,eJ,en]),tO=!!(tP&&eJ?.truncated&&eJ.cwd===en);(0,i.useEffect)(()=>{if(!tO||!en||!tP)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(en)}&q=${encodeURIComponent(tP)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e2({cwd:en,query:tP,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tO,tP,en]);let tW=tO&&null!==e1&&e1.cwd===en&&e1.query===tP,tF=tW?e1.matches:tz,tD=null===eM?null:`${eM.start}:${+!!eM.quoted}:${eM.query}`;(0,i.useEffect)(()=>{if(null===tD){eL(!1),eW(0);return}eL(!0),eW(0)},[tD]);let tB=null!==eM;(0,i.useEffect)(()=>{if(!tB||!en)return;let e=tp.current;e&&e.cwd===en&&Date.now()-e.fetchedAt<1e4||th.current===en||(th.current=en,e0(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(en)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:en,entries:(0,nX.Yh)(e.files??[]),truncated:!!e.truncated}),tp.current={cwd:en,fetchedAt:Date.now()}}).catch(()=>{tp.current=null}).finally(()=>{th.current=null,e0(!1)}))},[tB,en]);let t_=(0,i.useCallback)(e=>{if(!eM)return;let t=e3.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eM.quoted&&'"'===t.value[n]?1:0),i=(0,nX.W)(e.path,e.isDir,eM.quoted),s=eM.start+i.cursorOffset;rx(t,eM.start,r,i.text,i.cursorOffset),eR((0,nX.RO)(t.value.slice(0,s)))},[eM]);(0,i.useEffect)(()=>{eO>=tF.length&&eW(Math.max(0,tF.length-1))},[tF.length,eO]),(0,i.useEffect)(()=>{tc.current.length=tF.length},[tF.length]),(0,i.useEffect)(()=>{eA&&tc.current[eO]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eO,eA]),(0,i.useEffect)(()=>{eH>=q.length&&eU(Math.max(0,q.length-1))},[q.length,eH]),(0,i.useEffect)(()=>{tu.current.length=q.length},[q.length]),(0,i.useEffect)(()=>{eB&&tu.current[eH]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eH,eB]);let tH=(0,i.useCallback)(e=>{eh(e),e_(!1),eU(0),eR(null),requestAnimationFrame(()=>{let t=e3.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),rb(t),rv(t))})},[]),tU=(0,i.useCallback)(e=>{let t=`/${e.name} `;eh(t),eN(!1),e$(0),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),rb(e))})},[]),tq=(0,i.useCallback)(()=>{let e=ep.trim();e&&!ey.length&&p&&(tj(),p(e))},[ep,ey,p,tj]),tK=(0,i.useCallback)(e=>{let t=ep.trim();if(!t&&!ey.length)return;if(t.startsWith("!")&&!ey.length)return void tC();Q?.();let n=ey.length?ey:void 0,r=()=>{if(t.startsWith("/")&&ee){tj(),ee(t,"steer"===e?"steer":"followUp",n);return}tj(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!ey.length&&G&&rC(t)?tS(t):!ey.length&&G&&n6(t)?tS(t).then(e=>{e||r()},()=>r()):r()},[ep,ey,G,ee,u,h,tj,Q,tS,tC]),tZ=(0,i.useCallback)(e=>{let t=t$.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eI-1);if("right"===e)return Math.min(t,eI+1);let n=to.current[eI];if(!n)return"down"===e?Math.min(t,eI+1):Math.max(0,eI-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eI)continue;let t=to.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-s;if("down"===e?l<=4:l>=-4)continue;let d=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);d<o&&(a=n,o=d)}return a>=0?a:"down"===e?Math.min(t,eI+1):Math.max(0,eI-1)},[t$.length,eI]),tV=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ed||"ctrlEnter"===eu?n&&(e.ctrlKey||e.metaKey):n,i=ed?r:n,s=Date.now()-tr.current<100,a=tn.current||t.isComposing||229===t.keyCode;if(i&&(a||s)){s&&e.preventDefault();return}if(eB&&!a){if("ArrowDown"===e.key){e.preventDefault(),eU(e=>Math.min(Math.max(0,q.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eU(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e_(!1);return}if(("Tab"===e.key||i)&&q[eH]){e.preventDefault(),tH(q[eH]);return}}if(eC&&null!==tN){if("ArrowDown"===e.key){e.preventDefault(),e$(tZ("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e$(tZ("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e$(tZ("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e$(tZ("left"));return}if("Escape"===e.key){e.preventDefault(),eN(!1);return}let t=t$[eI];if("Tab"===e.key&&t){e.preventDefault(),tU(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 n8(t)&&n6(e)}(ep,t,m)?(eN(!1),tC()):tU(t);return}}if(eA&&null!==eM&&!a){if("ArrowDown"===e.key){e.preventDefault(),eW(e=>rg(e,tF.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eW(e=>rg(e,tF.length,-1));return}if("Escape"===e.key){e.preventDefault(),eL(!1);return}if(("Tab"===e.key||i)&&tF[eO]){e.preventDefault(),t_(tF[eO]);return}}if("ArrowUp"===e.key&&!a&&!m&&q.length>0&&0===ep.trim().length){e.preventDefault(),eN(!1),eL(!1),eU(q.length-1),e_(!0);return}if("Escape"===e.key&&!a&&m&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),m&&(u||h)?tK(e.altKey&&h||!u?"followup":"steer"):tC())},[ed,eu,m,u,h,c,eC,tN,t$,eI,tU,tK,tC,tZ,eA,eM,tF,eO,t_,eB,q,eH,tH,ep]),tJ=(0,i.useCallback)(()=>{ti.current=null;let e=e3.current;e&&rb(e)},[]),tG=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!ei&&t.length){e.preventDefault(),tb(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,a={};ti.current=a,setTimeout(()=>{ti.current===a&&(ti.current=null,!n.defaultPrevented&&t.isConnected&&rx(t,i,s,r))},0)}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:a,occurrence:o}of t){if(!s||!a)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 l=s.replace(/([\\[\]])/g,"\\$1"),d=a.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${l}](${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 a=e.currentTarget,o=a.selectionStart,l=a.value.slice(0,o)+s+a.value.slice(a.selectionEnd);e.preventDefault(),tg.current=l,eh(l),e_(!1),tL(l,o+s.length),requestAnimationFrame(()=>{a.focus(),a.setSelectionRange(o+s.length,o+s.length),rv(a)})},[ei,tb,tL]);(0,i.useEffect)(()=>{if(null===tN){eN(!1),e$(0),ts.current=!1;return}eN(!0),e$(0),!ts.current&&J&&(ts.current=!0,Promise.resolve(J()).catch(()=>{ts.current=!1}))},[tN,J]),(0,i.useEffect)(()=>{if(!eC||!en)return;let e=!1;return e8({cwd:en,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(en)}`).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;e8({cwd:en,values:n})}).catch(()=>{e||e8({cwd:en,values:{}})}),()=>{e=!0}},[eC,en]),(0,i.useEffect)(()=>{eI>=t$.length&&e$(Math.max(0,t$.length-1))},[t$.length,eI]),(0,i.useEffect)(()=>{to.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eC&&to.current[eI]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eI,eC]),(0,i.useLayoutEffect)(()=>{if(!eC||null===tN)return void eT(null);let e=ta.current;if(e)return ry(e,e=>{eT(t=>t===e?t:e)})},[eC,tN]),(0,i.useLayoutEffect)(()=>{if(!eA||null===eM)return void ez(null);let e=td.current;if(e)return ry(e,e=>{ez(t=>t===e?t:e)})},[eA,eM]);let tY=b&&b.length>0?b.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})):Object.entries(x??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),tX=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,tQ=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:es("chat.compacted")} ${rw(A.tokensBefore)} -> ${rw(A.estimatedTokensAfter)} tokens (${es("chat.tokensSaved",{saved:rw(tX)})})`:null,t0=z&&"auto"!==z?z:null,t1="auto"!==(n=t0??"auto")&&D?D[n]??n:n,t2=Object.entries(rh).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",t4="chat-only"===t2?es("chat.chatOnly"):t2;(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&eg(!1),e9.current&&!e9.current.contains(e.target)&&ex(!1),e7.current&&!e7.current.contains(e.target)&&ev(!1),!te.current||te.current.contains(e.target)||e3.current?.contains(e.target)||e_(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eg(!1)},[m]);let t8=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t8.current=performance.now()}},[m]);let t6=e=>{var t,n;return t=e.detail,n=performance.now()-t8.current,t>0&&n<600};return(0,i.useEffect)(()=>{ed||ev(!1)},[ed]),(0,r.jsxs)("fieldset",{disabled:eq,"aria-busy":eq,className:ei?void 0:"chat-input-shell",style:{...ei?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:ei?0:"0 16px 8px",paddingRight:ei?0:ed?16:52,opacity:eq?.5:1,transition:"opacity 0.15s"},children:[!ei&&(0,r.jsx)("input",{ref:tt,type:"file",accept:er?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tv}),(0,r.jsxs)("div",{style:{...ei?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(rF,{cwd:y}),(0,r.jsx)(rD,{error:v}),(0,r.jsx)(rB,{warnings:k}),tA&&(s=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(rW,{tone:"warning",title:es("chat.imageNotSupportedTitle"),body:es("chat.imageNotSupportedBody",{model:s?.name||g?.modelId||""}),onClose:()=>eD(!0)})),(U?.steering.length??0)+(U?.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:es("chat.queued",{count:(U?.steering.length??0)+(U?.followUp.length??0)})}),K&&(0,r.jsxs)("button",{onClick:K,title:es("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"})]}),es("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[U?.steering.map((e,t)=>(0,r.jsx)(rO,{kind:"steer",text:e},`steer-${t}`)),U?.followUp.map((e,t)=>(0,r.jsx)(rO,{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"})]}),es("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:R?"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:R?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:M}),R&&(0,r.jsx)(tl.R,{onClick:R,title:es("chat.dismissCompactError")})]}),ey.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ey.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(n5.k,{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:()=>ty(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:[eB&&q.length>0&&(0,r.jsxs)("div",{ref:te,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:es("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:q.map((e,t)=>{let n=t===eH;return(0,r.jsxs)("button",{ref:e=>{tu.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eU(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}`)})})]}),eC&&null!==tN&&(0,r.jsxs)("div",{ref:ta,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===eE?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eE}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?es("chat.loadingCommands"):es("chat.slashCommands",{label:tT})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:V||0!==tI.length?tE.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:es(rI[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===eI,s=rT(t,e6);return(0,r.jsxs)("button",{ref:e=>{to.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tU(t)},onMouseEnter:()=>e$(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:es("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:rE(t,es)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:es("chat.noCommands")})})]}),eA&&null!==eM&&(a=eY&&(!eJ||eJ.cwd!==en),o=1===tF.length?es("chat.match"):es("chat.matches",{count:tF.length}),l=eJ?.truncated&&!tW?eM.query?es("chat.searchingAll"):es("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:td,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===eP?"min(48vh, 400px)":`min(48vh, 400px, ${eP}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?es("chat.loadingFiles"):es("chat.files",{label:o,hint:l})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tF.length?tF.map((e,t)=>{let n=t===eO,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tc.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eW(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)(n3.sj,{size:14}):(0,n3.I3)(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&&!tW?es("chat.searching"):es("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tR?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tR?"column":"row",gap:8,alignItems:tR?"stretch":"center",background:"var(--bg)",border:ei?"none":`1px solid ${ew?"var(--tool-bg)":m&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!ei,padding:ei?0:ed?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:ei?"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:e3,className:"chat-input-textarea","aria-label":ei?es("chat.askInSideChat"):void 0,value:ep,onChange:e=>{tg.current=e.target.value,eh(e.target.value),e_(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tV,onCompositionStart:()=>{tn.current=!0},onCompositionEnd:e=>{tn.current=!1,tr.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tJ,onPaste:tG,placeholder:T?es("chat.compactingPlaceholder"):m&&(u||h)?es("chat.steerPlaceholder"):m?es("chat.agentPlaceholder"):es("chat.messagePlaceholder"),rows:1,style:{flex:tR?"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:ei?96:24,maxHeight:200,overflow:"auto"}}),m&&!ew?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[p&&(0,r.jsx)("button",{type:"button",onClick:tq,disabled:!ep.trim()||ey.length>0,title:es("chat.sideChatHint"),"aria-label":es("chat.sideChat"),className:`bg-transparent ${ep.trim()&&!ey.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",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:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>tK("steer"),disabled:!tM,title:es("chat.steerHint"),"aria-label":es("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tM?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tM?"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"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:es("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>tK("followup"),disabled:!tM,title:`${es("chat.followUpHint")} (${ed?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":es("chat.followUp"),"aria-keyshortcuts":ed?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tM?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tM?"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"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:es("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tC,disabled:!ep.trim()&&!ey.length,title:es("chat.send"),"aria-label":es("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ed?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ep.trim()||ey.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ep.trim()||ey.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ep.trim()||ey.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ep.trim()||ey.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"})]}),!ed&&es("chat.send")]})]})]}),ew&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eS?"var(--text-muted)":"var(--accent)",marginTop:4},children:[es("chat.shell")," \xb7 ",eS?es("chat.outputLocal"):es("chat.outputModel")]}),!ei&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ed?4:8,display:ed?"grid":"flex",gridTemplateColumns:ed?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ed?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>tt.current?.click(),title:es("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:ec,height:ec,padding:0,background:"none",border:"none",borderRadius:9,color:ey.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=ey.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ey.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:ed?18:15,height:ed?18: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"})]})}),(tY.length>0||g||v)&&S&&(0,r.jsx)(rc,{options:tY,value:g,onChange:S,onReselect:S,busy:C,isAutoSelection:f,defaultValue:N,onSetDefault:I,allOptions:j?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:w})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e7,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto"},children:[ed&&(0,r.jsx)("button",{type:"button",title:eb?void 0:es("chat.moreControls"),"aria-label":es("chat.moreControls"),"aria-expanded":eb,"aria-hidden":eb||void 0,tabIndex:eb?-1:void 0,onClick:()=>{ev(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:ec,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eb?"default":"pointer",fontSize:12,fontWeight:500,visibility:eb?"hidden":"visible",pointerEvents:eb?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eb||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:es("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ed?eb?"flex":"none":"flex",alignItems:"center",gap:ed?1:2,...ed?{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:e9,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ex(e=>!e),title:m?es("chat.currentReasoning",{level:t1}):es("chat.changeReasoning",{level:t1}),"aria-label":es("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,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"})]}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ed?{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:rk.filter(e=>!F||"auto"===e||F.includes(e)).map(e=>{let t="auto"===e?O:!O&&t0===e,n=es(rj[e]),i="auto"!==e&&D?D[e]:void 0,s=null!=i&&i!==e?i:e,a=null!=i&&i!==e;return(0,r.jsxs)(rd,{active:t,onSelect:()=>{if(ex(!1),"auto"===e){O||W("auto");return}(!t||O)&&W(e)},gutter:!!_,star:_&&"auto"!==e?{isDefault:B===e,saveLabel:es("chat.saveDefaultThinking"),defaultLabel:es("chat.defaultThinking"),onSave:()=>{ex(!1),_(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,a&&(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&&P&&(0,r.jsxs)("div",{ref:e5,style:{position:ed?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t6(e)||eg(e=>!e)},disabled:m,title:es("chat.changeToolPreset")+`: ${t4}`,"aria-label":es("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:em?"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=em?"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"})}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t4})]}),em&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ed?"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:rp.map(e=>{let t,n=rh[e],i=(L??"configured")===n;return t="configured"===e?es("chat.configuredTools"):"chat-only"===e?es("chat.chatOnly"):"read-only"===e?es("chat.readOnlyTools",{count:4}):"default"===e?es("chat.builtInTools",{count:4}):es("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eg(!1),i||P(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||T)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:T?E:e=>{t6(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:T?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:T?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=T?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=T?"#ef4444":"var(--text-muted)"},title:T?es("chat.stopCompaction"):es("chat.compactContext"),"aria-label":T?es("chat.stopCompaction"):es("chat.compactContext"),children:T?(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"})}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:es("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"})]}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:es("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:c,title:es("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:ec,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"})}),es("chat.stop")]}),void 0!==X&&(0,r.jsx)("button",{onClick:X,title:Y?es("chat.disableSound"):es("chat.enableSound"),"aria-label":Y?es("chat.disableSound"):es("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:ec,height:ec,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"})]})}),ed&&eb&&(0,r.jsx)("button",{type:"button",title:es("chat.collapseControls"),"aria-label":es("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eg(!1),ex(!1),ev(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ed?ec:36,height:ec,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"})]})})]})]})]})]})]})}));var rH=n(19109),rU=n(32316),rq=n(88374),rK=n(68925);let rZ="pi-web:minimap-preview-locked";function rV(){try{return window.localStorage}catch{return null}}function rJ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rV();if(!e)return!1;try{return"true"===e.getItem(rZ)}catch{return!1}}var rG=n(88576),rY=n.n(rG);function rX(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:rY().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 rQ=[...rK.iA??[],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]:[]}}],r0=[[rq.A,{throwOnError:!1,strict:!1}]];function r1(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 r2=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,a=(0,i.useMemo)(()=>(0,rK.Ep)(t),[t]);return t?(0,r.jsx)("div",{className:rY().outline,children:(0,r.jsx)(rU.oz,{remarkPlugins:rQ,rehypePlugins:r0,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rX,{level:1,headingIndex:r1(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rX,{level:2,headingIndex:r1(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rX,{level:3,headingIndex:r1(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:rY().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:a})}):null}),r4=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:a,onRevealHistory:o,turnsBefore:l}=e,{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(600),[b,v]=(0,i.useState)(!1),[y,k]=(0,i.useState)(rJ),[j,w]=(0,i.useState)(null),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),N=(0,i.useRef)([]),I=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),$=(0,i.useRef)(null),E=(0,i.useRef)(new Map),T=(0,i.useRef)(null),M=(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,f),[p,f]),{nodes:P,gap:z}=L;I.current=L;let O=(0,i.useCallback)(e=>{M.current={index:e,until:Date.now()+1600},g(e)},[]),W=(0,i.useCallback)((e,t)=>{let n=M.current;if(n&&Date.now()<n.until)return void g(n.index);M.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void g(null);let i=e.scrollTop+.3*e.clientHeight;g(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),W(e,n)},[s,W]),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=a.current,i=e.getBoundingClientRect(),o=[],l=0,d=null,c=n();for(let t of c?[...A.current,c]:A.current){let n=(0,nb.Y0)(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[l];if(l++,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 a=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=(0,nb.dQ)(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);a&&d.assistantPreviews.push({markdown:a,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),W(e,p);let m=R.current,g=m?p[m.nodeIndex]:null;if(m&&g){let t=void 0===m.assistantIndex?null:g.targetTurn.assistantPreviews[m.assistantIndex],n=g.targetTurn.scrollTop;if("assistant"===m.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===m.target){let r=void 0===m.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(m.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;R.current=null,O(g.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,O,a,s,W]);(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 _=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(O(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})},[O,o,s]),H=(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(),a=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;O(e.index),n.scrollTo({top:Math.max(0,a),behavior:"smooth"})},[O,o,s]),U=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=I.current,i=C.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),a=t[0].topRatio*i,o=n>0?Math.round((s-a)/n):0,l=Math.max(0,Math.min(t.length-1,o)),d=t[l];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 a=i.querySelectorAll("h1, h2, h3").item(n);if(!a)return;let l=r.getBoundingClientRect(),d=a.getBoundingClientRect().top-l.top+r.scrollTop-.3*r.clientHeight;O(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[O,o,s]),K=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),Z=(0,i.useCallback)(()=>{y||(K(),v(!0))},[K,y]),V=(0,i.useCallback)(()=>{let e=!y;k(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rV();if(t)try{t.setItem(rZ,String(e))}catch{}}(e),e&&(K(),v(!1),w(null))},[K,y]),J=(0,i.useCallback)(()=>{K(),T.current=setTimeout(()=>{T.current=null,v(!1),w(null)},250)},[K]);(0,i.useEffect)(()=>()=>K(),[K]);let G=(0,i.useCallback)(e=>{if(!c)return;S.current=!0,Z();let t=e.currentTarget.getBoundingClientRect();w(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&&_(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,_,Z,c]),Y=null===j?null:U(j),X=Y?.index??null;if((0,i.useEffect)(()=>{if(!b||null===X)return;let e=$.current,t=E.current.get(X);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[p,b,X]),!c)return null;let Q=Math.max(1,(P.length>0?P[P.length-1].topRatio*f:12)-12);return(0,r.jsxs)("div",{ref:C,onMouseDown:G,onMouseEnter:Z,onMouseLeave:J,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();w((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:[l>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}}),P.map(e=>{let t=b&&Y?.index===e.index,n=m===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,z),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:rY().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(),V()},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"})]})}),b&&p.length>0&&(0,r.jsxs)("div",{ref:$,className:rY().preview,"data-minimap-preview-box":"",onMouseEnter:Z,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[l>0&&(0,r.jsx)("button",{type:"button",className:rY().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:d("chatMinimap.earlierTurns",{count:l})}),p.map(e=>{var t;let n=X===e.index;return(0,r.jsxs)("div",{ref:t=>{t?E.current.set(e.index,t):E.current.delete(e.index)},className:rY().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:rY().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(l+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:rY().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:rY().content,children:[(0,r.jsx)("button",{type:"button",className:rY().user,"data-minimap-preview-user":e.index,onClick:()=>{_(e,"smooth")},children:(0,r.jsx)("span",{className:rY().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:rY().assistant,children:[(0,r.jsx)("button",{type:"button",className:rY().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>H(e,n),"aria-label":d("chatMinimap.locateAssistant"),title:d("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(r2,{markdown:t.markdown,onAnswerClick:()=>H(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]})});var r8=n(42790);function r6(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new r8.v;e.use_classes=!0;let n=t.replace(nl,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function r3(e){let t,n,s,{widgets:a,children:o}=e,{t:l}=(0,eX.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>a.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[m,g]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(a.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(g(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),g(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[a]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===a.length)return null;let f=a.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[f&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=a.indexOf(f),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:f.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(r6,{text:f.lines.join("\n")})})]},f.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:a.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===f?.key,s=m.has(e.key),a=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=l("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}, ${a}`,title:`${e.key} - ${o} - ${i?l("i18n.collapse"):l("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}, ${a}`,title:`${e.key} - ${o}`,children:p},e.key)})}),o]})]})}let r5="command:";function r9(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,a=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(r5))return null;let t=e.slice(r5.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=nd(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else nd(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===a.length&&0===n.length)return null;let o=a.some(e=>"command"===e.kind),l=a.map(e=>"text"===e.kind?nd(e.text):e.label).join(" "),d=a.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":l,title:l,children:(0,r.jsx)("span",{className:"extension-status-text",children:a.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(r6,{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":""}${a.length>0?" has-status":""}${o?" has-commands":""}`,children:n.length>0?(0,r.jsx)(r3,{widgets:n,children:d}):d})}function r7(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function ie(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function it(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function ir(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function ii(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function is(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(!ii(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=ii(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ii(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 ia(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 io 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 il(e){return e instanceof io&&"prompt_rejected"===e.code&&!1===e.accepted}function id(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function ic(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 io(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,ia(r)??void 0);return r.data}let iu={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function ip(e,t,n){let r=await fetch(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({side:!0,...n?{name:n}:{}}),cache:"no-store"}),i=await r.json().catch(()=>null);return r.ok&&i?.sessionId&&i.session?{session:i.session}:{error:i?.code&&i.code in iu?t(iu[i.code]):i?.error??`HTTP ${r.status}`}}async function ih(e){let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE",cache:"no-store"});if(t.ok)return null;let n=await t.json().catch(()=>null);return{error:n?.error??`HTTP ${t.status}`}}function im(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let ig=new WeakMap;function ix(e){let t,n=ig.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return ig.set(e,t),t}function ib(e){let t=im().get(e);return t?Date.now()-t.savedAt>6e5?(im().delete(e),null):(im().delete(e),im().set(e,t),t):null}function iv(e){if(!e.sessionId||!e.revision)return!1;let t=im();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(ix(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=im();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+=ix(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-=ix(r))}}(),im().has(n.sessionId))}function iy(e){im().delete(e)}var ik=n(14755);let ij="pi-tool-preset";function iw(){try{return window.localStorage}catch{return null}}function iS(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 iC(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,iS(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),iS(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}var iN=n(64738);function iI(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 i$(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(iI).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let iE=(e,t)=>`live:${e??""}:${t}`;class iT 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 iM{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.endedSessionId=null,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 iT("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.endedSessionId===e||!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof iT?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new iT("closed");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 iT("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new iT("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new iT("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 iT("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),a=setTimeout(()=>{this.fail(d,new iT("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(a),n())},fail(e){i||(i=!0,clearTimeout(a),r(e))}},l=Date.now(),d={sessionId:e,source:t,attempt:o,watchdog:null,openedAt:l,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=t=>{let n;if(this.current===d){d.lastSeenAt=Date.now();try{n=JSON.parse(t.data)}catch{return}if("session_ended"===n.type&&n.sessionId===e){this.endedSessionId=e,this.close(),this.options.onEvent(n);return}if("heartbeat"===n.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===n.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??l)>e&&this.fail(d,new iT("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===n.type){let e="string"==typeof n.errorMessage?n.errorMessage:void 0;this.fail(d,new iT("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(d,new iT("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 iR(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}var iA=n(48495);function iL(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function iP(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 iz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let iO=/^(?:custom-ui|extension-widget):/;var iW=n(89594),iF=n(40505);function iD(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let iB={isStreaming:!1,streamingMessage:null};function i_(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 iH(){let e=iB,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=is(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 i_(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return i_(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return i_(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return i_(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return i_(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return i_(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return i_(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 i_(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 i_(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return iB;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 iU(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function iq(e,t){return e.reduce((e,n)=>"user"===n.role&&i$(n)===t?e+1:e,0)}function iK(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function iZ(e){return e&&"auto"!==e?e:null}let iV=new Map,iJ=[2e3,5e3,1e4],iG=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:200,t=new Set;return n=>!t.has(n)&&(t.add(n),t.size>e&&t.delete(t.values().next().value),!0)}();function iY(e){return new Promise(t=>setTimeout(t,e))}function iX(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iQ(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:iX(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iX(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=iX(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function i0(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 i1(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 i2=e=>e.isStreaming,i4=e=>!!e.streamingMessage?.content.length,i8=e=>e.streamingMessage;var i6=n(70843),i3=n(36690);let i5=null,i9=null;function i7(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>i9);if((0,i.useEffect)(()=>{if(i9)return;let e=!1;return(i5??=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=>(i9=e,e)).catch(()=>(i5=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let a=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:a,"aria-label":a,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 se(e){let{messageCount:t,toolCallCount:n,durationMs:s,cacheMisses:a,defaultExpanded:o=!1,reveal:l=!1,children:d,t:c}=e,[u,p]=(0,i.useState)(o);(0,i.useLayoutEffect)(()=>{l&&p(!0)},[l]);let h=[`${t} ${c(1===t?"chat.message":"chat.messages")}`];n>0&&h.push(`${n} ${c(1===n?"chat.toolCall":"chat.toolCalls")}`),void 0!==s&&h.push(c("chat.turnDuration",{time:(0,nL.J)(s)}));let m=a&&!(u||l)?(0,i3.YL)(c,a):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u||l,"aria-label":[c("chat.processDetails"),...h,...m?[m]:[]].join(" \xb7 "),onClick:()=>p(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:c(u?"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:u?"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:[h.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:i3.lV},children:` \xb7 ${m}`})]})]}),(u||l)&&(0,r.jsx)("div",{style:{marginTop:8},children:d})]})}function st(e){var t;let s,{session:o,searchTarget:d,onSearchTargetHandled:c,initialScrollPosition:u,onScrollPositionChange:p,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:g,newSessionContextBar:f,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:v,onSessionEnded:y,onToolEnd:k,onAttentionNeeded:j,onSessionCreated:w,onSessionForked:S,panel:C=!1,onSideSession:N,modelsRefreshKey:I,chatInputRef:$,onBranchDataChange:E,onSystemPromptChange:T,onSystemToolsChange:M,onSystemInfoLoaderChange:R,onDebugSnapshotReaderChange:A,onSessionStatsChange:L,onSessionStatsPanelOpen:P,onOpenSettings:z,onContextUsageChange:O,onOpenFile:W,onFilesUploaded:F,onOpenSubagent:D,onEnterSubagent:B,quoteSelectionEnabled:_=!1,initialPrompt:H,onInitialPromptConsumed:U,soundEnabled:q=!0,onSoundToggle:K,playDoneSound:Z=()=>{},unlockAudio:V,holdAudio:J}=e,{t:G}=(0,eX.s)(),Y=(0,eQ.a)(),X=!l(o?.relation),Q=(0,i.useRef)(Z);Q.current=Z;let ee=(0,i.useRef)(q);ee.current=q;let et=(0,i.useRef)(!1),en=(0,i.useCallback)(e=>{X&&ee.current&&!e.aborted&&!e.subagentsActive&&Q.current(),v?.(e)},[X,v]),er=(0,i.useRef)(d?null:u??null),[ei,es]=(0,i.useState)(()=>{let e=er.current;return e&&!e.atBottom?e:null}),[ea,eo]=(0,i.useState)(!1),{loading:el,error:ed,messages:ec,activeToolResults:eu,toolClocks:ep,entryIds:eh,messageKeys:em,historyCursor:eg,hasEarlierMessages:ef,earlierTurnCount:ex,streamingStore:eb,agentRunning:ev,bashRunning:ey,pendingBash:ek,modelNames:ej,modelList:ew,modelError:eS,missingCwd:eC,modelScopeWarnings:eN,isModelScopeActive:eI,allModelList:e$,modelThinkingLevels:eT,modelThinkingLevelMaps:eM,toolPreset:eR,thinkingLevel:eA,retryInfo:eL,contextUsage:eP,forkingEntryId:ez,isCompacting:eO,compactError:eW,compactResult:eF,displayModel:eD,modelSwitching:eB,sessionStats:e_,slashCommands:eH,slashCommandsLoading:eU,queuedMessages:eq,notices:eK,extensionDialog:eZ,waitingExtensionDialogCount:eV,extensionCustomUi:eJ,waitingExtensionCustomUiCount:eG,extensionStatuses:eY,extensionWidgets:e0,respondToExtensionUi:e2,sendExtensionCustomInput:e4,setNoticePaused:e8,addNotice:e6,isAutoModelSelection:e3,isAutoThinkingSelection:e9,defaultModel:e7,savedDefaultThinkingLevel:te,agentPhase:tt,isNew:tn,editEntryId:tr,showScrollToBottom:ti,sessionIdRef:ts,scrollContainerRef:ta,lastUserMsgRef:to,promptAnchorActive:tl,handleSend:td,handleAbort:tu,startSideChat:tp,handleFork:th,handleEditContent:tm,cancelEdit:tg,handleModelChange:tf,handleCompact:tx,handleSteer:tb,handleFollowUp:tv,handlePromptWithStreamingBehavior:ty,handleAbortCompaction:tk,dismissCompactError:tj,handleRecallQueue:tw,handleBuiltinSlashCommand:tS,handleToolPresetChange:tC,handleThinkingLevelChange:tN,handleSetDefaultModel:tI,handleSetDefaultThinkingLevel:t$,loadSlashCommands:tE,loadAllModels:tT,scrollUserMsgToTop:tM,loadContext:tR,activeLeafId:tA,scrollToBottom:tL,scrollToMessage:tP}=function(e){var t;let r,s,{session:a,newSessionCwd:o,newSessionDraftKey:l,onAgentEnd:d,onSessionEnded:c,onToolEnd:u,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:m,onSideSession:g,modelsRefreshKey:f,onBranchDataChange:x,onSystemPromptChange:b,onSystemToolsChange:v,onSystemInfoLoaderChange:y,onSessionStatsPanelOpen:k,onOpenSettings:j,onDebugSnapshotReaderChange:w}=e,S=null===a&&null!==o,C=S?e.initialNewSessionChoices??null:null,[N,I]=(0,i.useState)(null),[$,E]=(0,i.useState)(!S),[T,M]=(0,i.useState)(null),[R,A]=(0,i.useState)(null),[L,P]=(0,i.useState)([]),[z,O]=(0,i.useState)(new Map),[W,F]=(0,i.useState)(iF.HP),[D,B]=(0,i.useState)([]),[_,H]=(0,i.useState)(()=>new Map),[U,q]=(0,i.useState)(null),[K,Z]=(0,i.useState)(!1),[V,J]=(0,i.useState)(0),[G]=(0,i.useState)(iH),Y=G.dispatch,[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(!1),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)({}),[ea,eo]=(0,i.useState)([]),[el,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,eg]=(0,i.useState)([]),[ef,ex]=(0,i.useState)(!1),[eb,ev]=(0,i.useState)(null),ey=(0,i.useRef)(null),[ek,ej]=(0,i.useState)({}),[ew,eS]=(0,i.useState)({}),[eC,eN]=(0,i.useState)(()=>C?.model??null),[eI,e$]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(ik.Q8),[eR,eA]=(0,i.useState)(()=>C?.thinkingLevel??null),[eL,eP]=(0,i.useState)(null),[ez,eO]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(null),[eD,eB]=(0,i.useState)(null),[e_,eH]=(0,i.useState)(null),[eU,eq]=(0,i.useState)(null),[eK,eZ]=(0,i.useState)(null),eV=(0,i.useRef)(0),eJ=(0,i.useRef)(0),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(null),[e3,e5]=(0,i.useState)(!1),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!0),[tn,tr]=(0,i.useState)(null),[ti,ts]=(0,i.useState)(null),[ta,to]=(0,i.useState)(null),[tl,td]=(0,i.useState)(!1),[tu,tp]=(0,i.useState)(!1),[th,tm]=(0,i.useState)([]),[tg,tf]=(0,i.useState)(!1),[tx,tb]=(0,i.useReducer)(iQ,{visible:[],pending:[]}),[tv,ty]=(0,i.useState)(null),[tk,tj]=(0,i.useState)([]),[tw,tS]=(0,i.useState)([]),[tC,tN]=(0,i.useState)([]),[tI,t$]=(0,i.useState)([]),[tE,tT]=(0,i.useState)({steering:[],followUp:[]}),tM=(0,i.useRef)(null),tR=(0,i.useRef)(null),tA=(0,i.useRef)(0),tL=(0,i.useRef)(!1),tP=(0,i.useRef)(!1),[tz,tO]=(0,i.useState)(0),tW=(0,i.useRef)(null),tF=(0,i.useRef)(()=>{}),tD=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tB=(0,i.useRef)({count:0,lastAt:null}),t_=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tH=(0,i.useRef)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(!1),tK=(0,i.useRef)(0),tZ=(0,i.useRef)(a?.id??null),tV=(0,i.useRef)(null),tJ=(0,i.useRef)(a?.id??null),tG=(0,i.useRef)(!1),tY=(0,i.useRef)(!1),tX=(0,i.useRef)(!1),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(-1),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(0),t4=(0,i.useRef)(0),t8=(0,i.useRef)(null),t6=(0,i.useRef)(!!e.deferInitialScroll),t3=(0,i.useRef)(null),t5=(0,i.useRef)(!1),t9=(0,i.useRef)(!0),t7=(0,i.useRef)(0),ne=(0,i.useRef)(null),nt=(0,i.useRef)(void 0),nn=(0,i.useRef)(void 0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(null),ns=(0,i.useRef)([]),na=(0,i.useRef)(null),no=(0,i.useRef)(0),nl=(0,i.useRef)(!1),nc=(0,i.useRef)(C?.model??null),nu=(0,i.useRef)(C?.thinkingLevel??null),np=(0,i.useRef)({}),nh=(0,i.useRef)(null),nm=(0,i.useRef)(0),ng=(0,i.useRef)(null),nf=(0,i.useRef)(null),nx=(0,i.useRef)(null),nv=(0,i.useRef)(0),ny=(0,i.useRef)(null),nk=(0,i.useCallback)(()=>{nf.current=nm.current,nx.current?.runId===nm.current&&(nx.current=null)},[]),nw=(0,i.useRef)(!1),nS=(0,i.useRef)(new Map),nC=(0,i.useRef)(!0),nN=(0,i.useRef)(new Map),nI=(0,i.useRef)(null),nE=(0,i.useRef)([]),nT=(0,i.useRef)([]),nM=(0,i.useRef)(null),nR=(0,i.useRef)(null),nA=(0,i.useRef)(!1),nL=(0,i.useRef)(0);tJ.current=a?.id??null,nI.current=N,nE.current=L,nT.current=D,nM.current=R,nR.current=U,nA.current=K,nL.current=V,tq.current=e9,tK.current=tk.length+tw.length;let nP=(0,i.useCallback)(e=>nC.current&&tV.current!==e&&tZ.current===e&&(tY.current||tL.current||tJ.current===e&&!tP.current),[]);tM.current||(tM.current=new iM({createSource:e=>(0,eE.Lf)("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent((0,eE.nU)())}`),e),onEvent:e=>t8.current?.(e),shouldMaintain:nP,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nz=e.setToolPreset??eM,nO=a?.id;(0,i.useLayoutEffect)(()=>{(nO||S&&!tZ.current)&&nz(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iw();if(!e)return ik.Q8;try{let t=e.getItem(ij);return(0,ik.sn)(t)?t:ik.Q8}catch{return ik.Q8}}())},[nO,S,nz]);let nW=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{S&&nW?.({model:eC,thinkingLevel:eR})},[S,eC,eR,nW]);let nF=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=nr.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),t7.current=t.scrollTop)},[]),nD=e0??e2??N?.context.model??e8??null,nB=S?eC??eI:nD??(N?.context.messages.length===0?eI:null),nH=iZ(N?.context.thinkingLevel&&"off"!==N.context.thinkingLevel?N.context.thinkingLevel:null),nU=S?eR??eL:eW??eD??nH??(N?.context.messages.length===0?eL:null),nV=a?.id??l??void 0,nJ=(0,i.useCallback)(e=>{e4(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eB(iZ(e.thinkingLevel))},[]),nX=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nS.current.get(t);if(!e)break;t=e}return t},[]),nQ=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=nX(r);if(!nC.current&&!nl.current&&r===l)return;let a=e.chatInputRef?.current;a?a.restoreSubmission(t,i,s):s&&nG(s,t,i)},[l,e.chatInputRef,nX]),[n0,n1]=(0,i.useState)(()=>{let e=a?.id;return e&&!nq(e)&&iV.delete(e),e&&iV.get(e)||null}),n2=(0,i.useCallback)(e=>{a?.id&&(e?iV.set(a.id,e):iV.delete(a.id),n1(e))},[a?.id]),n4=(0,i.useCallback)((t,n)=>{a?.id&&(e.chatInputRef?.current?.replaceMessage(t),n2(n))},[e.chatInputRef,a?.id,n2]),n6=(0,i.useCallback)(()=>n2(null),[n2]),n3=(0,i.useMemo)(()=>{let e=N?.totalActiveMs,t=eK&&eK.sessionId===N?.sessionId?eK.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(tv)return{...tv,totalActiveMs:n,...eU?{contextUsage:eU}:{}};let r=N?.stats,i=function(e,t,n){let r=iC(n);if(!e)return r;let i=iC(t),s=(e,t)=>Math.max(0,e-t),a={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 a.total=a.input+a.output+a.cacheRead+a.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:a,cost:e.cost+s(r.cost,i.cost)}}(r,N?.context.messages??[],L);return 0!==i.tokens.total||0!==L.length||r?{sessionFile:N?.filePath||void 0,sessionId:tZ.current??a?.id??"",sessionName:a?.name,...i,totalActiveMs:n,...eU?{contextUsage:eU}:{}}:null},[L,tv,eU,eK,N?.sessionId,N?.context.messages,N?.filePath,N?.totalActiveMs,N?.stats,a?.id,a?.name]),n5=(0,i.useCallback)((e,t,n,r)=>{nC.current&&tZ.current===t&&nm.current===n&&!(r<=eJ.current)&&(eJ.current=r,e?.contextUsage!==void 0&&eq(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eZ({sessionId:t,value:e.totalActiveMs}))},[]),n9=(0,i.useCallback)(async e=>{let t=nm.current,n=++eV.current;try{let r=await fetch(id(e));if(!r.ok)return;let i=await r.json();n5(i.state,e,t,n)}catch{}},[n5]),n7=(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:nN.current.get(i);if(s)return await s;let a=(async()=>{let i=!1,s=++nv.current,a=!tY.current;try{t&&E(!0);let o=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&o.set("force","1");let l=await fetch(`/api/sessions/${encodeURIComponent(e)}?${o}`);if(404===l.status)return t&&(I(null),A(null),P([]),B([]),q(null),Z(!1),J(0),M(null)),iy(e),null;if(!l.ok)throw Error(`HTTP ${l.status}`);let d=await l.json();if(tZ.current!==e)return null;(ny.current?.seq??0)<s&&(ny.current={sid:e,seq:s,messages:d.context.messages,entryIds:d.context.entryIds??[]});let c=ib(e),u=!!(d.snapshotRevision&&c?.revision===d.snapshotRevision&&c.entryIds.length>=(d.context.entryIds??[]).length),p=u?nE.current:d.context.messages;if(I(u?{...d,context:{...d.context,messages:nE.current,entryIds:nT.current,oldestEntryId:nR.current,hasMore:nA.current,turnsBefore:nL.current}}:d),A(d.leafId),u)iv({sessionId:e,revision:d.snapshotRevision,messages:nE.current,entryIds:nT.current,leafId:d.leafId,oldestEntryId:nR.current,hasMore:nA.current,turnsBefore:nL.current,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:nT.current});else{let e={messages:nE.current,entryIds:nT.current},t={messages:p,entryIds:d.context.entryIds??[]};H(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],a=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===a&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var o,l;let d=t.entryIds[a+n];if(void 0===d||(o=e.messages[i+n],l=t.messages[a+n],o.role!==l.role||("user"===o.role?i$(o)!==i$(l):"custom"===o.role?o.customType!==l.customType:o.timestamp!==l.timestamp)))break;r.set(d,iE(s,n))}return r})({...e,aliases:n},t)),P(t.messages),B(t.entryIds),q(d.context.oldestEntryId),Z(d.context.hasMore),J(d.context.turnsBefore??0)}if(tG.current=void 0!==d.toolNames,nz(void 0!==d.toolNames?(0,ik.YO)(d.toolNames):ik.Q8),e1(e=>nw.current?e:null),eF(null),M(null),"summary"===d.treeFormat&&d.snapshotRevision&&iv({sessionId:e,revision:d.snapshotRevision,messages:p,entryIds:d.context.entryIds??[],leafId:d.leafId,oldestEntryId:d.context.oldestEntryId,hasMore:d.context.hasMore,turnsBefore:d.context.turnsBefore??0,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:d.context.entryIds??[]}),d.wrapperRebuilt&&(tM.current?.close("rebuilt"),tM.current?.maintain(e)),!n&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eB(iZ(d.context.thinkingLevel)),i=!0,a&&s>t2.current&&er(e=>e?.result?null:e),t&&E(!1),!n)return null;try{let t=nm.current,n=++eV.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tZ.current!==e)return null;let s=i.state;return nJ(s),s?(n5(s,e,t,n),void 0!==s.systemPrompt&&eY(s.systemPrompt??null),void 0!==s.extensionStatuses&&tN(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&t$(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tT(iK(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tt(s.autoCompactionEnabled??!0)):i.running||tT({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return M(String(e)),"error"}finally{t&&!i&&E(!1)}})();return nN.current.set(i,a),a.finally(()=>{nN.current.get(i)===a&&nN.current.delete(i)}),await a},[n5,nz,nJ]),re=(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}`,a=await fetch(s,{signal:r?.signal});if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json();if(tZ.current!==e||r?.signal?.aborted||!nC.current)return;return q(o.context.oldestEntryId),Z(o.context.hasMore),J(o.context.turnsBefore??0),I(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?(P(e=>[...o.context.messages,...e]),B(e=>[...o.context.entryIds,...e])):(P(o.context.messages),B(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),rt=(0,i.useCallback)(async e=>{try{let t=await ic(e,{type:"get_tools"});if(!t||!nC.current||tZ.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nz(tG.current?r(t):ik.Q8),v?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[v,nz]),rn=(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)",r=tZ.current;if(S&&o&&r&&!nl.current&&(nl.current=!0,l)){if(l!==r){nS.current.set(l,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(l,r):nY(l,r)}h?.({id:r,path:"",cwd:o,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},l)}},[S,o,l,h,e.chatInputRef]),rr=(0,i.useCallback)(async()=>{if(tZ.current||!S||!o)return tZ.current;if(ni.current)return ni.current;let e=(async()=>{let e=nc.current,t=nu.current;e&&e6(e);let n=(0,ik.xG)(eT);tG.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:o,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok){let e=await r.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${r.status}`,n=ia(e);throw n?new io(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return tZ.current=s,i.model&&nc.current===e&&(e6(i.model),e||e$(i.model)),i.thinkingLevel&&nu.current===t&&(eB(iZ(i.thinkingLevel)),t||eP(iZ(i.thinkingLevel))),s})();ni.current=e;try{return await e}finally{ni.current=null}},[S,o,eT]),ri=(0,i.useCallback)(async()=>{let e=tZ.current??await rr();if(!e)return;let[t]=await Promise.all([ic(e,{type:"get_state"}),rt(e)]);nC.current&&tZ.current===e&&(nJ(t),eY(t.systemPrompt??""))},[rr,rt,nJ]),rs=(0,i.useCallback)(e=>{ns.current=e,tm(e)},[]),ra=(0,i.useCallback)(()=>{no.current+=1,na.current=null,rs([])},[rs]),ro=(0,i.useCallback)(()=>{let e=++no.current,t=(async()=>{let t=tZ.current??await rr();if(!t)return no.current===e&&rs([]),[];tf(!0);try{let n=await ic(t,{type:"get_commands"}),r=n?.commands??[];return no.current===e&&rs(r),r}catch(t){return console.error("Failed to load slash commands:",t),no.current===e&&rs([]),null}finally{no.current!==e&&na.current||tf(!1)}})();na.current=t;let n=()=>{na.current===t&&(na.current=null)};return t.then(n,n),t},[rr,rs]),rl=(0,i.useCallback)(async()=>await ro()??[],[ro]),rd=(0,i.useCallback)(async()=>{let e=na.current,t=ns.current;return!e&&t.length>0?t:await (e??ro()).catch(()=>null)??(t.length>0?t:null)},[ro]),rc=(0,i.useCallback)(()=>{tA.current+=1,tL.current=!1,tU.current=null,tR.current&&(clearTimeout(tR.current),tR.current=null)},[]),ru=(0,i.useCallback)(e=>{tM.current?.close(e)},[]),rp=(0,i.useCallback)(e=>tM.current.ensureConnected(e),[]),rh=(0,i.useCallback)(e=>{tM.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=a?.id;if(e)return nC.current=!0,tP.current=!1,rh(e),()=>{tZ.current===e&&tM.current?.close("deselected")}},[rh,a?.id]);let rm=(0,i.useCallback)(e=>{let t=tW.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,a=Date.now();tD.current.inFlightSince=a,tD.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 s=n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tW.current===i&&(tW.current=null);try{let e=tD.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-a),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tW.current=i,i.promise},[]),rg=!X&&!ee&&!e9&&0===tk.length&&0===tw.length;(0,i.useEffect)(()=>{let e=a?.id;if(!e||!rg)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tP.current&&tZ.current===e&&tJ.current===e&&!tY.current&&!t1.current,i=async()=>{if(n=null,tH.current=null,!r())return;let t=await rm(e);if(r()){if(!("unanswered"===t||t&&!iR(t)))return void s();tP.current=!0,tB.current={count:tB.current.count+1,lastAt:Date.now()},ru("released")}},s=()=>{null===n&&(n=setTimeout(()=>void i(),iA.P),tH.current=Date.now()+iA.P)},o=()=>{"hidden"===document.visibilityState?s():n&&(clearTimeout(n),n=null,tH.current=null)};return"hidden"===document.visibilityState&&s(),document.addEventListener("visibilitychange",o),()=>{t=!0,n&&clearTimeout(n),tH.current=null,document.removeEventListener("visibilitychange",o)}},[ru,rg,tz,rm,a?.id]);let rf=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(tj(t=>ir(t,e.id)),n)try{await ic(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),rx=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(n)try{await ic(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rb=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tb({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"}})},[]),rv=(0,i.useRef)(e.t);rv.current=e.t;let ry=(0,i.useCallback)((e,t)=>rv.current(e,t),[]),rk=(0,i.useCallback)(()=>{rb({type:"warning",message:ry("chat.sendUnconfirmed")})},[rb,ry]),rj=(0,i.useCallback)(e=>{nC.current&&P(t=>iU(t,e.bubble));let t=ib(e.sid);t?.messages.includes(e.bubble)&&iv({...t,messages:iU(t.messages,e.bubble)})},[]),rw=(0,i.useCallback)((e,t,n)=>{let r=nx.current;if(!r||r.runId!==t||r.sid!==e)return;nx.current=null;let i=ny.current,s=i?.sid===e&&i.seq>n?i:null,a=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&a>=0&&iq(s.messages.slice(a),r.key)>r.sameTextAfterSend||(nQ(r.message,r.images,r.draftKey),s&&rj(r),rb(s&&!r.command&&a===s.entryIds.length?{type:"error",message:ry("chat.sendNotReceived")}:{type:"warning",message:ry("chat.sendUnconfirmed")}))},[rb,rj,nQ,ry]),rS=(0,i.useCallback)(()=>{let e=nx.current;if(nx.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});nG(e.parkedDraftKey,e.message,t)}else nQ(e.message,e.images,e.draftKey);rj(e)}},[rj,nQ]),rC=(0,i.useRef)(rS);rC.current=rS;let rN=(0,i.useCallback)(t=>{switch(ie(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tj(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!iG(t.id))break;rb({id:t.id,message:nd(t.message),type:t.notifyType??"info"});break;case"setStatus":tN(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":t$(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=nd(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(nd(t.text));break;case"custom":tS(e=>{let n;return t.closed?ir(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)})}},[rb,p,e.chatInputRef]),rI=(0,i.useCallback)(()=>{let e=tY.current;return tY.current=!1,Q(!1),to(null),eH(null),O(new Map),F(iF.HP),Y({type:"end"}),e},[Y]),r$=(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 t0.current!==e&&(t0.current=e,d?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[d]),rE=(0,i.useCallback)(e=>{if(tJ.current===e)return void rc();rc(),tL.current=!0;let t=tA.current,n=async()=>{if(t===tA.current&&tZ.current===e&&tL.current)try{let r=await fetch(id(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tA.current||tZ.current!==e||!tL.current)return;let s=i.state;if(nJ(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tL.current=!1,tR.current=null,tU.current=null,tX.current=!!s?.isStreaming,tQ.current=!!s?.isPromptRunning,tY.current=!0,Q(!0),to(e=>r7(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){e7(!0),tR.current=setTimeout(()=>void n(),600),tU.current=Date.now()+600;return}tL.current=!1,tR.current=null,tU.current=null,ru("grace_end")}catch{if(t!==tA.current||tZ.current!==e||!tL.current)return;tR.current=setTimeout(()=>void n(),600),tU.current=Date.now()+600}};tR.current=setTimeout(()=>void n(),3e4),tU.current=Date.now()+3e4},[rc,ru,nJ]),rT=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tZ.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nm.current;if(nm.current!==t)return;let n=nv.current;try{e&&await n7(e)}finally{if(nm.current!==t)return;e&&rw(e,t,n);let r=tQ.current,i=tX.current;tQ.current=!1,tX.current=!1,ng.current=null;let s=rI();r?r$(t):i&&s&&d?.({aborted:!1}),e&&rE(e)}},[n7,r$,d,rE,rI,rw]),rM=(0,i.useCallback)(async(e,t)=>{await iY(800);let n=Date.now();for(;tY.current&&Date.now()-n<2e4;){if(void 0!==t&&nm.current!==t)return;try{let n=await fetch(id(e));if(n.ok){let r=await n.json(),i=r.state;if(nJ(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rT(e,t)}}catch{}await iY(600)}},[rT,nJ]),rR=(0,i.useCallback)(async e=>{let t=t4.current+1;for(t4.current=t;t1.current&&t4.current===t&&tZ.current===e;){await iY(1e3);try{let n=await fetch(id(e));if(!n.ok)continue;let r=await n.json();if(nJ(r.state),r.state?.isBashRunning)continue;if(await n7(e),t4.current!==t||tZ.current!==e)return;t1.current=!1,et(!1),er(null);return}catch{}}},[n7,nJ]),rA=(0,i.useCallback)(async e=>{if(!tY.current||tZ.current!==e)return;let t=nm.current,n=++eV.current;try{let r=await fetch(id(e));if(!r.ok)return;let i=await r.json();if(tZ.current!==e||nm.current!==t)return;let s=i.state;if(n5(s,e,t,n),nJ(s),e7(s?.isCompacting??!1),tt(s?.autoCompactionEnabled??!0),tT(iK(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tX.current=!!s.isStreaming,tQ.current=!!s.isPromptRunning;return}if(!tY.current)return;s&&(void 0!==s.extensionStatuses&&tN(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&t$(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nC.current&&tZ.current===e&&t.state?.systemPrompt!==void 0&&eY(t.state.systemPrompt??null)}).catch(()=>{})),await rT(e,t)}catch{}},[n5,rT,nJ]);(0,i.useEffect)(()=>{if(!X)return;let e=()=>{let e=tZ.current;e&&rA(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)}},[X,rA]),(0,i.useEffect)(()=>{tY.current=X},[X]);let rL=(0,i.useCallback)(e=>nC.current&&tZ.current===e&&!tY.current,[]),rP=(0,i.useRef)(null),rz=(0,i.useRef)(null),rO=(0,i.useCallback)(async e=>{var t;let n,r=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:"1"}),i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let{context:s,leafId:a}=await i.json();if(!rL(e))return;let o=nT.current.at(-1),l=nE.current.at(-1),d=void 0!==o&&nE.current.length===nT.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(o))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!d)return void await n7(e);if(0===d.entryIds.length)return;if(t1.current&&d.messages.some(e=>"bashExecution"===e.role)){rz.current=e;return}nT.current=[...nT.current,...d.entryIds],nE.current=[...nE.current,...d.messages],B(e=>e.at(-1)===o?[...e,...d.entryIds]:e),P(e=>e.at(-1)===l?[...e,...d.messages]:e),a&&(rP.current={base:nM.current,lastEntryId:d.entryIds.at(-1),leafId:a});let c=ib(e);c&&iv({...c,loadedEntryIds:[...c.loadedEntryIds,...d.entryIds]})},[rL,n7]),rW=(0,i.useRef)(rO);rW.current=rO;let rF=(0,i.useRef)(null);rF.current??=(t={pendingReads:e=>[nN.current.get(e),nN.current.get(`force:${e}`)],read:e=>rW.current(e),wanted:rL,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,s=null,e=>{s=e,r||(r=!0,(async()=>{try{for(;null!==s;){let e=s;if(s=null,t.wanted(e))try{await Promise.allSettled(t.pendingReads(e)),t.wanted(e)&&await t.read(e)}catch(e){t.onError?.(e)}}}finally{r=!1}})())}),t8.current=(0,i.useCallback)(t=>{if(!tV.current)switch(t.type){case"session_ended":{let e=tZ.current;if(!e||t.sessionId!==e)return;tV.current=e,rc(),tM.current?.close(),iy(e),c?.(e);return}case"connected":if(Y({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tj(t=>it(t,e)),tS(t=>it(t,e))}F(iF.E),!0===t.isStreaming&&(rc(),tX.current=!0,tY.current=!0,Q(!0),to({kind:"waiting_model"})),tZ.current&&n9(tZ.current);break;case"agent_start":nk(),rc(),tX.current=!0,tY.current=!0,Q(!0),to({kind:"waiting_model"}),eH(null),Y({type:"start"});break;case"agent_end":if(!tY.current)break;if(to(null),eH(null),Y({type:"end"}),tZ.current){let e=tZ.current,t=nm.current,n=++eV.current;n7(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nC.current&&tZ.current===e&&nm.current===t&&(nJ(r.state),n5(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eY(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tN(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&t$(r.state.extensionWidgets??[]),tT(iK(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=tX.current;if(tX.current=!1,!e||tQ.current)break;let n=tZ.current,r=rI();e7(!1),n&&(n7(n),rE(n)),r&&d?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{nk();let e=nm.current,n=tQ.current;tQ.current=!1,ng.current=null;let r=r$(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=tZ.current;i&&n7(i),!tX.current&&(rI(),i&&rE(i))}break;case"prompt_error":rb({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rb({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!iO.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!tY.current||iP(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(Y({type:"snapshot",message:e}),e.content.length>0&&to(null)):e&&to(null)}else{let e=t.assistantMessageEvent;e&&(Y({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&to(null))}!t5.current&&t9.current&&null===ne.current&&(ne.current=requestAnimationFrame(()=>{ne.current=null,t9.current&&nF("auto")}));break;case"message_end":{if(!tY.current){let e=t.message;e?.role==="custom"&&!(0,nb.zZ)(e)&&tZ.current&&rF.current?.(tZ.current);break}if(iP(t))break;let e=t.message;if(e&&"user"===e.role){let t=is(e),n=i$(t),r=ng.current;ng.current=null,r&&nk(),P(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&i$(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(P(t=>[...t,(0,iW.mO)(is(e),n)]),"toolResult"===e.role){let t=e.toolCallId;F(e=>(0,iF.vx)(e,t))}if("assistant"===e.role){let e=tZ.current;e&&n9(e)}}Y({type:"end"}),to({kind:"waiting_model"});break}case"tool_execution_start":{if(iL(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();F(e=>(0,iF.Ho)(e,t,r)),to(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[];return r.some(t=>t.id===e)||r.push({id:e,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(iL(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content;Array.isArray(i)&&("bash"===n||"powershell"===n||n===nj.sp||(0,n$.G)(r?.details))&&O(t=>{let s=new Map(t);return s.set(e,{role:"toolResult",toolCallId:e,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===nj.sp?(0,nj.ky)(t.partialResult):function(e){if(!iz(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>iz(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)}`}(t.partialResult);to(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),a={id:e,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),a]}});break}case"tool_execution_end":{if(iL(t))break;let e=t.toolCallId;u?.(t.toolName);let n=performance.now();F(e=>(0,iF.Ho)(e,t,n)),O(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n}),to(t=>{if(t?.kind!=="running_tools")return t;let n=t.tools.filter(t=>t.id!==e);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":nk(),tT({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":eH({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":eH(null);break;case"auto_compaction_start":case"compaction_start":e7(!0),tr(null),ts(null);break;case"auto_compaction_end":case"compaction_end":e7(!1),eH(null),t.errorMessage?(tr(t.errorMessage),ts(null)):!t.aborted&&(ts(i0(t.result,t.reason??"auto")),tZ.current&&n7(tZ.current));break;case"bash_output":{let e=t.output;if(!t1.current||"string"!=typeof e)break;er(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(nd(t.text));break;case"extension_ui_request":rN(t);break;case"extension_ui_closed":tj(e=>ir(e,t.id))}},[rb,n5,e.chatInputRef,rc,Y,rN,n7,nk,r$,d,c,u,n9,rE,nF,rI,nJ]);let rD=(0,i.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(t1.current||tY.current&&!r){t1.current&&r&&rb({type:"warning",message:ry("chat.bashAlreadyRunning")}),nQ(e,t,nV);return}if(n0&&(n2(null),!await nn.current?.(n0))){n2(n0),nQ(e,t,nV);return}let i=!t?.length&&n.startsWith("/");if(r){let r=n.startsWith("!!"),i=(r?n.slice(2):n.slice(1)).trim();return i?void await nt.current?.(i,r):void nQ(e,t,nV)}let s=nm.current+1;rc(),tQ.current=!0;let l=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),d={role:"user",content:l?.length?[...e.trim()?[{type:"text",text:e}]:[],...l]:e,timestamp:Date.now()},c=i$(d),u=nT.current,p=u.at(-1)??null,h=iq(nE.current.slice(u.length),c);P(e=>[...e,d]),ng.current=c,nm.current=s,tY.current=!0,Q(!0),to(i?{kind:"running_command"}:{kind:"waiting_model"}),Y({type:"start"}),t5.current=!0,td(!0);let m=()=>{P(e=>{let t=e.lastIndexOf(d);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),ng.current=null},g=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),f=null,x=!1;try{if(S&&o){let t=tZ.current??await ni.current,n=t??await rr();if(!n)throw Error("Unable to create a session for the prompt");f=n,eC&&(e6(eC),t&&await ic(n,{type:"set_model",provider:eC.provider,modelId:eC.modelId})),nC.current&&await rp(n).catch(e=>{if(nC.current)throw e}),x=!0;let r=await ic(n,{type:"prompt",message:e,...g?.length?{images:g}:{}});r?.queued&&m(),rn(1,e)}else if(a){f=a.id,await rp(a.id),x=!0;let t=await ic(a.id,{type:"prompt",message:e,...g?.length?{images:g}:{}});t?.queued&&m()}else throw Error("No active session for the prompt");eh(null),i&&f&&rM(f,s)}catch(n){if(console.error("Failed to send message:",n),!(!x||il(n))&&f){nf.current!==s&&(nx.current={runId:s,sid:f,message:e,images:t,draftKey:nV,parkedDraftKey:S&&o?n_(o):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:d,key:c,command:i},nC.current||rS()),rM(f,s);return}if(tQ.current=!1,P(e=>iU(e,d)),n instanceof io&&n.missingCwd?eh(n.missingCwd):rb({type:"error",message:n instanceof Error?n.message:String(n)}),nQ(e,t,nV),ng.current=null,f)return void rA(f);tY.current=!1,ru("send_failed"),Q(!1),to(null),Y({type:"end"})}},[S,o,eC,a,rr,rp,rn,rM,rb,rS,rc,ru,nV,Y,rA,nQ,n0,n2,ry]);nt.current=(0,i.useCallback)(async(e,t)=>{if(t1.current)return;let n=`${t?"!!":"!"}${e}`;t1.current=!0;let r=Date.now();er({command:e,excludeFromContext:t,startedAt:r}),et(!0);let i=null;try{let s=tZ.current??a?.id??await rr();if(!s)throw Error("Unable to create a session for the shell command");await rp(s).catch(()=>{});let o=await ic(s,{type:"bash",command:e,excludeFromContext:t});tY.current&&o?(i={command:e,excludeFromContext:t,startedAt:r,result:o},t2.current=nv.current):(await n7(s),rn(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof io&&"extension_reported"===e.code||rb({type:"error",message:e instanceof Error?e.message:String(e)}),nQ(n,void 0,nV)}finally{t1.current=!1,er(i),et(!1);let e=rz.current;rz.current=null,e&&rF.current?.(e)}},[rb,nV,rp,rr,n7,rn,nQ,a]);let rB=en?.result;(0,i.useEffect)(()=>{if(X||!rB)return;let e=tZ.current;e&&n7(e,!1,!1,{force:!0})},[X,rB,n7]);let r_=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nQ(n,t.images,nV):n&&e.chatInputRef?.current?.prependText(n)},[nV,e.chatInputRef,nQ]),rH=(0,i.useCallback)(async()=>{let e=tZ.current;if(e){if(t1.current&&!tY.current){try{await ic(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await ic(e,{type:"abort"});t&&tT({steering:[],followUp:[]}),r_(t)}catch(e){console.error("Failed to abort:",e)}}},[r_]),rU=(0,i.useCallback)(async(e,t)=>{if(t1.current)return;let n=tZ.current;if(n){eQ(e);try{let{cancelled:r,newSessionId:i}=await ic(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&nK(i,t),m?.(i))}catch(e){console.error("Fork failed:",e),rb({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eQ(null)}}},[rb,m]),rq=(0,i.useCallback)(async e=>{if(t1.current)return!1;let t=tZ.current;if(!t)return!1;try{let n=await ic(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tZ.current!==t)return!1;return await n7(t),tZ.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[n7]);nn.current=rq;let rK=(0,i.useCallback)(async e=>{if(t1.current||tY.current||e9)return;A(e);let t=tZ.current;t&&(await re(t,e),e&&ic(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[e9,re]),rZ=(0,i.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};nc.current=n,eN(n),e6(n),null===nu.current&&eP(iZ(np.current[`${e}/${t}`])??nh.current);let r=tZ.current??await ni.current;if(!r)return;try{await ic(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tZ.current;if(!n||nw.current)return;nw.current=!0,e1({provider:e,modelId:t}),e5(!0);let r=tY.current||t1.current,i=async()=>{let e=await fetch(id(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nC.current&&tZ.current===n&&nJ(t.state)};try{let s=await ic(n,{type:"set_model",provider:e,modelId:t});e4({provider:s.provider,modelId:s.id}),nw.current=!1,r?(e1(null),await i()):await n7(n)}catch(e){console.error("Failed to set model:",e),nw.current=!1,e1(e0),rb({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await n7(n,!1,!0)}finally{nw.current=!1,e5(!1)}},[rb,e0,S,n7,eN,nJ]),rV=(0,i.useCallback)(async e=>{let t=tZ.current;if(!t||e9)return!0;e7(!0),tr(null),ts(null);try{let n=await ic(t,{type:"compact",...e?{customInstructions:e}:{}});return ts(i0(n,"manual")),await n7(t)&&rn(),!0}catch(e){return tr(e instanceof Error?e.message:String(e)),ts(null),!1}finally{e7(!1)}},[e9,n7,rn]),rJ=(0,i.useCallback)(()=>tr(null),[]),rG=(0,i.useCallback)(async e=>{let t,n=o??a?.cwd??"",r=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=null;try{let n=await fetch(r,e?{signal:e}:void 0);if(!n.ok){let e="";try{let t=await n.json();t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error&&(e=t.error),i=ia(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${n.status})`)}t=await n.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(eu(i),ed(i?null:t instanceof Error?t.message:String(t))),t}eu(null),es(t.models),ed(t.modelError??null),eg(t.modelScopeWarnings??[]),ex(!!t.isScoped),ev(null),ey.current=null,ej(t.thinkingLevels??{}),eS(t.thinkingLevelMaps??{});let s=t.modelList??[];eo(s);let l=t.defaultModel?s.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(e$(l?{provider:l.provider,modelId:l.id}:null),np.current=t.thinkingLevelPins??{},nh.current=iZ(t.defaultThinkingLevel),eO(iZ(t.savedDefaultThinkingLevel)),S&&!tZ.current){let e=nc.current,n=e&&(0===s.length||!!t.isScoped||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(nc.current=null,eN(null));let r=n?e:l&&{provider:l.provider,modelId:l.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nu.current&&eP(iZ(i)??nh.current)}},[S,o,a?.cwd]),rY=(0,i.useCallback)(()=>{if(ey.current)return;let e={};ey.current=e;let t=o??a?.cwd??"";fetch(`/api/models?scope=all${t?`&cwd=${encodeURIComponent(t)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();ey.current===e&&(es(e=>({...n.models,...e})),ej(e=>({...n.thinkingLevels,...e})),eS(e=>({...n.thinkingLevelMaps,...e})),ev(n.modelList??[]))}).catch(t=>{ey.current===e&&(ey.current=null,rb({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rb,o,a?.cwd]);(0,i.useEffect)(()=>{!ef||!nB||eb||ea.some(e=>e.provider===nB.provider&&e.id===nB.modelId)||rY()},[eb,nB,ef,rY,ea]);let rX=(0,i.useCallback)(async e=>{let t=o??a?.cwd,n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},...e})});if(n.ok)return;let r="";try{let e=await n.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(r=e.error)}catch{}throw Error(r||`HTTP ${n.status}`)},[o,a?.cwd]),rQ=(0,i.useCallback)(()=>{rG().catch(()=>{})},[rG]),r0=(0,i.useCallback)(async(e,t)=>{try{await rX({provider:e,modelId:t})}catch(e){rb({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rb({type:"success",message:`Default model: ${e}/${t}`}),e$({provider:e,modelId:t}),(nB?.provider!==e||nB?.modelId!==t)&&await rZ(e,t),rQ()},[rb,nB,rZ,rQ,rX]),r1=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return ry(iu[r]);let i=tZ.current;if(!i)return ry("sideChat.error.noSession");let s=await ip(i,ry,n);return"error"in s?s.error:(g?.(s.session,t),null)},[g,e.session?.relation?.kind,ry]),r2=(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(),a=tZ.current??await rr(),o=e=>(e.handled&&(e.error?rb({type:"error",message:e.error}):e.action||rb({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!a||e9)return o({handled:!0,error:"No active session to compact"});return rV(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),o({handled:!0,action:"compact"});case"auto-compact":{if(!a)return o({handled:!0,error:"No active session"});let e=await ic(a,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await ic(a,{type:"set_auto_compaction",enabled:t}),tt(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!a)return o({handled:!0,error:"No active session to reload"});return await ic(a,{type:"reload"}),await Promise.all([n7(a,!1,!0),rt(a),rl(),rG()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return o({handled:!0,error:"No active session to name"});if(!s)return o({handled:!0,error:"Usage: /name <name>"});return await ic(a,{type:"set_session_name",name:s}),await n7(a)&&rn(),o({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return o({handled:!0,error:"No active session"});if(!k)return o({handled:!0,message:(0,iN.C$)(n3,ry)});let e=await ic(a,{type:"get_session_stats"});return e&&ty(e),k(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!j)return{handled:!1};let e=await rd();if(!e||!(e.some(n8)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return j("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!a)return o({handled:!0,error:"No active session"});let e=await ic(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await (0,tc.D)(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!a)return o({handled:!0,error:"No active session to clone"});if(tY.current||t1.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=rP.current,t=await ic(a,{type:"clone",leafId:e?.base===R&&e.lastEntryId===nT.current.at(-1)?e.leafId:R});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=o({handled:!0,message:"Cloned current session branch"});return m?.(t.newSessionId),n}case"side":{let e=await r1(s||null);return o(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return o({handled:!0,error:e instanceof Error?e.message:String(e)})}},[R,rb,rr,rV,e9,rG,n7,rl,rt,rn,j,m,k,e.chatInputRef,n3,rd,r1,ry]),r4=(0,i.useCallback)(async(e,t,n)=>{let r=tZ.current;if(n0)return void nQ(e,n,nV);if(!r){nQ(e,n,nV),rb({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 ic(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nQ(e,n,nV),t instanceof io&&t.missingCwd)return void eh(t.missingCwd);il(t)?rb({type:"error",message:t.message}):rk()}},[rb,rk,nV,n0,nQ]),r8=(0,i.useCallback)(async(e,t)=>{await r4(e,"steer",t)},[r4]),r6=(0,i.useCallback)(async(e,t,n)=>{await r4(e,t,n)},[r4]),r3=(0,i.useCallback)(async(e,t)=>{await r4(e,"followUp",t)},[r4]),r5=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{await ic(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r9=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{let t=await ic(e,{type:"clear_queue"});tT({steering:[],followUp:[]}),r_(t)}catch(e){console.error("Failed to recall queued messages:",e),rb({type:"error",message:"Failed to recall queued messages"})}},[rb,r_]),ii=(0,i.useCallback)(async e=>{if("auto"===e){nu.current=null,eA(null),eF(null);return}S?(nu.current=e,eA(e)):eF(e);let t=tZ.current??await ni.current;if(t)try{await ic(t,{type:"set_thinking_level",level:e}),nC.current&&tZ.current===t&&(eB(e),eF(null))}catch(e){console.error("Failed to set thinking level:",e),eF(null)}},[S]),ih=(0,i.useCallback)(async e=>{try{await rX({thinkingLevel:e})}catch(e){rb({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rb({type:"success",message:`Default reasoning level: ${e}`}),eO(e),nU!==e&&await ii(e),rQ()},[rb,nU,ii,rQ,rX]),im=(0,i.useCallback)(async e=>{let t=(0,ik.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iw();if(t)try{t.setItem(ij,e)}catch{}}(e),nz(e);let n=tZ.current??await ni.current;if(!n){tG.current=void 0!==t;return}try{let e=await ic(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tG.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rc(),ru("set_tools"),tj([]),tS([]),tZ.current=r,e?.recreated&&tJ.current===r&&rh(r)),ra(),tN([]),t$([]);let[i]=await Promise.all([ic(r,{type:"get_state"}),rt(r)]);nC.current&&tZ.current===r&&(eY(i.systemPrompt??""),nJ(i))}catch(e){console.error("Failed to set tools:",e)}},[rc,ra,ru,rt,rh,nz,nJ]),ig=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=nr.current;n&&(null!==ne.current&&(cancelAnimationFrame(ne.current),ne.current=null),t6.current=!0,t5.current=!1,t9.current=!1,td(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),t7.current=n.scrollTop)},[]),ix=(0,i.useCallback)(()=>{let e=nr.current,t=t3.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!==ne.current&&(cancelAnimationFrame(ne.current),ne.current=null),t9.current=!0,t7.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),iS=(0,i.useCallback)(()=>{let e=nr.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tY.current,s=t9.current,a=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!iD(n,r,i)||!(n<t)&&(!!(!e&&n>t&&iD(n,r,i,s))||e)}(s,t7.current,t,n,r,i?96:8);t9.current=a,t7.current=t;let o=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!iD(e,t,n,r)}(t,n,r);tp(e=>e===o?e:o),!s&&a&&i?nF("auto"):a||null===ne.current||(cancelAnimationFrame(ne.current),ne.current=null)}},[nF]),iI=(0,i.useCallback)((e,t)=>{t?.running&&(rt(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tX.current=!!t.state.isStreaming,tQ.current=!!t.state.isPromptRunning,tY.current=!0,Q(!0),to(e=>r7(e,t.state?.isStreaming===!0)),Y({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rM(e)),t.state?.isBashRunning&&(t1.current=!0,et(!0),rR(e))),t?.state&&(void 0!==t.state.isCompacting&&e7(t.state.isCompacting),void 0!==t.state.systemPrompt&&eY(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tN(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&t$(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tT(iK(t.state.queuedMessages)))},[Y,rt,rR,rM]);tF.current=(e,t)=>{!tP.current||tV.current===e||(tP.current=!1,t_.current={count:t_.current.count+1,lastAt:Date.now(),lastReason:t},tO(e=>e+1),nC.current&&tZ.current===e&&tJ.current===e&&(rh(e),n7(e,!1,!0).then(t=>{nC.current&&tZ.current===e&&iI(e,t)})))},(0,i.useEffect)(()=>{let e=a?.id;if(!e)return;let t=!1,n=tD.current,r=async()=>{let n=await rm(e);!t&&"hidden"===document.visibilityState&&iR(n)&&tF.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let s=()=>{"visible"===document.visibilityState&&(tF.current(e,"visible"),r())};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",s)}},[rm,a?.id]),(0,i.useEffect)(()=>{if(nC.current=!0,eJ.current=eV.current,a){tZ.current=a.id;let e=ib(a.id);e&&(I({sessionId:a.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}),A(e.leafId),P(e.messages),B(e.entryIds),q(e.oldestEntryId),Z(e.hasMore),J(e.turnsBefore),M(null),E(!1)),n7(a.id,!e,!0,{force:!0}).then(e=>{iI(a.id,e)})}return()=>{nC.current=!1;let e=S?l:null;e&&queueMicrotask(()=>{nC.current||nl.current||nZ(e)});let t=tZ.current,n=nI.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=ib(t),r=nT.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)?iv({sessionId:t,revision:n.snapshotRevision,messages:nE.current,entryIds:nT.current,leafId:nM.current,oldestEntryId:nR.current,hasMore:nA.current,turnsBefore:nL.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nT.current}):iy(t)}rC.current(),null!==ne.current&&(cancelAnimationFrame(ne.current),ne.current=null),t4.current+=1,rc(),ru()}},[]),(0,i.useEffect)(()=>{b?.(eG)},[eG,b]),(0,i.useEffect)(()=>(y?.(ri),()=>y?.(null)),[ri,y]);let iT=(0,i.useCallback)(()=>{let e=null;try{e=tM.current?.snapshot?.()??null}catch{e=null}let t=tZ.current,n=tD.current,r=t_.current;return{pageId:(0,eE.kz)(),sessionId:t,selectedSessionId:tJ.current,mounted:nC.current,wantsStream:null!==t&&nP(t),connection:e,released:{active:tP.current,...tB.current},reattached:{...r},hiddenReleaseDueAt:tH.current,hiddenGraceMs:iA.P,graceDueAt:tU.current,run:{agentRunning:tY.current,bashRunning:t1.current,compacting:tq.current,dialogs:tK.current},lease:{renewIntervalMs:3e4,renewStartedAt:n.renewStartedAt,inFlightSince:n.inFlightSince,requests:n.requests,unanswered:n.unanswered,errors:n.errors,last:n.last&&{...n.last,reply:n.last.reply&&{...n.last.reply}}}}},[nP]);(0,i.useEffect)(()=>(w?.(iT),()=>w?.(null)),[iT,w]);let iB=X||ee||e9;(0,i.useEffect)(()=>{x&&x(N?.tree??[],R,rK,iB)},[N?.tree,R,rK,iB,x]),(0,i.useEffect)(()=>{let e=nr.current;if(e)return t7.current=e.scrollTop,e.addEventListener("scroll",iS,{passive:!0}),()=>{e.removeEventListener("scroll",iS)}},[L.length,$,iS]),(0,i.useEffect)(()=>{X||td(!1)},[X]),(0,i.useLayoutEffect)(()=>{L.length>0&&(t5.current?(t5.current=!1,t6.current=!0,ix()):t6.current?!tY.current&&t9.current&&nF("auto"):(t6.current=!0,nF("instant")))},[L.length,X,nF,ix]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rG(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=iJ.length||(await iY(iJ[t]),e.signal.aborted))return}})(),()=>e.abort()},[rG,f]),(0,i.useEffect)(()=>{if(!ti)return;let e=setTimeout(()=>ts(null),6e3);return()=>clearTimeout(e)},[ti]);let[i_,iX]=(0,i.useState)(null),i1=(0,i.useRef)(5e3),i2=(0,i.useRef)(null),i4=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tx.visible.length){i4.current=null;return}let e=tx.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tb({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tx.visible[0];if(!t||(i4.current!==t.id&&(i4.current=t.id,i1.current=5e3),tx.visible.some(e=>e.id===i_)))return;i2.current=Date.now();let n=setTimeout(()=>{tb({type:"mark_oldest_exiting"})},i1.current);return()=>{clearTimeout(n),null!==i2.current&&(i1.current=Math.max(0,i1.current-(Date.now()-i2.current)),i2.current=null)}},[tx.visible,i_]),(0,i.useEffect)(()=>{ty(null)},[L.length,eU?.tokens,eU?.percent,eU?.contextWindow]);let i8=nU??"auto",i6=tk[0]??null,i3=Math.max(0,tk.length-1),i5=tw[0]??null,i9=Math.max(0,tw.length-1),i7=(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?iE(r,s-e.length):n.get(t)??t)}return i})(D,L.length,_),[D,L.length,_]);return{data:N,loading:$,error:T,activeLeafId:R,messages:L,activeToolResults:z,toolClocks:W,entryIds:D,messageKeys:i7,historyCursor:U,hasEarlierMessages:K,earlierTurnCount:V,streamingStore:G,agentRunning:X,modelNames:ei,modelList:ea,modelError:el,missingCwd:ep??ec,modelScopeWarnings:em,isModelScopeActive:ef,allModelList:eb,modelThinkingLevels:ek,modelThinkingLevelMaps:ew,newSessionModel:eC,toolPreset:eT,thinkingLevel:i8,retryInfo:e_,contextUsage:eU,systemPrompt:eG,forkingEntryId:eX,isCompacting:e9,compactError:tn,compactResult:ti,currentModel:nD,displayModel:nB,modelSwitching:e3,sessionStats:n3,autoCompactionEnabled:te,slashCommands:th,slashCommandsLoading:tg,queuedMessages:tE,notices:tx.visible,extensionDialog:i6,waitingExtensionDialogCount:i3,extensionCustomUi:i5,waitingExtensionCustomUiCount:i9,extensionStatuses:tC,extensionWidgets:tI,respondToExtensionUi:rf,sendExtensionCustomInput:rx,isAutoModelSelection:S&&null===eC,isAutoThinkingSelection:S&&null===eR,defaultModel:eI,savedDefaultThinkingLevel:ez,agentPhase:ta,isNew:S,editEntryId:n0,promptAnchorActive:tl,showScrollToBottom:tu,sessionIdRef:tZ,scrollContainerRef:nr,lastUserMsgRef:t3,pendingScrollToUserRef:t5,initialScrollDoneRef:t6,handleSend:rD,handleAbort:rH,startSideChat:r1,handleFork:rU,handleNavigate:rq,handleModelChange:rZ,handleCompact:rV,handleSteer:r8,handleFollowUp:r3,handlePromptWithStreamingBehavior:r6,handleAbortCompaction:r5,dismissCompactError:rJ,handleRecallQueue:r9,handleBuiltinSlashCommand:r2,handleEditContent:n4,cancelEdit:n0?n6:void 0,addNotice:rb,setNoticePaused:iX,handleToolPresetChange:im,handleThinkingLevelChange:ii,handleSetDefaultModel:r0,handleSetDefaultThinkingLevel:ih,loadTools:rt,loadSlashCommands:rl,loadAllModels:rY,setActiveLeafId:A,setData:I,setMessages:P,loadContext:re,scrollToBottom:nF,scrollUserMsgToTop:ix,scrollToMessage:ig,dispatch:Y,setAgentRunning:Q,setForkingEntryId:eQ,bashRunning:ee,pendingBash:en,handleAgentEventRef:t8}}({session:o,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:g,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:en,onSessionEnded:y,onToolEnd:k,onAttentionNeeded:j,onSessionCreated:w,onSessionForked:S,onSideSession:N,modelsRefreshKey:I,chatInputRef:$,onBranchDataChange:E,onSystemPromptChange:T,onSystemToolsChange:M,onSystemInfoLoaderChange:R,onSessionStatsPanelOpen:P,onOpenSettings:z,onDebugSnapshotReaderChange:A,t:G,deferInitialScroll:!!ei}),tz=i1(eb,i2),tO=i1(eb,i4),tW=(0,i.useCallback)(()=>eb.getState().streamingMessage,[eb]),tF=ev||ey,tD=(0,i.useCallback)((e,t)=>{th(e,{value:rL(t),images:rP(t)})},[th]);(0,i.useEffect)(()=>{if(ev&&J)return J()},[ev,J]);let[tB,t_]=(0,i.useState)(null),[tH,tU]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(!1),[tZ,tV]=(0,i.useState)(null),tJ=(0,i.useRef)(null),tG=(0,i.useRef)(null),tY=(0,i.useCallback)(()=>{t_(null),tU(!1),tV(null)},[]);(0,i.useEffect)(()=>{_||tY()},[_,tY]);let tX=(0,i.useCallback)(()=>{if(!_||tH)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t5.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void t_(null);let r=e.toString().trim();if(!r)return void t_(null);let i=t.getBoundingClientRect();t_({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))})},[_,tH]);(0,i.useEffect)(()=>{tH&&tB&&tG.current?.insertIfEmpty(nP(tB.text))},[tH,tB]),(0,i.useLayoutEffect)(()=>{let e=tJ.current;if(!e||!tB)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(tB.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tB.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)}},[tB,tH,tZ]),(0,i.useEffect)(()=>{if(!tB)return;let e=e=>{tH||tJ.current?.contains(e.target)||tY()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tq||tY())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tB,tH,tq,tY]);let tQ=(0,i.useCallback)(()=>{tB&&($?.current?.insertQuote(nP(tB.text)),tY())},[$,tB,tY]),t0=(0,i.useCallback)(async e=>{if(!tq&&e.trim()&&tB){tK(!0),tV(null);try{let t=await tp(e,tB.text);if(!t)return void tY();tG.current?.restoreSubmission(e),tV(t)}catch(t){tG.current?.restoreSubmission(e),tV(t instanceof Error?t.message:String(t))}finally{tK(!1)}}},[tB,tq,tY,tp]),t1=(0,i.useCallback)(async e=>{let t;try{t=await tp(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&($?.current?.restoreSubmission(e),e6({type:"error",message:t}))},[e6,$,tp]),t2=(0,i.useRef)(!1);(0,i.useEffect)(()=>{el||ed||!H||t2.current||(t2.current=!0,U?.(),td(H))},[H,el,ed,td,U]),(0,i.useEffect)(()=>{let e=!!eZ&&!et.current;et.current=!!eZ,X&&e&&Q.current()},[X,eZ]),(0,i.useEffect)(()=>{C||(a=tF?tu:null)},[C,tF,tu]);let[t4,t8]=(0,i.useState)(50),[t6,t3]=(0,i.useState)(null),t5=(0,i.useRef)(null),t9=(0,i.useRef)(null),t7=(0,i.useRef)(!1),ne=(0,i.useRef)(!1),nt=(0,i.useRef)(ei);nt.current=ei;let[nn,nr]=(0,i.useState)(null),ni=ec[eh.indexOf(nn?.entryId??"")],na=ni?.role==="assistant"?nn?.blockIndex===void 0?ni.content.find(e=>"text"===e.type):ni.content[nn.blockIndex]:void 0,no=(0,i.useRef)({entryIds:eh,historyCursor:eg,hasEarlierMessages:ef});no.current={entryIds:eh,historyCursor:eg,hasEarlierMessages:ef};let nl=(0,i.useRef)(null),nc=(0,i.useCallback)(async(e,t,n)=>{nl.current=t;let r=await tR(e,tA,t,n);return r||nl.current!==t||(nl.current=null),r},[tA,tR]);(0,i.useEffect)(()=>{eg!==nl.current&&(nl.current=null)},[eg]),(0,i.useLayoutEffect)(()=>{let e=o?.id,t=ta.current,n=t5.current;if(e&&p&&t&&n)return()=>{if(nt.current)return;if(iD(t.scrollTop,t.clientHeight,t.scrollHeight))return void p(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&&p(e,{atBottom:!1,...i,oldestEntryId:no.current.historyCursor})}},[el,p,ta,o?.id]),(0,i.useEffect)(()=>{d&&es(null)},[d]),(0,i.useEffect)(()=>{let e=o?.id;if(!ei||!e||el||d||ne.current)return;ne.current=!0;let t=new AbortController;return(async()=>{let n=no.current;if(n.entryIds.includes(ei.anchorEntryId)){t8(e=>Math.max(e,2*n.entryIds.length)),eo(!0);return}t7.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nc(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tL("instant"),es(null);return}if(t8(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ei.anchorEntryId))return void eo(!0);if(n.oldestEntryId===ei.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tL("instant"),es(null))}finally{t7.current=!1}})(),()=>{t.abort(),es(null)}},[tA,nc,el,ei,tL,d,o?.id]),(0,i.useLayoutEffect)(()=>{let e=t5.current;if(!ei||!e||d)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ei.anchorEntryId);if(t instanceof HTMLElement){tP(t,ei.anchorOffset),es(null);return}ea&&(tL("instant"),es(null))},[eh,ei,ea,tL,tP,d,t4]),(0,i.useEffect)(()=>{if(!d||el)return;let e=new AbortController;return(async()=>{let t=no.current,n=t.entryIds.includes(d.entryId);if(!n&&!tF&&t.hasEarlierMessages&&t.historyCursor&&!t7.current){t7.current=!0;let r=ta.current;r&&(t9.current=r.scrollHeight-r.scrollTop);let i=await nc(d.sessionId,t.historyCursor,{tail:200,signal:e.signal});t7.current=!1,n=!!i?.entryIds.includes(d.entryId)}e.signal.aborted||(n?(t9.current=null,t8(e=>Math.max(e,(no.current.entryIds.length+200)*2)),nr(d)):c?.(d))})(),()=>e.abort()},[d,el,tF,nc,c,ta]),(0,i.useLayoutEffect)(()=>{if(!nn||nn!==d)return;let e=`[data-entry-id="${CSS.escape(nn.entryId)}"]`,t=ta.current?.querySelector(ni?.role==="user"?e:`${e} [data-search-target]`);t&&(tP(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),nr(null),c?.(nn)},[nn,d,ni,ta,tP,c]),(0,i.useEffect)(()=>{let e=ta.current;if(!t6||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t7.current)return;if(!ef){t9.current=e.scrollHeight-e.scrollTop,t8(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eg||eg===nl.current)return;let n=o?.id??ts.current;n&&(t7.current=!0,t9.current=e.scrollHeight-e.scrollTop,nc(n,eg).finally(()=>{t7.current=!1}))},{root:e,threshold:0});return t.observe(t6),()=>t.disconnect()},[t6,t4,eg,ef,o,nc,ts,ta]),(0,i.useEffect)(()=>{t8(e=>Math.max(e,ec.length))},[ec.length]),(0,i.useEffect)(()=>{if(null==t9.current)return;let e=ta.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t9.current),t9.current=null}},[t4,ta]);let nu=e_?[e_.sessionId,e_.sessionFile??"",e_.sessionName??"",e_.userMessages,e_.assistantMessages,e_.toolCalls,e_.toolResults,e_.totalMessages,e_.tokens.input,e_.tokens.output,e_.tokens.cacheRead,e_.tokens.cacheWrite,e_.tokens.total,e_.cost??0,e_.totalActiveMs??0].join("|"):null,np=(0,i.useRef)(e_);np.current=e_,(0,i.useEffect)(()=>{L?.(np.current)},[nu,L]),(0,i.useEffect)(()=>()=>{L?.(null)},[L]);let nh=eP?`${eP.percent??"null"}|${eP.contextWindow}|${eP.tokens??"null"}`:null,nm=(0,i.useRef)(eP);nm.current=eP,(0,i.useEffect)(()=>{O?.(nm.current)},[nh,O]),(0,i.useEffect)(()=>()=>{O?.(null)},[O]);let ng=(0,i.useCallback)(async e=>{let t=o?.cwd??m;if(!t)return void e6({type:"warning",message:G("chat.dropNeedsCwd")});try{let{status:n,data:r}=await (0,nO.Zn)(t,e,"skip");if(200!==n&&207!==n)throw Error(r.error??`HTTP ${n}`);let i=r.uploaded??[],s=r.skipped??[],a=(0,nO.JI)(e,[...i,...s]);for(let e of(a&&$?.current?.insertText(a),i.length>0&&(e6({type:"success",message:G("chat.dropUploaded",{count:i.length})}),F?.()),s.length>0&&e6({type:"warning",message:G("chat.dropAlreadyExists",{names:s.join(", ")})}),r.errors??[]))e6({type:"error",message:G("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e6({type:"error",message:G("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e6,$,m,F,o?.cwd,G]),nf=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=(0,nO.H7)(e);t.length>0&&$?.current?.addImages(t),r.length>0&&e6({type:"warning",message:G("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&ng(n)},[e6,$,G,ng]),nx=(0,i.useCallback)(e=>{nf(e.map(e=>({kind:"file",file:e})))},[nf]),{isDragOver:nv,handleDragEnter:ny,handleDragOver:nk,handleDragLeave:nw,handleDrop:nS}=(0,i6.J)(nf),nC=ec.filter(e=>(0,nb.Y0)(e)||"assistant"===e.role),nz=(0,i.useMemo)(()=>{let e=new Map(eu);for(let t of ec)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eu,ec]),nF=(0,i.useMemo)(()=>new WeakMap,[]),nD=(0,i.useMemo)(()=>(0,nI.n_)(ec),[ec]),nB=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ec.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}(ec[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ec]),nH=(t=nC.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),nU=(0,i.useCallback)(()=>{t8(e=>Math.max(e,2*ec.length))},[ec.length]),nV=tn&&0===ec.length&&!tz&&!tF;e1(ta,!!o?.id||!nV);let nJ=o?.cwd??m??void 0,nX=function(e,t,n){let[r,s]=(0,i.useState)(()=>new Map);return(0,i.useEffect)(()=>{let r=nE(e,t);if(0===r.length)return;let i=!1;return Promise.allSettled(r.map(async e=>({sessionId:e.sessionId,entry:await function(e,t,n){let r=nM.get(e);if(r)return r;let i=nR.get(e);if(void 0!==i&&Date.now()-i<3e4)return Promise.resolve(null);let s=(async()=>{try{var r;let{messages:i,cwd:s}=await nT(e,5),a=new Map;for(let e of i)"toolResult"===e.role&&a.set(e.toolCallId,e);return{files:(r=t??s??n,nN(i.flatMap(e=>"assistant"===e.role?e.content??[]:[]),a,r))}}catch{return nR.set(e,Date.now()),null}})();return nM.set(e,s),s.catch(()=>nR.set(e,Date.now())),s}(e.sessionId,e.cwd,n)}))).then(e=>{i||s(t=>{let n=null;for(let r of e){if("fulfilled"!==r.status)continue;let{sessionId:e,entry:i}=r.value;!i||t.get(e)||(n??=new Map(t)).set(e,i.files)}return n??t})}),()=>{i=!0}},[e,t,n]),r}(ec,nz,nJ),nQ=(0,i.useRef)(null),n0=(0,i.useRef)(0),n1=(0,i.useRef)(null),n2=(0,i.useRef)(!1),n4=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nQ.current;if(!ev||!tl){n4.current=null,n0.current=0,n2.current=!1,e&&(e.style.height="");return}let t=ta.current,n=t5.current,r=to.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let a;if(i||ta.current!==t||t5.current!==n||to.current!==r||nQ.current!==e)return;let o=t.getBoundingClientRect().top,l=Math.max(0,r.getBoundingClientRect().top-o+t.scrollTop-16),d=e.getBoundingClientRect().top-o+t.scrollTop,c=(s=t.clientHeight,0===(a=Math.max(0,l))?0:Math.max(0,Math.ceil(a+s-Math.max(0,d)))),u=!n2.current;u&&(n2.current=!0),c!==n0.current&&(n0.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tM())};n4.current=s,s();let a="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==n1.current||(n1.current=requestAnimationFrame(()=>{n1.current=null,s()}))});return a?.observe(t),a?.observe(n),a?.observe(r),()=>{i=!0,n4.current===s&&(n4.current=null),a?.disconnect(),null!==n1.current&&(cancelAnimationFrame(n1.current),n1.current=null)}},[ev,to,ec.length,tl,ta,tM]);let n6=(0,i.useCallback)(()=>{n4.current?.()},[]);(0,i.useLayoutEffect)(n6,[tz,tO,n6]);let n3=eD?eT[`${eD.provider}:${eD.modelId}`]??null:null,n5=eD?eM[`${eD.provider}:${eD.modelId}`]??null:null,n9=(0,r.jsx)(r_,{ref:$,onSend:td,onAbort:tu,onSideChat:N&&!l(o?.relation)?t1:void 0,onSteer:ev?tb:void 0,onFollowUp:ev?tv:void 0,onPromptWithStreamingBehavior:ev?ty:void 0,isStreaming:tF,model:eD,isAutoModelSelection:e3,modelNames:ej,modelList:ew,modelError:eS,missingCwd:eC,modelScopeWarnings:eN,allModelList:e$,onLoadAllModels:eI?tT:void 0,onModelChange:tf,modelSwitching:eB,defaultModel:e7,onSetDefaultModel:tI,onCompact:o||tn?tx:void 0,onAbortCompaction:tk,isCompacting:eO,compactError:eW,onDismissCompactError:tj,compactResult:eF,toolPreset:eR,onToolPresetChange:o&&!l(o.relation)||tn?tC:void 0,thinkingLevel:eA,isAutoThinkingSelection:e9,onThinkingLevelChange:o||tn?tN:void 0,availableThinkingLevels:n3,thinkingLevelMap:n5,savedDefaultThinkingLevel:te,onSetDefaultThinkingLevel:o||tn?t$:void 0,retryInfo:eL,queuedMessages:eq,inputHistory:nB,onRecallQueue:tw,slashCommands:eH,slashCommandsLoading:eU,onLoadSlashCommands:tE,onBuiltinCommand:tS,soundEnabled:q,onSoundToggle:K,onAudioUnlock:V,draftKey:o?.id??g??void 0,cwd:o?.cwd??m,onAttachFiles:nx});return el?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:G("chat.loadingSession")}):ed?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ed}):(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:ny,onDragOver:nk,onDragLeave:nw,onDrop:nS,children:[nv&&(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*!Y,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(si,{notices:eK,floating:!0,onPauseChange:e8})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eZ&&(0,r.jsx)(so,{request:eZ,waitingCount:eV,onRespond:e2},eZ.id),eJ&&(0,r.jsx)(sl,{request:eJ,waitingCount:eG,onInput:e4},eJ.id),!nV&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:ta,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ei?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t5,onPointerUp:tX,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=ec.length-1;e>=0;e--)if("user"===ec[e].role){s=e;break}let a=-1;for(let e=ec.length-1;e>=0;e--)if((0,nb.Y0)(ec[e])){a=e;break}let l=new Map,d=0;ec.forEach((e,t)=>{((0,nb.Y0)(e)||"assistant"===e.role)&&l.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ec[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(sn,{},"side-chat-divider");if((0,nb.zZ)(n))return null;let a=!1===t.withNotices?[]:(0,iW.YQ)(ec[e]),d=(0,nb.Y0)(n)||"assistant"===n.role,c=l.get(e),u=t.keyPrefix??"message",p=em[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ec.length;t++){let e=ec[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tz&&e===ec.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let m=(0,r.jsx)(nW.Dx,{message:n,toolResults:nz,toolClocks:ep,modelNames:ej,cwd:nJ,onOpenFile:W,onOpenSubagent:D,onEnterSubagent:B,entryId:eh[e],searchBlock:eh[e]===nn?.entryId?na:void 0,onFork:ey||tn?void 0:tD,forking:ez===eh[e],onEditContent:tF?void 0:tm,onCancelEdit:tg,isEditing:tr===eh[e],showTimestamp:h,prevTimestamp:e>0?ec[e-1].timestamp:void 0,sessionId:o?.id??ts.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tx:void 0,isCompacting:t.recoverTruncation?eO:void 0,compactError:t.recoverTruncation?eW:void 0},`${u}-view-${p}`),g=a.length>0?(0,r.jsx)(i3.yt,{notices:a},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":eh[e],ref:!1===t.attachRef?void 0:t=>{nH.current[c]=t,e===s&&(to.current=t)},children:[m,g]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[m,g]},`${u}-${p}`)},u=[];for(let e=0;e<ec.length;){let t,n=ec[e],i=(0,nb.Y0)(n);if(!i&&0!==e){u.push(c(e)),e+=1;continue}let s=i?e:-1,o=i?e:0,d=e+1;for(;d<ec.length&&!(0,nb.Y0)(ec[d]);)d+=1;let p=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&(0,nb.dQ)(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}(ec,s,d);if(-1===p||(tF||tz)&&d===ec.length&&s===a){for(let e=o;e<d;e++)u.push(c(e));e=d;continue}i&&u.push(c(s));let h=i&&eh[s]?(0,nL.G)(ec,s,d):void 0,m=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=(0,nb.dQ)(t),i=r.length>0||(0,nb.mc)(t)||(0,nb.PC)(t)||(0,nb.oG)(t)?nA(t,r):null,s=t.content.indexOf(r[0]),a={answer:i,process:nA(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,a),a}(nF,ec[p]),g=m.answer,f=[],x=0,b=0,v=!1;for(let e=s+1;e<=p;e++){let n=ec[e];if("custom"===n.role){if((0,nb.zZ)(n))continue;v||=!!(nn&&nn.entryId===eh[e]),x+=1,f.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===p?m.process:n,s=e!==p||!g,a=(0,nb.TC)(i);if(0===a.length){let t=s?(0,iW.YQ)(n):[];t.length>0&&f.push((0,r.jsx)(i3.yt,{notices:t},`process-notices-${em[e]}`));continue}t??=l.get(e),b+=(0,nb._q)(a),x+=1,v||=!!(nn&&eh[e]===nn.entryId&&(!na||a.includes(na))),f.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===x)u.push(...f);else if(f.length>0){let e=(0,nb.sE)(g),n=(0,iW.Uv)(ec.slice(s+1,g?p:p+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nH.current[t]=e},children:(0,r.jsx)(se,{messageCount:x,toolCallCount:b,durationMs:h,cacheMisses:n,defaultExpanded:!e,reveal:v,t:G,children:f},e?"answered":"unanswered")},`process-group-${em[o]}`))}if(g){let e=[];for(let t=s+1;t<=p;t++){let n=ec[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=nN(e,nz,nJ);for(let e of nE(ec.slice(s+1,p+1),nz))for(let n of nX.get(e.sessionId)??[])t.some(e=>e.filePath===n.filePath)||t.push(n);let n=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)}(m,t);u.push(c(p,{messageOverride:g,writtenFiles:n,turnDurationMs:0===f.length?h:void 0,recoverTruncation:d===ec.length&&!tz&&!(0,nb.D6)(g)}))}for(let e=p+1;e<d;e++)u.push(c(e));e=d}let{startIndex:p}=(t=Math.min(Math.max(t4,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||ef;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t3,className:"py-3 text-center text-xs text-text-muted",children:G("chat.loadEarlier")}),u.slice(p)]})})(),tz&&tO&&(0,r.jsx)(sr,{store:eb,onCommit:n6,toolResults:nz,modelNames:ej,cwd:nJ,onOpenFile:W,onOpenSubagent:D,onEnterSubagent:B}),(ev||eO)&&!tO&&(tt||eO)&&(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}(tt,G,eO,(eq?.steering.length??0)+(eq?.followUp.length??0))})}),ey&&!ek&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:G("chat.runningCommand")})}),ek&&(0,r.jsx)(nW.Dx,{message:{role:"bashExecution",command:ek.command,output:"",...ek.result,excludeFromContext:ek.excludeFromContext,timestamp:ek.startedAt},sessionId:o?.id??ts.current??void 0,onOpenSubagent:D,onEnterSubagent:B}),ek?.liveOutput&&!ek.result&&(0,r.jsx)("div",{"aria-live":"off",className:"rounded-md border border-border px-2.5 py-1.5 font-mono text-[12px] leading-[1.45] text-text-muted",style:{marginTop:-2,background:"var(--tool-bg)"},children:(0,r.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:`${1.45*nb.OP}em`},children:(0,r.jsx)("span",{children:(0,nb.Kj)(ek.liveOutput)})})}),(0,r.jsx)("div",{ref:nQ,"aria-hidden":"true"})]})})}),Y||ei?null:(0,r.jsx)(r4,{messages:ec,getStreamingMessage:tW,scrollContainer:ta,messageRefs:nH,onRevealHistory:nU,turnsBefore:ex})]})]}),_&&tB&&(0,e5.createPortal)((0,r.jsx)("div",{ref:tJ,role:tH?"dialog":"toolbar","aria-label":G(tH?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tB.top,left:tB.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tH?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tH?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tH?(0,r.jsxs)("fieldset",{disabled:tq,"aria-busy":tq,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:G("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:G("i18n.close"),"aria-label":G("i18n.close"),disabled:tq,onClick:tY,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)(r_,{ref:tG,compact:!0,onSend:t0,onAbort:tY,isStreaming:!1}),tZ&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tZ})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:G("chat.quoteSelection"),"aria-label":G("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:tQ,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:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}),(0,r.jsx)("path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"})]}),(0,r.jsx)("span",{children:G("chat.quoteSelection")})]}),N&&!l(o?.relation)&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:G("chat.askInSideChat"),"aria-label":G("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tU(!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.jsx)("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:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}),(0,r.jsx)("span",{children:G("chat.askInSideChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nV&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!Y,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${ti&&!ei?" is-visible":""}`,title:G("chat.scrollToLatest"),"aria-label":G("chat.scrollToLatest"),onClick:()=>tL("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"})})})}),nV&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:Y?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)(ns.A,{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.16.1"]}),(0,r.jsx)(i7,{label:e=>G("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.5.2"]})]})]})]}),f]})}),(0,r.jsx)(rH.Z,{snapshot:nD}),n9,(0,r.jsx)(r9,{statuses:eY,widgets:e0,onCommand:td,commandsDisabled:tF})]}),nV&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function sn(){let{t:e}=(0,eX.s)();return(0,r.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,r.jsx)("span",{children:e("sideChat.divider")}),(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let sr=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:a,cwd:o,onOpenFile:l,onOpenSubagent:d,onEnterSubagent:c}=e,u=i1(t,i8);return((0,i.useLayoutEffect)(n,[u,n]),u)?(0,r.jsx)(nW.Dx,{message:u,toolResults:s,isStreaming:!0,modelNames:a,cwd:o,onOpenFile:l,onOpenSubagent:d,onEnterSubagent:c}):null});function si(e){let{notices:t,floating:n=!1,onPauseChange:s}=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,a)=>{var o;let l,d,c,u="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>s?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||s?.(null)},onFocus:()=>s?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||s?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(a!==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:u,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:(o=e.message,l=[],d=(e,t)=>{if(!t)return;let n=l[l.length-1];n?.kind===e?n.text+=t:l.push({kind:e,text:t})},c=!1,o.split("\n").forEach((e,t)=>{let n=nh.test(e);t>0&&d(n&&c?"art":"text","\n"),d(n?"art":"text",e),c=n}),l).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):(0,r.jsx)(i.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(nm)){let i=function(e){let t=0,n=0;for(let r of e)"("===r?t+=1:")"===r&&(n+=1);let r=e.length;for(;r>0;){let i=e[r-1];if(ng.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/.test(i))continue;let s=r.index??0;s>n&&t.push({kind:"text",text:e.slice(n,s)}),t.push({kind:"link",text:i}),n=s+i.length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t})(e.text).map((e,n)=>"link"===e.kind?(0,r.jsx)("a",{href:e.text,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,wordBreak:"break-all"},children:e.text},`${t}-${n}`):e.text)},t))})]},e.id)})})}function ss(e){let{count:t}=e,{t:n}=(0,eX.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 sa(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 so(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:a}=(0,eX.s)(),[o,l]=(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,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>f(e=>!e),[]),[b,v]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),k=function(e){if("select"===e.method&&e.options.length>0)return nd(e.options[0]);if("confirm"===e.method){let t=nd(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-b)/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&&m(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(()=>v(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let w=null!==j&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:a("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:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:nd(t.title)}),k&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:k}),(0,r.jsx)(ss,{count:n}),w,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":nd(t.title),style:{pointerEvents:"auto",width:g?"100%":`min(${h??560}px, 100%)`,maxHeight:g?"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:nd(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:a("chat.extensionRequest")}),(0,r.jsx)(ss,{count:n}),w]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:a(g?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":a(g?"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)(sa,{expanded:g})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:a("chat.extensionCollapse"),"aria-label":a("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)(nF.m,{children:nd(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":nd(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)(nF.m,{children:nd(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:t.placeholder,onChange:e=>l(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=>l(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:a("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:a("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:a("chat.submit")}):null]})]})})}function sl(e){let{request:t,waitingCount:n,onInput:s}=e,{t:a}=(0,eX.s)(),o=(0,i.useRef)(null),l=(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(nl,""),i=nd(e).trimEnd();if(t.test(i))continue;let s=e,a=np(s);("│"===a||"┃"===a)&&" "===np(s=nu(s,0))&&(s=nu(s,0));let o=function(e){let t=nc(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),l=o>=0?nc(s)[o]?.char:void 0;("│"===l||"┃"===l)&&(s=nu(s,o)),n.push(function(e){let t=e;for(;;){let e=nc(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&&""===nd(n[0]).trim();)n.shift();for(;n.length>0&&""===nd(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(nl,""))}(t.lines),p=u.map(nd).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:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:a("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)(ss,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("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":a("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(l.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=nx[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":" ":nf[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.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:a("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(ss,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:a("chat.extensionCollapse"),"aria-label":a("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:a("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)(r6,{text:u.join("\n")})})]})})}let sd=null,sc="";function su(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:a,onPick:o,onUseDefaultDirectory:l,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,eX.s)(),[h,m]=(0,i.useState)(()=>sc),g=(0,i.useRef)(null),f=(0,i.useRef)(s),x=(0,i.useRef)(a);return x.current=a,(0,i.useEffect)(()=>{if(sc)return;let e=!1;return(sd??=fetch("/api/home").then(e=>e.json()).then(e=>sc=e.home??"").catch(()=>(sd=null,""))).then(t=>{!e&&t&&m(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=f.current;if(!e)return;f.current=null,x.current();let t=g.current;e$(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(tY,{handleRef:g,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:o,onUseDefaultDirectory:l,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}var sp=n(30392),sh=n(90137),sm=n(88545),sg=n(96793),sf=n(68929);let sx=["general","models","skills","agents","plugins","mcp","channels","automations"],sb="pi-web:settings-navigation",sv=new Set(["skills","agents","plugins"]);function sy(e){return sv.has(e)}function sk(){try{return window.localStorage}catch{return null}}function sj(e){let t=e.getItem(sb);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 sw(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e||"channels"===e||"automations"===e?e:null}function sS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sk();if(t)try{let n=sj(t);n.section=e,t.setItem(sb,JSON.stringify(n))}catch{}}function sC(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:sk();if(!n)return null;let r=sw(e,t);if(!r)return null;try{let e=sj(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function sN(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:sk();if(!r||!t)return;let i=sw(e,n);if(i)try{let e=sj(r);e.selections={...e.selections,[i]:t},r.setItem(sb,JSON.stringify(e))}catch{}}var sI=n(61958);let s$="llama.cpp";function sE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class sT extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function sM(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 sR={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class sA extends Error{constructor(e,t){super(sR[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function sL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sP(e){return!sL(e)||"string"!=typeof e.id||e.id.trim().length>0}function sz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sO(e){let t=sz(e.inputLimits)?e.inputLimits.images:void 0,n=sz(t)?t.resize:void 0;return sz(n)?n.maxBytes:void 0}function sW(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 sF(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 sD 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 sB=["input","output","cacheRead","cacheWrite"];function s_(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 sH(e){if(!sU(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 sU(e){return sB.some(t=>""!==e[t].trim())}function sq(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function sK(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function sZ(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function sV(e,t,n,r){let i=e.providers??{},s=i[n],a=s?.models;if(!a||r.every((e,t)=>e===t))return null;let o=t.get(n);return o&&t.set(n,r.map(e=>o[e]??null)),{config:{...e,providers:{...i,[n]:{...s,models:r.map(e=>a[e])}}},providerName:n,order:r}}function sJ(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 sG(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function sY(e){return e.name?.trim()||e.id}function sX(e){let t=new Map;for(let[n,r]of Object.entries(e.providers??{}))"string"==typeof r.name&&t.set(n,r.name);return t}function sQ(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:a,children:o,width:l=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${l}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||a()},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:a,title:s,"aria-label":s,children:"\xd7"})]}),o]})})}let s0=(0,i.createContext)(null);function s1(){return(0,i.useContext)(s0)??s2}let s2={detailOpen:!1,openDetail:()=>{},closeDetail:()=>{},reportDetailTitle:()=>{}};function s4(e,t){let{detailOpen:n,reportDetailTitle:r}=s1(),s=(0,i.useRef)(null);return(0,i.useLayoutEffect)(()=>{let t=s.current;if(!e||!n||!t||t.closest("[hidden]"))return;let i=(t.querySelector(".config-sidebar-text")??t).textContent?.trim();i&&r(i)}),e=>{s.current=e,"function"==typeof t?t(e):t&&(t.current=e)}}function s8(e){let{children:t}=e,n=(0,i.useContext)(s0);return(0,r.jsx)("div",{className:"config-split-view","data-pane":n?n.detailOpen?"detail":"list":void 0,children:t})}function s6(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function s3(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function s5(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 s9(e){let{enabled:t,total:n,checked:i,label:s,disabled:a=!1,loading:o=!1,describedBy:l,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)(aw,{checked:i??(n>0&&t===n),disabled:a,loading:o,label:s,describedBy:l,onChange:d})]})}function s7(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 ae(e){let{active:t=!1,className:n,children:i,onClick:s,ref:a,...o}=e,{openDetail:l}=s1(),d=s4(t,a);return(0,r.jsx)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||l()},"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function at(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function an(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function ar(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function ai(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function as(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function aa(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function ao(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function al(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 ad(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function ac(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:a,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:a,children:o})]})}function au(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function ap(e){let{value:t,options:n,label:s,disabledReason:a,size:o="default",onChange:l,children:d}=e,c=(0,i.useId)(),u=a&&n.some(e=>e.disabled)?a: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||l(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function ah(e){let{value:t,options:n,label:s,path:a,disabledReason:o,onChange:l,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(ap,{value:t,options:n,label:s,disabledReason:o,size:"small",onChange:l,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof a?a.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):a})}),d]})}function am(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)(aa,{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 ag(e){let{title:t,catalogs:n,target:s,inputLabel:a,inputId:o,placeholder:l,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:m,examples:g,error:f,multiline:x=!1,children:b}=e,v=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():v.current?.focus()},[x]);let k=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(an,{className:"is-fill",children:[(0,r.jsx)(am,{title:t,catalogs:n,target:s}),(0,r.jsx)(al,{label:a,children:x?(0,r.jsx)("textarea",{id:o,ref:y,value:d,"aria-label":a,className:"config-add-source-input is-multiline",placeholder:l,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:k,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:v,value:d,"aria-label":a,className:"config-add-source-input",placeholder:l,onChange:e=>p(e.target.value),onPaste:k,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&"Enter"===e.key&&c&&h()}})}),b,g.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:m}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:g.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))})]}),f&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:f})]})}function af(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 ax(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:a}=e;return(0,r.jsx)(af,{id:t,action:a&&i?(0,r.jsx)(aj,{size:"small",onClick:a,disabled:s,children:i}):void 0,children:n})}function ab(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function av(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function ay(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 ak(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 aj(e){let{variant:t="secondary",size:n="default",className:i,children:s,...a}=e;return(0,r.jsx)("button",{type:"button",...a,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function aw(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:a,describedBy:o,onChange:l}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":a,"aria-describedby":o,title:a,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>l(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function aS(e){let{active:t=!1,children:n,className:i,onClick:s,ref:a,...o}=e,{openDetail:l}=s1(),d=s4(t,a);return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||l()},"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 aC(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 aN(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 aI(e,t){let n=aN(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 a$(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function aE(e,t){return e?.providers.find(e=>e.id===t)}function aT(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:a=!1,describedBy:o}=e,{t:l}=(0,eX.s)(),d=void 0!==i&&void 0===sM(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:l("models.contextWindow"),"aria-label":l("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":o,disabled:a,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let aM={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function aR(e){let{controller:t}=e,{t:n}=(0,eX.s)(),{view:i,pending:s}=t;if(!i)return null;let a=!i.allEnabled,o=i.stalePatterns.length;return a||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)(aj,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&a&&(0,r.jsx)(aj,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function aA(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,eX.s)(),{view:a,loading:o,pending:l,failure:d}=n,c=aE(a,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=aL(n,t)?i:void 0;if(o&&!a)return null;if(!c)return(0,r.jsx)(aw,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=aI(a,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(aw,{checked:h.checked,loading:l===`provider:${c.id}`,disabled:null!==l||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function aL(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=aE(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=aI(n,i);return s?aM[s]:null}function aP(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,eX.s)(),a=aL(n,t);return a?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(a)}):null}function az(e){var t;let n,{providerId:s,controller:a,contextSettings:o,emptyCatalogHint:l}=e,{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(""),{view:p,loading:h,pending:m,failure:g}=a,f=aE(p,s)??(l&&!g?{id:s,models:[],enabledCount:0}:void 0),x=function(e,t){let[n,r]=(0,i.useState)(!1),[s,a]=(0,i.useState)(null);return(0,i.useEffect)(()=>a(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),a(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?a("models.catalogOffline"):r.completed?a(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):a("models.catalogUnreachable"),r.changed&&t()}catch{a("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,a.refresh),b=(0,i.useId)();if((0,i.useEffect)(()=>u(""),[s]),h&&!p)return(0,r.jsx)("div",{className:"enabled-models-empty",children:d("agents.modelsLoading")});if(!f)return g?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:g.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:d("models.enabledUnavailable")});let v=(t=f.models,(n=c.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),y=aN(p,v),k=v.length!==f.models.length,j=null!==m,w=`provider:${f.id}`,S=p?.editable===!0,C=`${b}-scope`,N=`${b}-last`,I=`${b}-context`,$=S&&!y.canDisable&&y.disableRefs.length>0,E=$||S&&v.some(e=>a$(p,e)),T=(e,t)=>{k?a.setModels(w,t,e):a.setProvider(f.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:d("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:d("models.enabledCount",{enabled:f.enabledCount,total:f.models.length})}),(0,r.jsx)(aj,{size:"small",disabled:j||!y.canEnable,"aria-describedby":S?void 0:C,onClick:()=>T(!0,y.enableRefs),children:k?d("models.enableShown"):d("models.enableAll")}),(0,r.jsx)(aj,{size:"small",disabled:j||!y.canDisable,"aria-describedby":S?$?N:void 0:C,onClick:()=>T(!1,y.disableRefs),children:k?d("models.disableShown"):d("models.disableAll")}),(0,r.jsx)(aj,{size:"small",disabled:j||x.refreshing,title:d("models.refreshCatalogHint"),onClick:x.refresh,children:x.refreshing?d("models.refreshingCatalog"):d("models.refreshCatalog")})]}),x.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:d(x.note)}),!S&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:d("models.enabledProjectScope")}),E&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:d("models.enabledLastModel")}),g&&(0,r.jsx)("div",{className:"enabled-models-error",children:g.messageKey?d(g.messageKey):g.message}),f.models.length>8&&(0,r.jsx)("input",{value:c,onChange:e=>u(e.target.value),placeholder:d("models.enabledFilterPlaceholder",{count:f.models.length}),"aria-label":d("models.enabledFilter"),className:"enabled-models-filter"}),o&&f.models.length>0&&(0,r.jsx)("div",{id:I,className:"enabled-models-note",children:d("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:0===f.models.length&&l||d("models.enabledNoMatches")}):v.map(e=>{let t=a$(p,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:d("models.enabledPinHint"),children:e.thinkingPin}),o&&(0,r.jsx)(aT,{modelName:e.name,effective:e.contextWindow,value:i,disabled:o.disabled,describedBy:I,onChange:t=>o.onChange(e.id,t)}),(0,r.jsx)(aw,{checked:e.enabled,loading:m===e.ref,disabled:j||!p?.editable||t,label:d("models.enabledToggle",{model:e.name}),describedBy:S?t?N:void 0:C,onChange:t=>a.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function aO(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:a,inputLabel:o,disabled:l=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!l&&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:l||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:a})]})]})}let aW={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},"llama.cpp":{symbol:"llama-cpp",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 aF(e){let{id:t,size:n}=e,i=aW[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 aD=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],aB="pi-web:provider-usage:";function a_(e){let{providerId:t,enabled:n}=e;return aD.includes(t)?(0,r.jsx)(aH,{providerId:t,enabled:n}):null}function aH(e){let{providerId:t,enabled:n}=e,[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:m,t:g}=(0,eX.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),a(null);try{let e=localStorage.getItem(`${aB}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&a(t)}}catch{try{localStorage.removeItem(`${aB}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let f=(0,i.useCallback)(async()=>{l(!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){a(n);try{localStorage.setItem(`${aB}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??g("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:g("providerUsage.queryFailed"))}finally{l(!1)}},[t,g]),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:g("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:f,disabled:!n||o,title:g(o?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":g(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(m),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:g("providerUsage.updated",{time:(0,tm.ob)(x.capturedAt,m)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:g("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 ":"$"}${aU(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${aU(e.remaining)} / ${aU(e.limit)}`:e.period??t}(e,g("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 aU(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function aq(){let e=sC("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 aK(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let aZ=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],aV={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function aJ(e){let{label:t,children:n}=e;return(0,r.jsx)(al,{label:t,children:n})}let aG={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 aY(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:{...aG,fontFamily:s?"var(--font-mono)":"inherit"}})}function aX(e){let{value:t,onChange:n,placeholder:s,mono:a,onKeyDown:o,autoComplete:l="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eX.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:{...aG,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:l,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 aQ(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?{...aG,borderColor:"#ef4444"}:aG})}function a0(e){let{value:t,onChange:n,options:i,required:s}=e,{t:a}=(0,eX.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...aG,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",a("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function a1(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 a2(e){let{children:t}=e;return(0,r.jsx)(ao,{children:t})}function a4(e){let{name:t,editingName:n,fallbackLabel:s,provider:a,onChange:o,onEditingNameChange:l,onRename:d,onDelete:c,onAddModels:u,enabledModels:p}=e,{t:h}=(0,eX.s)(),[m,g]=(0,i.useState)({phase:"idle"}),[f,x]=(0,i.useState)(""),[b,v]=(0,i.useState)([]),y=(0,i.useRef)(0),k=(0,i.useRef)(null),j=(0,i.useId)(),w=(e,t)=>o({...a,[e]:t});(0,i.useEffect)(()=>{y.current+=1,g({phase:"idle"}),x(""),v([])},[t,a.baseUrl,a.api,a.apiKey]);let S=(0,i.useCallback)(async()=>{if("loading"===m.phase)return;let e=++y.current;g({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:{...a,models:void 0}})}),r=await n.json();if(e!==y.current)return;if(!n.ok||r.error||!r.models)return void g({phase:"error",message:r.error??`HTTP ${n.status}`});g({phase:"success",models:r.models,endpoint:r.endpoint??a.baseUrl??""})}catch(t){if(e!==y.current)return;g({phase:"error",message:t instanceof Error?t.message:String(t)})}},[m.phase,t,a]),C=new Set((a.models??[]).map(e=>e.id)),N="success"===m.phase?m.models:[],I=f.trim().toLocaleLowerCase(),$=N.filter(e=>!I||e.id.toLocaleLowerCase().includes(I)||e.name?.toLocaleLowerCase().includes(I)),E=$.slice(0,300),T=E.filter(e=>!C.has(e.id)).map(e=>e.id),M=b.filter(e=>!C.has(e)).length,R=T.length>0&&T.every(e=>b.includes(e)),A=!R&&T.some(e=>b.includes(e));return(0,i.useEffect)(()=>{k.current&&(k.current.indeterminate=A)},[A]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:h("i18n.provider")})}),(0,r.jsxs)(as,{children:[(0,r.jsx)(aA,{providerId:t,controller:p,noteId:j}),(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:c,children:h("i18n.delete")})]})]}),(0,r.jsx)(aP,{providerId:t,controller:p,id:j})]}),(0,r.jsxs)(aJ,{label:h("i18n.providerId"),children:[(0,r.jsx)(aY,{value:n,onChange:l,placeholder:"provider-id",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>d(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:h("i18n.rename")})]}),(0,r.jsx)(aJ,{label:h("models.providerDisplayName"),children:(0,r.jsx)(aY,{value:a.name??"",onChange:e=>o(function(e,t){if(!t.trim()){let t={...e};return delete t.name,t}return"name"in e?{...e,name:t}:{name:t,...e}}(a,e)),placeholder:s})}),(0,r.jsx)(aJ,{label:"Base URL",children:(0,r.jsx)(aY,{value:a.baseUrl??"",onChange:e=>w("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(aJ,{label:"API Key",children:(0,r.jsx)(aX,{value:a.apiKey??"",onChange:e=>w("apiKey",e||void 0),placeholder:h("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(aJ,{label:"API",children:(0,r.jsx)(a0,{value:a.api??"",onChange:e=>w("api",e||void 0),options:aZ})}),(0,r.jsx)(aJ,{label:"Headers",children:(0,r.jsx)(oe,{headers:a.headers,onChange:e=>w("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==m.phase&&(0,r.jsx)("button",{onClick:S,disabled:"loading"===m.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===m.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===m.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===m.phase?h("models.discoveryFetching"):h("models.discoveryFetch")}),"error"===m.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:m.message}),"success"===m.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:f,onChange:e=>x(e.target.value),placeholder:h("models.discoveryFilterPlaceholder",{count:m.models.length}),"aria-label":h("models.discoveryFilter"),style:{...aG,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:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:k,type:"checkbox",checked:R,disabled:0===T.length,onChange:()=>{let e=new Set(T);v(t=>R?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),h("models.discoverySelectShown")]}),0===E.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:h("models.discoveryNoMatches")}):E.map((e,t)=>{let n=C.has(e.id),i=b.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:h("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:m.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:$.length>E.length?h("models.discoveryShowing",{shown:E.length,total:$.length}):h("models.discoveryFetched",{count:m.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==m.phase)return;let e=new Set(b),t=m.models.filter(t=>e.has(t.id)&&!C.has(t.id));0!==t.length&&(u(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?h("models.discoveryAddSelectedCount",{count:M}):h("models.discoveryAddSelected")})]})]})]})]})}let a8=["off","minimal","low","medium","high","xhigh","max"],a6={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function a3(e){let{value:t,onChange:n}=e,{t:i}=(0,eX.s)(),s=t??{},a=(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:a8.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",o="string"==typeof t?t:"",l=a6[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:l,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:()=>a(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>a(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:()=>a(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=>a(e,t.target.value),onFocus:()=>{"string"!==n&&a(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 a5={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function a9(e){return e.compat?.thinkingFormat==="deepseek"}function a7(e,t){return{...e.compat??{},...t.compat??{}}}function oe(e){let{headers:t,onChange:n}=e,{t:s}=(0,eX.s)(),[a,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),l=(0,i.useRef)(a.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(a.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:[a.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:{...aG,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:{...aG,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void d(a.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>o(e=>[...e,{id:l.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 ot(e){let{providerName:t,provider:n,model:s,onChange:a,onDelete:o}=e,[l,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(()=>s_(s.cost)),x=(0,i.useRef)(g),[b,v]=(0,i.useState)(!1),y=(0,i.useRef)(0),k=s.baseUrl??n.baseUrl,j=(0,i.useRef)(0),w=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>a({...s,[e]:t}),N=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return c("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[c("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,l.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"}),w.current=null},[t,k,s.id]);let I=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===l.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,l.phase]),$=(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"});k?.trim()&&r.set("baseUrl",k.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 l=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 a=sH(s_(i));s>0&&a&&(n.cost={...i,...a},r+=s)}return{model:n,appliedCount:r}}(s,o.recommendation.preset);l.appliedCount>0&&(w.current=s,a(l.model)),m(!1),p({phase:"success",recommendation:o.recommendation,appliedCount:l.appliedCount})}catch(e){if(n!==j.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,a,k,t]),E=(()=>{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}`})(),T="error"===u.phase?u.message:E,M="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;a9(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 P=sO(s),z=sW(P),O=[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!==z?c("models.imageMaxBytesSummary",{size:sF(z)}):null].filter(e=>!!e),W=O.length?O.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:c("i18n.model")})}),(0,r.jsxs)(as,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.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)(aj,{size:"small",variant:"success"===l.phase?"primary":"secondary",onClick:"success"===l.phase?()=>d({phase:"idle"}):I,disabled:!s.id.trim()||"testing"===l.phase,title:c("i18n.testConnection"),className:"success"===l.phase?"is-success":void 0,children:["success"===l.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"===l.phase?c("i18n.checking"):"success"===l.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(aj,{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)(aJ,{label:"ID *",children:(0,r.jsx)(aY,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aJ,{label:"Name",children:(0,r.jsx)(aY,{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 $(),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")})]}),T&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:T,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),w.current&&(0,r.jsx)("button",{onClick:()=>{let e=w.current;e&&(w.current=null,a(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)(a2,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(a1,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(a1,{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)(a2,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void m(!1);S.current=s.cost;let e=s_(s.cost);x.current=e,f(e),m(!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)(aJ,{label:c("models.contextWindow"),children:(0,r.jsx)(aQ,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aJ,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(aQ,{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)(aJ,{label:n,children:(0,r.jsx)(aQ,{value:g[t],onChange:e=>{let n,r,i;return r=sH(n={...x.current,[t]:e}),i={...s},void(x.current=n,f(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,a(i))},placeholder:"0"})},t)}),sU(g)&&!sH(g)&&(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,a=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:a?"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:()=>v(e=>!e),"aria-expanded":b,"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:W})]}),(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:b?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(aJ,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(aY,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(aJ,{label:c("models.apiOverride"),children:(0,r.jsx)(a0,{value:s.api??"",onChange:e=>C("api",e||void 0),options:aZ})}),(0,r.jsxs)(aJ,{label:c("models.headers"),children:[(0,r.jsx)(oe,{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!==P)&&(0,r.jsxs)(aJ,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(aQ,{value:void 0===P?"":String(P),onChange:e=>{var t;let n,r,i,o;return a((t=e.trim()||void 0,n={...sz(s.inputLimits)?s.inputLimits:{}},r={...sz(n.images)?n.images:{}},i={...sz(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=sW(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===z&&void 0!==P}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==z&&`${sF(z)} \xb7 `,c("models.imageMaxBytesHelp",{size:sF(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)(a2,{children:c("models.compatibility")}),(0,r.jsx)(a1,{label:c("models.deepSeekThinkingCompat"),checked:a9(s),onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...a5}};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)(a1,{label:c("models.developerRole"),checked:!1!==a7(n,s).supportsDeveloperRole,onChange:e=>a(sq(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(a1,{label:c("models.adaptiveThinking"),checked:!0===a7(n,s).forceAdaptiveThinking,onChange:e=>a(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return sq(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)(a2,{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)(a3,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function on(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,[o,l]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eX.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)(()=>{l({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let m=(0,i.useCallback)(()=>{p.current?.close(),l({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?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({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?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(e.close(),l({phase:"success"}),n()):"error"===r.type?(e.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),l({phase:"idle"}))},e.onerror=()=>{e.close(),l(e=>"success"===e.phase?e:{phase:"error",message:d("models.connectionLost")})}},[t.id,n,d]),g=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),l({phase:"idle"}),n()},[t.id,n]),f=(0,i.useCallback)(async(e,n)=>{if(n.trim()){l({phase:"progress",message:d("models.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(()=>({}));l({phase:"error",message:e.error??d("models.serverError",{status:r.status})});return}u("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}}},[t.id,d]),x=(0,i.useCallback)(async(e,n)=>{l({phase:"progress",message:d("i18n.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(()=>({}));l({phase:"error",message:e.error??d("models.serverError",{status:r.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}},[t.id,d]),b="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)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:d("i18n.subscription")})}),(0,r.jsxs)(as,{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:t.loggedIn?d("i18n.connected"):d("i18n.notConnected")})]}),b?(0,r.jsx)(aj,{size:"small",onClick:()=>{p.current?.close(),l({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aj,{variant:"primary",size:"small",onClick:m,children:t.loggedIn?d("i18n.relogin"):d("i18n.login")}),t.loggedIn&&(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:g,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)(aO,{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 f(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?` ${d("models.deviceCodeExpires",{minutes:Math.ceil(o.expiresInSeconds/60)})}`:""]})]}),"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)(a_,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(az,{providerId:t.id,controller:s,contextSettings:a})]})}let or="http://127.0.0.1:8080";function oi(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,o=t.id===s$,[l,d]=(0,i.useState)(o&&!t.configured?or:""),[c,u]=(0,i.useState)(""),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(!1),{t:y}=(0,eX.s)(),k=!!(o?l.trim():c.trim());async function j(){if(k&&!p){h(!0),x(null),v(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:c.trim(),...o?{serverUrl:l.trim()}:{}})}),r=await e.json();!e.ok||r.error?x(r.error??`HTTP ${e.status}`):(u(""),o&&(d(""),s.refresh(),r.catalog?.completed||x(y(r.catalog?.reason==="offline"?"models.catalogOffline":"models.catalogUnreachable"))),v(!0),setTimeout(()=>v(!1),2e3),n())}catch(e){x(String(e))}finally{h(!1)}}}let w=(0,i.useCallback)(async()=>{g(!0),x(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?x(r.error??`HTTP ${e.status}`):n()}catch(e){x(String(e))}finally{g(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:o?t.displayName:"API Key"})}),(0,r.jsxs)(as,{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:t.configured?y("i18n.configured"):y("i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:w,disabled:m,children:m?y("i18n.removing"):y("i18n.disconnect")})]})]}),o&&(0,r.jsxs)("label",{style:{display:"grid",gap:6},children:[y("models.llamaRouterUrl"),(0,r.jsx)("input",{type:"url",style:aG,value:l,placeholder:or,onChange:e=>d(e.target.value),spellCheck:!1})]}),!o&&!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?y("models.apiKeyEnableOne",{provider:t.displayName}):y("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(aX,{value:c,onChange:u,onKeyDown:e=>{"Enter"===e.key&&j()},placeholder:o?y("models.optionalApiKey"):t.configured?y("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:j,disabled:p||!k||b,style:{padding:"6px 12px",background:b?"#16a34a":k?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:b?"#fff":k?"var(--accent-contrast)":"var(--text-dim)",cursor:p||!k||b?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[b&&(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"})}),b?y("i18n.saved"):p?y("i18n.saving"):y("i18n.save")]})]}),f&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:f}),(0,r.jsx)(a_,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(az,{providerId:t.id,controller:s,contextSettings:a,emptyCatalogHint:o?y("models.llamaEmptyCatalog"):void 0})]})}function os(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:a,onAddCustom:o,onClose:l}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,eX.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),m=t.filter(e=>!e.loggedIn&&sG(h,e.id,e.name)),g=n.filter(e=>!e.configured&&sG(h,e.id,e.displayName)),f=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=m.length+g.length+ +!!f,b={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&&l()},onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),l())},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:[f&&(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")}),f&&(0,r.jsxs)("button",{onClick:()=>{o(),l()},style:b,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"})]})})]}),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),l()},style:b,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)(aF,{id:e.id,size:28})]},e.id)),g.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(m.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),g.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),l()},style:b,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:e.id===s$?u("models.optionalApiKey"):u(1===e.modelCount?"models.modelCountOne":"models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(aF,{id:e.id,size:28})]},e.id))]})})]})})}function oa(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:a}=(0,eX.s)(),{openDetail:o,closeDetail:l}=s1(),d=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(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 g=(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?aM[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=g;let f=(0,i.useCallback)((e,t,n)=>{g(e,{op:"models",refs:t,enabled:n})},[g]),x=(0,i.useCallback)((e,t)=>{g(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[g]),b=(0,i.useCallback)(()=>g("clear",{op:"clear"}),[g]),v=(0,i.useCallback)(()=>g("prune",{op:"prune"}),[g]),y=(0,i.useCallback)(()=>m(e=>e+1),[]),k=(0,i.useCallback)((e,n)=>{g("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)})},[g,t]);return{view:t,loading:r,pending:a,failure:l,setModels:f,setProvider:x,clearScope:b,pruneStale:v,refresh:y,resync:k}}(s),[c,u]=(0,i.useState)({providers:{}}),[p,h]=(0,i.useState)(!0),[m,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(!1),[j,w]=(0,i.useState)(aq),[S,C]=(0,i.useState)([]),[N,I]=(0,i.useState)([]),[$,E]=(0,i.useState)({}),[T,M]=(0,i.useState)(()=>new Map),[R,A]=(0,i.useState)(!1),[L,P]=(0,i.useState)(!1),z=(0,i.useRef)(new Set),O=(0,i.useRef)(new Map),W=(0,i.useRef)(new Map),F=(0,i.useRef)(new WeakMap),D=(0,i.useRef)(0),B=(0,i.useRef)(null),[_,H]=(0,i.useState)(null),[U,q]=(0,i.useState)(null),K=(0,i.useCallback)(()=>fetch("/api/auth/providers").then(e=>e.json()).then(e=>(Array.isArray(e.oauthProviders)&&C(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&I(e.apiKeyProviders),E(e.providerNames??{}),!0)).catch(()=>!1).finally(()=>A(!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:{}};u(t),z.current=new Set(Object.keys(t.providers??{})),W.current=sK(t),M(sX(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=>v(e instanceof Error?e.message:String(e))).finally(()=>h(!1)),K()},[K]),(0,i.useEffect)(()=>{j&&sN("models",JSON.stringify(j))},[j]),(0,i.useEffect)(()=>{if(j?.type!=="provider")return;let e=c.providers?.[j.name];!(!e||!aK(e)||T.has(j.name))&&(S.some(e=>e.id===j.name)?w({type:"oauth",providerId:j.name}):N.some(e=>e.id===j.name)&&w({type:"apikey",providerId:j.name}))},[N,c.providers,S,T,j]);let Z=e=>({overrides:c.providers?.[e]?.modelOverrides,disabled:p||m||null!==b,onChange:(t,n)=>{try{u(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},a={...s.modelOverrides},o=Object.hasOwn(a,n)?a[n]:void 0;if(void 0!==o&&!sE(o))throw Error("Model override must be an object");let l={...o};return void 0===r?delete l.contextWindow:l.contextWindow=r,Object.keys(l).length?Object.defineProperty(a,n,{value:l,enumerable:!0,configurable:!0}):delete a[n],Object.keys(a).length?s.modelOverrides=a:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(c,e,t,n)),k(!1),x(null)}catch(e){x(String(e))}}}),V=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;u(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),w({type:"provider",name:e})},[c.providers]),J=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),G=(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:a}=t,o=sJ(t,n);o===r?s.delete(o):null!==o&&s.set(o,r);let l=a.get(n);l&&(a.delete(n),a.set(r,l));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:z.current,renames:O.current,slots:W.current},t,n);return r?(u(r),q(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},[]),Y=(0,i.useCallback)((e,t)=>{G(c,e,t)?x(null):x(a("models.providerIdTaken",{name:t}))},[G,c,a]),X=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=sJ(t={savedProviders:z.current,renames:O.current,slots:W.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...c.providers??{}},delete r[e],{...c,providers:r}),s=Object.keys(i.providers??{});q(t=>t?.provider===e?null:t),u(i),w(s.length>0?{type:"provider",name:s[0]}:null),l()},[c,l]),Q=(0,i.useCallback)(e=>{sZ(W.current,e,1),u(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),u(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return w({type:"model",providerName:e,index:n}),t})},[]),ee=(0,i.useCallback)((e,t)=>{u(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));sZ(W.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],a=new Set(s.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),et=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]],a=F.current.get(s[t]);return a&&F.current.set(n,a),s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),en=(0,i.useCallback)(e=>{e&&(u(e.config),k(!1),x(null),w(t=>t?.type==="model"&&t.providerName===e.providerName?{...t,index:e.order.indexOf(t.index)}:t))},[]),er=(0,i.useCallback)((e,t,n)=>{m||b||en(function(e,t,n,r,i){let s=e.providers?.[n]?.models??[];if(r<0||r>=s.length||i<0||i>=s.length)return null;let a=[...s.keys()];return a.splice(r,1),a.splice(i,0,r),sV(e,t,n,a)}(c,W.current,e,t,n))},[en,c,b,m]),ei=(0,i.useCallback)(e=>{if(!m&&!b){var t;let n,r;en((t=W.current,n=c.providers?.[e]?.models??[],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sV(c,t,e,[...n.keys()].sort((e,t)=>r.compare(sY(n[e]),sY(n[t]))))))}},[en,c,b,m]),es=(0,i.useCallback)((e,t)=>{W.current.get(e)?.splice(t,1),u(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}),l()},[l]),ea=(0,i.useCallback)(async()=>{if(b)return;g(!0),x(null),k(!1);let e=c,t=U?.name.trim();if(U&&t&&c.providers?.[U.provider]){let n=G(c,U.provider,t);if(!n){x(a("models.providerIdTaken",{name:t})),g(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!sE(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(sE(n)&&sE(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!sE(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=sM(r.contextWindow);if(void 0===n)throw new sT(`${e}/${t}`);r.contextWindow=n}return t}(e);if(sL(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!sL(t))continue;if(t.oauth&&!t.baseUrl)throw new sA(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(sP),r=sL(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 sA(e,"empty")}var r=e;if(sz(r.providers)){for(let[e,t]of Object.entries(r.providers))if(sz(t)&&Array.isArray(t.models))for(let n of t.models){if(!sz(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=sO(n);if(void 0!==t&&void 0===sW(t))throw new sD(`${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)x(i.error??`HTTP ${t.status}`);else{k(!0),setTimeout(()=>k(!1),2e3);let t=[...O.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 a=e[s];a&&t.id&&a!==t.id&&i.push({from:`${r(n)}/${a}`,to:`${n}/${t.id}`})})}return i}(e,W.current,O.current);z.current=new Set(Object.keys(e.providers??{})),W.current=sK(e),O.current.clear(),d.resync(t,n);let r=sX(e);K().then(e=>{e&&M(r)})}}catch(e){e instanceof sA?(x(a(aV[e.problem],{provider:e.provider})),w({type:"provider",name:e.provider})):e instanceof sT?x(a("models.contextInvalid",{model:e.model})):x(e instanceof sD?a("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{g(!1)}},[G,c,d,b,U,K,a]),eo=Object.entries(c.providers??{}).filter(e=>{let[t,n]=e;if(!aK(n)||T.has(t))return!0;let r=S.some(e=>e.id===t)||N.some(e=>e.id===t);return R&&!r}),el=(e,t)=>{var n,r,i;return n=$[e]??d.view?.providers.find(t=>t.id===e)?.name,i=void 0!==(r=T.get(e))&&n?.trim()===r.trim()?void 0:n,t.name?.trim()||i?.trim()||e},ed=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=aE(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(d.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},ec=S.filter(e=>e.loggedIn),eu=N.filter(e=>e.configured),ep=(()=>{if(!j)return null;if("oauth"===j.type){let e=S.find(e=>e.id===j.providerId);return e?(0,r.jsx)(on,{provider:e,onRefresh:K,enabledModels:d,contextSettings:Z(e.id)},e.id):null}if("apikey"===j.type){let e=N.find(e=>e.id===j.providerId);return e?(0,r.jsx)(oi,{provider:e,onRefresh:K,enabledModels:d,contextSettings:Z(e.id)},e.id):null}if("provider"===j.type){let e=c.providers?.[j.name];return e&&eo.some(e=>{let[t]=e;return t===j.name})?(0,r.jsx)(a4,{name:j.name,editingName:U?.provider===j.name?U.name:j.name,fallbackLabel:el(j.name,{}),provider:e,onChange:e=>J(j.name,e),onEditingNameChange:e=>q(e===j.name?null:{provider:j.name,name:e}),onRename:e=>Y(j.name,e),onDelete:()=>X(j.name),onAddModels:e=>ee(j.name,e),enabledModels:d},j.name):null}let e=c.providers?.[j.providerName],t=e?.models?.[j.index];return t?(0,r.jsx)(ot,{providerName:j.providerName,provider:e,model:t,onChange:e=>et(j.providerName,j.index,e),onDelete:()=>es(j.providerName,j.index)},`${j.providerName}-${j.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(sQ,{embedded:n,title:a("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:a("i18n.close"),onClose:t,children:[(0,r.jsx)(aR,{controller:d}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsxs)(s3,{children:[ec.map(e=>{let t=j?.type==="oauth"&&j.providerId===e.id;return(0,r.jsxs)(ae,{active:t,onClick:()=>w({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(aF,{id:e.id,size:16}),(0,r.jsx)(at,{className:"is-grow",children:e.name}),ed(e.id)]},e.id)}),eu.map(e=>{let t=j?.type==="apikey"&&j.providerId===e.id;return(0,r.jsxs)(ae,{active:t,onClick:()=>w({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(aF,{id:e.id,size:16}),(0,r.jsx)(at,{className:"is-grow",children:e.displayName}),ed(e.id)]},e.id)}),(ec.length>0||eu.length>0)&&eo.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):eo.map(e=>{let[t,n]=e,i=j?.type==="provider"&&j.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(ae,{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)(at,{className:"is-grow",children:el(t,n)}),ed(t)]}),s.map((e,n)=>{var i;let s,o,l=j?.type==="model"&&j.providerName===t&&j.index===n,d=F.current.get(e);d||(d=`model-${++D.current}`,F.current.set(e,d));let c=_?.providerName===t&&_.index===n?_:null;return(0,r.jsxs)(ae,{active:l,className:"models-sidebar-indented-item",style:c?{boxShadow:`inset 0 ${c.after?"-2px":"2px"} 0 var(--accent)`}:void 0,"aria-keyshortcuts":"Alt+ArrowUp Alt+ArrowDown",onClick:()=>w({type:"model",providerName:t,index:n}),onKeyDown:e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let r="ArrowUp"===e.key?-1:"ArrowDown"===e.key?1:null;null!==r&&(e.preventDefault(),er(t,n,n+r))},...(i=e.id,s=e=>{var r;let i,s=B.current;if(s?.providerName!==t)return null;let a=e.currentTarget.getBoundingClientRect(),o=e.clientY>=a.top+a.height/2;return{from:s.index,to:(r=s.index,r<(i=o?n+1:n)?i-1:i),after:o}},{draggable:!m&&!b,onDragStart:e=>{B.current={providerName:t,index:n},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)},onDragOver:e=>{let r=s(e);if(!r)return;e.preventDefault(),e.dataTransfer.dropEffect="move";let i=r.to===r.from?null:{providerName:t,index:n,after:r.after};H(e=>e?.providerName===i?.providerName&&e?.index===i?.index&&e?.after===i?.after?e:i)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||H(e=>e?.providerName===t&&e.index===n?null:e)},onDrop:e=>{let n=s(e);n&&(e.preventDefault(),er(t,n.from,n.to),o())},onDragEnd:o=()=>{B.current=null,H(null)}}),children:[(0,r.jsx)(at,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:sY(e)||a("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"})]},d)}),(0,r.jsxs)("div",{className:"models-sidebar-model-footer",children:[(0,r.jsx)(ae,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),Q(t)},children:(0,r.jsxs)(at,{children:["+ ",a("i18n.model")]})}),(0,r.jsx)("button",{type:"button",className:"models-sidebar-sort-button","aria-label":a("models.sortByName"),title:a("models.sortByName"),disabled:m||null!==b||s.length<2,onClick:()=>ei(t),children:"A–Z"})]})]},t)})]}),(0,r.jsx)(aS,{onClick:e=>{e.preventDefault(),P(!0)},children:a("i18n.addProvider")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:p?null:ep??(0,r.jsx)(ab,{children:a("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(ay,{status:b||f?(0,r.jsx)("span",{style:{color:"#f87171"},children:b?a("models.configUnreadable",{error:b}):f}):a("models.applyHelp"),children:[!n&&(0,r.jsx)(aj,{onClick:t,children:a("i18n.cancel")}),(0,r.jsxs)(aj,{variant:"primary",onClick:ea,disabled:m||y||null!==b,className:y?"is-success":void 0,children:[y&&(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:y?a("i18n.saved"):m?a("i18n.saving"):a("i18n.save")})]})]})]}),L&&(0,r.jsx)(os,{oauthProviders:S,apiKeyProviders:N,onSelectOAuth:e=>{w({type:"oauth",providerId:e}),o()},onSelectApiKey:e=>{w({type:"apikey",providerId:e}),o()},onAddCustom:()=>{V(),o()},onClose:()=>P(!1)})]})}let oo=null;async function ol(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(oo)return oo;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 oo=null,!1}})();return oo=t,t.then(e=>{e||oo!==t||(oo=null)}),t}var od=n(9258);function oc(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function ou(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function op(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function oh(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function om(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function og(e,t){return e?e.slice(0,8):t}function of(e){let{skill:t,cwd:n,onToggle:s,toggling:a,saveError:o,updateStatus:l,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:m}=(0,eX.s)(),g=op(t),f=!t.disableModelInvocation,[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),k=t.filePath.split(/[\\/]/).pop(),[j,w]=(0,i.useState)([]),S=j.at(-1)??k,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[I,$]=(0,i.useState)(0),E=(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+1):w(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||v)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,v,I]),(0,i.useEffect)(()=>{let e=new AbortController;return b(null),y(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});S!==k&&i.set("document",S);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),a=await s.json();if(!s.ok||a.error||"string"!=typeof a.content)throw Error(a.error??`HTTP ${s.status}`);b((r=a.content,(0,od.yv)(r).rest.trim()))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,S,k]),(0,r.jsxs)(an,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(ar,{children:[(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:g,children:oh(g,m)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===g?eh(t.filePath,n):ep(t.filePath)})]}),(0,r.jsx)(as,{children:(0,r.jsx)(aw,{checked:f,loading:a,label:m(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:m("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(al,{label:m("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)(al,{label:m("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:og(l?.currentVersion??t.install.versionHash,m("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(aj,{size:"small",onClick:p,disabled:d||c,children:m("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:og(l.latestVersion,m("i18n.unknown"))}),(d||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:d?m("i18n.checking"):l?.state==="up-to-date"?m("i18n.upToDate"):l?.state==="unsupported"?m("i18n.automaticChecksUnavailable"):l?.message||m("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(aj,{variant:"primary",size:"small",onClick:h,disabled:c||d,children:m(c?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(al,{label:m("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(al,{label:m("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(al,{label:m("skills.instructions"),ref:C,children:[j.length>0&&(0,r.jsx)(ar,{children:(0,r.jsxs)(ai,{children:[(0,r.jsx)(aj,{size:"small",onClick:()=>{N.current="",w(e=>e.slice(0,-1))},children:m("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),v?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:v}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:m("i18n.loading")}):x?(0,r.jsx)(nF.m,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:E,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:m("skills.noInstructions")})]})]})}function ox(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:a}=e,{t:o}=(0,eX.s)(),[l,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(new Set),[j,w]=(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),g(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 g(n.error);u(n.results??[]),0===(n.results??[]).length&&g(o("i18n.noSkills"))}catch(e){g(String(e))}finally{h(!1)}}},[o]),N=(0,i.useCallback)(async e=>{x(e),v(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 v(r.error??`HTTP ${n.status}`);k(t=>new Set(t).add(`${j}:${e}`)),a()}catch(e){v(String(e))}finally{x(null)}},[a,j,t]),I="global"===j?"~/.pi/agent/skills/":`${ep(t)}/.pi/skills/`;return(0,r.jsxs)(an,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(am,{title:o("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(ah,{value:j,label:o("config.saveTo"),options:[{value:"global",label:oh("global",o)},{value:"project",label:oh("project",o),disabled:!s}],path:I,disabledReason:o("trust.projectScopeUnavailable"),onChange:w})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Enter"!==e.key||p||C(l))},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)(aj,{variant:"primary",onClick:()=>C(l),disabled:p||!l.trim(),children:p?o("i18n.searching"):o("i18n.search")})]}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:m}),b&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:b})]}),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=f===e.package,s=e.package.indexOf("@"),a=s>-1?e.package.slice(0,s):e.package,l=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:l??a}),(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:a}),(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)(aj,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==f,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 ob(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a}=e,{t:o}=(0,eX.s)(),[l,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(()=>sC("skills",t)),[f,x]=(0,i.useState)(new Set),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(null),[j,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)({}),[$,E]=(0,i.useState)(new Set),[T,M]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,P]=(0,i.useState)(null),[z,O]=(0,i.useState)(!0),W=(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),O(n.projectResourcesLoaded??!0),g(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)(()=>{I({}),P(null),W()},[t]);let F=ou(a),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,W())},[F,W]),(0,i.useEffect)(()=>{m&&sN("skills",m,t)},[t,m]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:l.filter(e=>!!e.install)).map(om).filter(e=>!!e);if(0!==n.length){P(null),E(e=>new Set([...e,...n])),e||M(!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}`);I(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{E(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,l]),_=(0,i.useCallback)(async e=>{if(!e.install)return;let n=om(e);A(n),P(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 W();let s=i.skill?.install?.versionHash;I(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,W]),H=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),v(null),w(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 v(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){v(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=oc(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])),k(e),v(null),w(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 a=n.results;d(e=>{let t;return t=new Set(a.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let l=a.filter(e=>e.error);if(l.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[o("skills.bulkFailed",{count:l.length,total:a.length}),...l.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{k(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[o]),q=l.find(e=>e.filePath===m)??null,K=c||f.size>0||null!==R;return(0,r.jsxs)(sQ,{embedded:s,title:o("common.skills"),subtitle:ep(t),closeLabel:o("i18n.close"),onClose:n,children:[!z&&(0,r.jsx)(ax,{message:o("trust.skillsNotLoaded")}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{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===l.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"===op(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===op(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===op(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===op(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===op(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&m===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(ae,{active:i,onClick:()=>{g(e.filePath),C(!1)},children:[(0,r.jsx)(aC,{active:!s}),(0,r.jsx)(at,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=om(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,a=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(s5,{aside:(0,r.jsx)(s9,{enabled:s,total:i.length,disabled:K,loading:y===t,label:o(a?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),j?.group===t&&(0,r.jsx)(s7,{error:j.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(aS,{onClick:()=>C(!0),active:S,children:o("i18n.addSkill")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:S?(0,r.jsx)(ox,{cwd:t,projectResourcesLoaded:z,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{W()}}):c?null:q?(0,r.jsx)(of,{skill:q,cwd:t,onToggle:H,toggling:f.has(q.filePath),saveError:b,updateStatus:om(q)?N[om(q)]:void 0,checkingUpdate:!!om(q)&&$.has(om(q)),updating:R===om(q),updateError:L,onCheckUpdate:()=>void B(q),onUpdate:()=>void _(q)},q.filePath):(0,r.jsx)(ab,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(ay,{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)(aj,{onClick:n,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(aj,{variant:"secondary",onClick:()=>void B(),disabled:T||null!==R,children:T?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let ov={builtin:0,global:1,workspace:2,project:3},oy=["read","bash","edit","write","grep","find","ls"],ok=["","off","minimal","low","medium","high","xhigh","max"],oj={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},ow={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"},oS={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function oC(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 oN(e){return`${e.scope}:${e.name}`}function oI(e){return"global"===e||"project"===e}function o$(e){return oI(e)||"builtin"===e}function oE(e){let{label:t,children:n}=e;return(0,r.jsx)(al,{label:t,children:n})}function oT(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 oM(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:a,embedded:o=!1,trust:l}=e,d=(0,eQ.a)(),{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)([]),[h,m]=(0,i.useState)([]),[g,f]=(0,i.useState)(!0),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(()=>sC("agents",t)),[k,j]=(0,i.useState)(oj),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[I,$]=(0,i.useState)(!0),[E,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,_]=(0,i.useState)(!0),[H,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),Y=(0,i.useMemo)(()=>u.find(e=>oN(e)===v)??null,[u,v]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{$(!0),z(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??sC("agents",t),a=i.find(e=>oN(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(a?oN(a):null),a&&(j(oC(a)),S(oI(a.scope)?"edit":"view"),oI(a.scope)&&N(a.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return _(!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}`);W(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||_(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{v&&sN("agents",v,t)},[t,v]);let ee=ou(l);(0,i.useEffect)(()=>{let e=new AbortController;return f(!0),b(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}`);m(r.modelList??[]),b(r.modelError??null)}catch(t){if(e.signal.aborted)return;b(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||f(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),z(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:k})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(oN(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}},en=async()=>{if(Y&&oI(Y.scope)&&window.confirm(c("agents.deleteConfirm",{name:Y.displayName}))){T(!0),z(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,es=!er||E||A,ea=ei?C:Y?.scope,eo=ei?"global"===C?`~/.pi/agent/agents/${k.name||"..."}.md`:`./.pi/agents/${k.name||"..."}.md`:Y?(Y.filePath?"project"===Y.scope||"workspace"===Y.scope?eh(Y.filePath,t):ep(Y.filePath):null)??c("agents.builtinPath"):"",el=ei?eo:Y?.filePath??eo,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=k.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&ok.includes(r)?e.slice(0,n):e}(k.model,ed),eu=!ec||ed(ec),em=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eg=es?{...ow,...oS}:ow,ef=ei?es:!Y||!o$(Y.scope)||E||A,ex=(e,t)=>{j(n=>({...n,[e]:t}))},eb=0===k.tools.length&&!k.loadSkills&&!k.loadExtensions,ev=async e=>{if(ei)return void ex("enabled",e);if(Y&&o$(Y.scope)){L(!0),z(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.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=>oN(e)===oN(i)?i:e)),j(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ey=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}`);W(r.enabled),V(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{U(!1)}},ek=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){G(!0),K(null);try{await ic(n,{type:"reload"}),V(!1),a?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(sQ,{embedded:o,title:c("common.agents"),subtitle:ep(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")}),Z&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[Z&&n&&(0,r.jsx)(aj,{size:"small",onClick:()=>void ej(),disabled:J||H,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||H,onChange:e=>D(Number(e.target.value)),onBlur:()=>void ek(F)})]}),(0,r.jsx)(aw,{checked:O,disabled:B||J,loading:H,label:c("agents.builtInTitle"),onChange:e=>void ey(e)})]})]}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:I?(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)(s5,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=ov[e.scope],u.some(e=>e.name.toLowerCase()===t&&ov[e.scope]>n));return(0,r.jsxs)(ae,{active:v===oN(e)&&!ei,onClick:()=>{y(oN(e)),j(oC(e)),S(oI(e.scope)?"edit":"view"),oI(e.scope)&&N(e.scope),z(null)},children:[(0,r.jsx)(aC,{active:e.enabled}),(0,r.jsx)(at,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},oN(e))})]},e)})}),(0,r.jsx)(aS,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),j({...oj,name:e,displayName:e}),S("create"),N("global"),z(null)},children:c("agents.new")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:Y||ei?(0,r.jsxs)(an,{children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:ei?(0,r.jsx)(ah,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:E})),path:eo,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[ea&&(0,r.jsx)(au,{scope:ea,children:c(`agents.scope.${ea}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:eo})]})}),(0,r.jsxs)(as,{children:[Y&&("view"===w||"edit"===w)&&(0,r.jsx)(aj,{size:"small",onClick:()=>{if(!Y)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}(Y.name,u);y(null),j({...oC(Y),name:e,displayName:c("agents.copyName",{name:Y.displayName})}),S("create"),N(oI(Y.scope)?Y.scope:"global"),z(null)},disabled:E||A,children:c("agents.duplicate")}),Y&&oI(Y.scope)&&"edit"===w&&(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:()=>void en(),disabled:E||A,children:c("agents.delete")}),(0,r.jsx)(aw,{checked:k.enabled,disabled:ef,label:k.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(oE,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:k.name,disabled:es,onChange:e=>ex("name",e.target.value),style:ow}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:k.name})}),(0,r.jsx)(oE,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:k.displayName,disabled:es,onChange:e=>ex("displayName",e.target.value),style:eg})})]}),(0,r.jsx)(oE,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:k.description,disabled:es,onChange:e=>ex("description",e.target.value),style:eg})}),(0,r.jsx)(oE,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:k.systemPrompt,disabled:es,onChange:e=>ex("systemPrompt",e.target.value),style:{...eg,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(oE,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:oy.map(e=>(0,r.jsx)(oT,{label:e,disabled:es,checked:k.tools.includes(e),onChange:t=>ex("tools",t?[...k.tools,e]:k.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(oE,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(oT,{label:c("agents.loadSkills"),disabled:es,checked:k.loadSkills,onChange:e=>ex("loadSkills",e)}),(0,r.jsx)(oT,{label:c("agents.loadExtensions"),disabled:es,checked:k.loadExtensions,onChange:e=>ex("loadExtensions",e)}),(0,r.jsx)(oT,{label:c("agents.mcp"),disabled:es||eb&&"on"!==k.mcp,checked:"on"===k.mcp,onChange:e=>ex("mcp",e?"on":"off")})]}),k.loadSkills&&void 0!==k.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:k.skills.length>0?c("agents.skillsOnly",{skills:k.skills.join(", ")}):c("agents.skillsNone")}),k.loadExtensions&&void 0!==k.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:k.extensions.length>0?c("agents.extensionsOnly",{extensions:k.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eb?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===k.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(oE,{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:k.codemode??"off",disabled:es,onChange:e=>ex("codemode",e.target.value),style:{...eg,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)(oE,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(rc,{options:X,value:em,onChange:(e,t)=>ex("model",`${e}/${t}`),onClear:()=>ex("model",void 0),emptyLabel:g?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:k.model&&!eu?c("agents.modelUnavailable",{model:k.model}):k.model!==ec?k.model:void 0,disabled:es||g||0===h.length&&!k.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(oE,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:k.thinking??"",disabled:es,onChange:e=>ex("thinking",e.target.value||void 0),style:eg,children:ok.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(oE,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:k.maxTurns??"",disabled:es,onChange:e=>ex("maxTurns",e.target.value?Number(e.target.value):void 0),style:eg})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(oT,{label:c("agents.inheritContext"),disabled:es,checked:k.inheritContext,onChange:e=>ex("inheritContext",e)}),(0,r.jsx)(oT,{label:c("agents.background"),disabled:es,checked:k.runInBackground,onChange:e=>ex("runInBackground",e)})]})]}):(0,r.jsx)(ab,{children:c("agents.empty")})})})]}),(0,r.jsx)(ay,{status:(q||P)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||P}),children:er&&(0,r.jsxs)(aj,{variant:"primary",onClick:()=>void et(),disabled:E||M||A||!k.name.trim(),className:M?"is-success":void 0,children:[M&&(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:M?c("i18n.saved"):E?c("agents.saving"):c("agents.save")})]})})]})}let oR=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function oA(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function oL(e){return`${e.scope}\0${e.source}`}function oP(e){return`extension\0${e.path}`}function oz(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function oO(e,t){return t(`plugins.status.${e}`)}function oW(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function oF(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function oD(e){let{pkg:t}=e,{t:n}=(0,eX.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 oB(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:a,actionError:o,onSourceChange:l,onScopeChange:d,onInstall:c}=e,{t:u}=(0,eX.s)();return(0,r.jsx)(ag,{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)(ah,{value:i,label:u("config.saveTo"),options:[{value:"global",label:oz("global",u)},{value:"project",label:oz("project",u),disabled:!s}],path:"project"===i?`${ep(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:!a&&!!n.trim(),normalizeValue:oA,onValueChange:l,onSubmit:c,examplesLabel:u("config.examples"),examples:oR,error:o,children:(0,r.jsx)(aj,{variant:"primary",onClick:c,disabled:a||!n.trim(),className:"is-pushed-right",children:u(a?"i18n.installing":"i18n.install")})})}function o_(e){let t,{pkg:n,cwd:s,busyKey:a,actionError:o,actionMessage:l,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:m,onReloadSession:g}=e,{t:f}=(0,eX.s)(),x=oL(n),b=(a?.endsWith(x)||a?.startsWith("bulk:"))??!1,v="reload"===a,y=!n.disabled,k=n.canCheckForUpdates,j=c?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(an,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ar,{className:"is-top-aligned",children:[(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:n.scope,children:oz(n.scope,f)}),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:f("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:f("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)(as,{children:[(0,r.jsx)(aj,{size:"small",variant:j?"primary":void 0,onClick:j||!k?()=>h("update",n):m,disabled:b||v||u,title:j?f("i18n.updateAvailable"):void 0,children:f(a===`update:${x}`?"i18n.updating":u?"i18n.checking":j||!k?"i18n.update":"i18n.check")}),(0,r.jsx)(aj,{size:"small",onClick:g,disabled:!d||v||b,"aria-describedby":d?void 0:S,children:f(v?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:b||v,children:f(a===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(aw,{checked:y,loading:b||v,onChange:()=>h(n.disabled?"enable":"disable",n),label:f(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:f("i18n.openSessionToReload")})]}),(0,r.jsxs)(ad,{children:[w&&(0,r.jsx)(ac,{label:f("i18n.description"),children:w}),(0,r.jsx)(ac,{label:f("i18n.status"),tone:"plain",style:{color:oF(n.status),textTransform:"capitalize"},children:oO(n.status,f)}),(0,r.jsxs)(ac,{label:f("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(f("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(f("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):f("i18n.unknown"))}),j&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:f("i18n.updateAvailable")}),k&&(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?f("i18n.checking"):c?.state==="up-to-date"?f("i18n.upToDate"):c?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):c?.message||f("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(ac,{label:f("i18n.package"),mono:!0,children:n.packageName??f("i18n.unknown")}),(0,r.jsx)(ac,{label:f("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,f)}),(0,r.jsx)(ac,{label:f("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?ep(n.installedPath):f("i18n.notFound")}),(0,r.jsx)(ac,{label:f("i18n.cwd"),tone:"dim",mono:!0,children:ep(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(ao,{children:f("i18n.resolvedResources")}),(0,r.jsx)(oD,{pkg:n})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:l}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function oH(e){let{extension:t}=e,{t:n}=(0,eX.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(an,{children:[(0,r.jsx)(ar,{children:(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:t.scope,children:oz(t.scope,n)}),(0,r.jsx)(aa,{children:t.name})]})}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:oO(i,n)}),(0,r.jsx)(ac,{label:n("i18n.installedPath"),mono:!0,children:ep(t.path)})]})]})}function oU(e){var t;let{cwd:n,sessionId:s,onClose:a,onReloaded:o,embedded:l=!1,trust:d}=e,{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!0),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(()=>sC("plugins",n)),[v,y]=(0,i.useState)(!1),[k,j]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)(null),[E,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[P,z]=(0,i.useState)(new Set),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,_]=(0,i.useState)(!1),H=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),q=H.find(e=>oL(e)===x)??null,K=U.find(e=>oP(e)===x)??null,Z=u?.projectResourcesLoaded??!0,V=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:H.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[H]),J=(0,i.useCallback)(async()=>{m(!0),f(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),b(e=>e&&(t.packages.some(t=>oL(t)===e)||t.standaloneExtensions.some(t=>oP(t)===e))?e:t.packages[0]?oL(t.packages[0]):t.standaloneExtensions[0]?oP(t.standaloneExtensions[0]):null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{m(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let G=ou(d),Y=(0,i.useRef)(G);(0,i.useEffect)(()=>{Y.current!==G&&(Y.current=G,J())},[G,J]),(0,i.useEffect)(()=>{x&&sN("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:H.filter(e=>e.canCheckForUpdates)).map(oL);if(0!==t.length){D(null),z(e=>new Set([...e,...t])),e||W(!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[oL(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{z(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||W(!1)}}},[n,H]),Q=(0,i.useCallback)(async()=>{_(!0),$(null),T(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({}),T(c("i18n.packagesUpdated")),s&&T(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){$(e instanceof Error?e.message:String(e))}finally{_(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=oL(t);N(`${e}:${r}`),$(null),T(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)b(s.packages[0]?oL(s.packages[0]):s.standaloneExtensions[0]?oP(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),T(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")};T(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t,r)=>{let i=oc(t,r,e=>!e.disabled,e=>e.filtered),a=r?0:t.filter(e=>!e.disabled&&e.filtered).length,o=a>0?c("plugins.bulkKeptFiltered",{count:a}):void 0;if($(null),T(null),R(o?{scope:e,note:o}:null),0===i.length)return;let l=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:l,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),a=await t.json();if(!t.ok||a.error||!a.results)throw Error(a.error??`HTTP ${t.status}`);let{results:d,...u}=a;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");T(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=oA(k).trim();if(!e)return;j(e);let t=`${w}\0${e}`;N(`install:${t}`),$(null),T(null),R(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),o=await a.json();if(!a.ok||o.error)throw Error(o.error??`HTTP ${a.status}`);p(o);let l=(r=o.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));b(l?oL(l):t),y(!1),j(""),T(c("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,k,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),$(null),T(null),R(null);try{await ic(s,{type:"reload"}),o?.(),await J(),T(c("i18n.sessionReloaded"))}catch(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,ea=H.some(e=>e.canCheckForUpdates),eo=h||null!==C||P.size>0||B;return(0,r.jsxs)(sQ,{embedded:l,title:c("common.plugins"),subtitle:ep(n),closeLabel:c("i18n.close"),onClose:a,children:[!Z&&(0,r.jsx)(ax,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):g?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:g}):0===H.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)(s5,{children:c("i18n.extensions")}),U.map(e=>{let t=oP(e);return(0,r.jsxs)(ae,{active:!v&&x===t,title:e.path,onClick:()=>{b(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aC,{active:e.enabled}),(0,r.jsx)(at,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),V.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)(s5,{aside:(0,r.jsx)(s9,{enabled:t,total:e.packages.length,disabled:eo,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:oz(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:oz(e.scope,c)}),M?.scope===e.scope&&(0,r.jsx)(s7,{error:M.error,note:M.note}),e.packages.map(e=>{let t=oL(e),n=!v&&x===t;return(0,r.jsxs)(ae,{active:n,title:e.description??e.source,onClick:()=>{b(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aC,{active:!e.disabled,color:oF(e.status)}),(0,r.jsx)(at,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[oL(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(aS,{active:v,onClick:()=>{y(!0),$(null),T(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:v?(0,r.jsx)(oB,{cwd:n,source:k,scope:w,projectResourcesLoaded:Z,busy:ei,actionError:I,onSourceChange:j,onScopeChange:S,onInstall:en}):h?null:K?(0,r.jsx)(oH,{extension:K}):q?(0,r.jsx)(o_,{pkg:q,cwd:n,busyKey:C,actionError:I,actionMessage:E,sessionId:s,updateStatus:A[oL(q)],checkingUpdate:P.has(oL(q)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(q),onReloadSession:er},oL(q)):(0,r.jsx)(ab,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(ay,{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)(ak,{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(oW)}):(0,r.jsx)(ak,{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:[!l&&(0,r.jsx)(aj,{onClick:a,children:c("i18n.close")}),ea&&(0,r.jsx)(aj,{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"):O?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(aj,{variant:"secondary",onClick:()=>void J(),disabled:eo,children:c("i18n.refresh")})]})]})}let oq="\\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",oK=RegExp(`[${oq}]`,"gu"),oZ=RegExp(`[${oq}]`,"u");function oV(e){return e.replace(oK,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let oJ=/[\s"'`$|&;<>()*?#~]/;function oG(e){let t=oZ.test(e),n=oV(e);return""===n||t||oJ.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function oY(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(oG).join(" ")}function oX(e){let t=void 0!==e.command?oY(e.command,e.args):void 0,n=void 0!==e.url?oV(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function oQ(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&oZ.test(e))}function o0(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:oV(e.name??"")}}}function o1(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function o2(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function o4(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function o8(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?oV(e.error):"link-outside"===e.reason?void 0===t?void 0:oV(t):void 0}let o6="codemode";function o3(e){return`${e.scope}\0${e.name}`}function o5(e){return e?.trust?.decision===!0}function o9(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function o7(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?o9(e.status):"on":"mcp-off":"not-trusted":"disabled"}let le={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"},lt={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function ln(e,t){return(t?.origin==="session"?lt[e]:void 0)??le[e]}let lr={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},li={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 ls(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 la(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function lo(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 ll={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"},ld={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"},lc={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},lu={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},lp=["codemode","deferred","direct","hidden"],lh={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function lm(e){return"auto-enable-codemode-invalid"!==e.reason}function lg(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 lf(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function lx(e,t){let n=e.flatMap(e=>e.servers.map(o3));return t===o6||null!==t&&n.includes(t)?t:n[0]??null}function lb(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function lv(e){return e.projectOverride?.preference??e.preference}let ly={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},lk={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},lj={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},lw={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function lS(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let lC=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function lN(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}:{},...lC(n.names)?{names:n.names}:{},...lC(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 lI(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},a=new AbortController,o=()=>a.abort();r?.aborted?a.abort():r?.addEventListener("abort",o,{once:!0});let l=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&a.abort()},n)});try{return await Promise.race([e(a.signal),l])}finally{clearTimeout(i),r?.removeEventListener("abort",o)}}function l$(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 lE(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&&l$(i)?{ok:!0,data:i}:{ok:!1,error:lN(i,r.status)}}let lT=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function lM(e,t,n){let r=await lE(e,t,n);if(r.ok||!e||!r.error.reason||!lT.has(r.error.reason))return r;let i=await lE(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function lR(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 lI(n=>lM(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function lA(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 a=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==a?{ok:!0,stored:a}:{ok:!1,error:lN(s,i.status)}}async function lL(e,t,n){let r=await lA({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 lP(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 lI(n=>lL(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function lz(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 lI(async n=>{let r=await lA({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 lO(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 lI(async n=>{let r=await lA({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 lW(e){return!e.available&&"builtin-disabled"!==e.reason}function lF(e,t){if(lW(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!o5(t.project))return"project-untrusted"}}let lD={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function lB(e){return!0!==e.notAnObject}function l_(e){return lB(e)&&void 0===e.webPasswordField}async function lH(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&&l$(i)?{ok:!0,data:i}:{ok:!1,error:lN(i,r.status)}}async function lU(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 lI(e=>lH(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let lq={"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 lK(e,t){let n=lF(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let lZ={"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"},lV={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},lJ={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},lG={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function lY(e){return(Math.max(0,e)/1e3).toFixed(1)}async function lX(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:lN(i,r.status)}}async function lQ(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 lI(e=>lX(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let l0="•••",l1=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),l2=new Set([...l1,"auth","sig","code","pw"]),l4=["token","secret","password","passwd","apikey"],l8=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),l6=new Set(["-k"]);function l3(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 l5(e,t){let n=l3(e);return!(n.length>1&&l8.has(n[n.length-1]))&&n.some(e=>t.has(e)||l4.some(t=>e.length>t.length&&e.endsWith(t)))}function l9(e){return l5(e,l1)}let l7=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,})"),de=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,dt=/^[A-Za-z0-9_\-+/=.~]+$/;function dn(e){return!(/\s/.test(e)||dl(e))&&(!!(l7.test(e)||de.test(e))||!(e.length<24||!dt.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 dr=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,di=RegExp(dr.source,"g"),ds=/^(?:bearer|basic|token)\s+/i;function da(e,t,n){let r=e.replace(ds,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function dl(e){return da(e.replace(/\$[$!]/g,"_x"),dr,di)}let dd=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,dc=RegExp(dd.source,"g");function du(e){return da(e,dd,dc)}function dp(e,t){if(!e||""===t)return;e.push(t);let n=dg(t);n!==t&&e.push(n)}let dh=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function dm(e,t,n){let r=!1,i=e,s="",a=dh.exec(e);if(a){let[o,l,d]=a,c=d.lastIndexOf("@");if(c>=0&&!t(dg(d.slice(0,c)))){s=`${l}${l0}${d.slice(c)}`,r=!0;let e=d.slice(0,c);dp(n,e);let t=e.indexOf(":");t>=0&&dp(n,e.slice(t+1))}else s=o;i=e.slice(o.length)}let o=i.search(/[?#]/),l=o<0?i:i.slice(0,o),d=o<0?"":i.slice(o),c=l.split("/").map(e=>dn(dg(e))?(r=!0,dp(n,e),l0):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let a=s.indexOf("=");if(a<0){let a=dg(s);return!dn(a)||t(a)?e:(r=!0,dp(n,s),`${i}${l0}`)}let o=s.slice(0,a),l=dg(s.slice(a+1));return""===l||t(l)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return l5(t,l2)}(o)&&!dn(l)?e:(r=!0,dp(n,s.slice(a+1)),`${i}${o}=${l0}`)}),{value:`${s}${c}${d}`,masked:r}}function dg(e){try{return decodeURIComponent(e)}catch{return e}}let df=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function dx(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&l9(r[1])){let[,i,s,a]=r;return t(a)?{value:e,masked:!1}:(dp(n,a.trim()),{value:`${i}:${s}${l0}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||df.test(e)))return;let i=!1;return{value:r.map(e=>{let r=df.exec(e);if(!r)return e;let[,s,a]=r;if(""===a.trim()||t(a))return e;if(l9(s.slice(0,-1).trim()))return i=!0,dp(n,a.trim()),`${s}${l0}`;let o=dx(a,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]&&l9(s[1]))return t(s[2])?{value:e,masked:!1}:(dp(n,s[2]),{value:`${s[1]}=${l0}`,masked:!0});if(/\s/.test(e)){var a,o,l;let r,i;return a=e,o=t,l=n,i=dy((r=a.split(/(\s+)/)).filter((e,t)=>t%2==0),o,!0,l),{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 dm(e,t,n);if(s&&""!==s[2]){let e=dx(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return dn(e)&&!t(e)?(dp(n,e),{value:l0,masked:!0}):{value:e,masked:!1}}function db(e){if(l6.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return l9(t)||"auth"===l3(t).at(-1)}let dv=/^(?:bearer|basic|token)$/i;function dy(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&dv.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,dp(r,e),l0)}let a=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(a){let[,e,n]=a;if(""!==n&&db(e)&&!t(n))return i=!0,dp(r,n),`${e}=${l0}`;let s=dx(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=db(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(dv.test(e)||t&&l9(t[1]))return s=!0,e}let o=dx(e,t,r);return i||=o.masked,o.value}),masked:i}}function dk(e){let{values:t,masked:n}=dy(e,du,!1);return{args:t,masked:n}}function dj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dw(e){return!e.startsWith("!")&&!dl(e)}function dS(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 dC={"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(dC);let dN={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},dI={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},d$={...dI,bareDollar:!0},dE={...dN,braceEnv:!0},dT=/^[A-Za-z_][A-Za-z0-9_]*$/,dM=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function dR(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function dA(e,t,n){let r=[],i=0;dM.lastIndex=0;for(let s=dM.exec(e);s;s=dM.exec(e)){let[a,o,l,d,c,u]=s,p=a;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(dT.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,a);else if(void 0!==l&&t.bareDollar)p={kind:"env",name:l,from:a};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:a};else if(void 0!==c&&t.braceEnv)p="env"===c&&dT.test(u)?{kind:"env",name:u,from:a}:{kind:"unsupported",from:a};else if(void 0!==d||void 0!==c){dR(r,e.slice(i,s.index+1)),i=s.index+1,dM.lastIndex=s.index+1;continue}dR(r,e.slice(i,s.index)),"string"==typeof p?dR(r,p):r.push(p),i=s.index+a.length}return dR(r,e.slice(i)),r}function dL(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 dP(e){return e.startsWith("!")}function dz(e){if(dP(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);dT.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 dO=/<[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,dW=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,dF=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,dD=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function dB(e){return e.join("\0")}function d_(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function dH(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function dU(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let dq=new Set(["HOME","USERPROFILE"]);class dK{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 dZ(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let dV=/\$\{[^{}]*\}/g,dJ=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class dG{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(dZ),this.urlText=dZ(e.url??[])}encode(e,t){let n,r=dH(e),i=d_(e),s=dZ(t),a=[],o=!1,l=()=>a.every(e=>""===e),d=e=>{if(!r)return void a.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=dL(e,{atStart:l()});n!==e&&(o=!0),a.push(n)},c=e=>a.push(e),u=e=>a.push({field:e});if(!r&&dU(e)&&1===t.length&&"text"in t[0]&&dF.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(dF.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,a,void 0)}let p=0;return t.forEach((a,o)=>{let h=t[o+1],m=void 0===h||"text"in h&&/^[\\/]/.test(h.text),g=(t,r,i)=>{let a=0;for(let[d,c]of function(e){let t=e.trim();if(dW.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=dD.exec(t);if(n&&dW.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];dO.lastIndex=0;for(let t=dO.exec(e);t;t=dO.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,l;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>a&&r(t.slice(a,d)),"url"===e[0]&&dY(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(o=e,l=h,"env"===o[0]||"headers"===o[0]?o[1]:l.replace(/^[<{\s]+|[>}\s]+$/g,"")||d_(o)),h)),a=c}a<t.length&&r(t.slice(a))};switch(a.kind){case"text":g(a.text,d,[]);break;case"pi":{var f;let e=h?(f=a.text,(/\$+$/.exec(f)?.[0].length??0)%2==1?`${f}$`:f):a.text;if(r&&l()&&dP(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(dV)].map(e=>[e.index,e.index+e[0].length]);g(e,c,t);break}case"env":r?(c(`$\{${a.name}}`),void 0!==a.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:a.name,fallback:a.fallback}),a.shell?this.draft.note("shell-variable",{field:i,name:a.name}):a.from!==`$\{${a.name}}`&&this.draft.note("variable-translated",{field:i,from:a.from,to:`$\{${a.name}}`})):dU(e)&&l()&&dq.has(a.name)&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):(u(this.field(e,"variable",a.name,a.from,void 0,a.fallback)),this.draft.note(a.shell?"shell-variable":"variable-unsupported-here",{field:i,name:a.name}));break;case"input":u(this.inputField(e,a));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:a.from,to:"${HOME}"})):dU(e)&&l()&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):u(this.field(e,"home","userHome",a.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",a.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:a.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",a.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",a.from,a.from)),this.draft.note("unsupported-variable",{field:i,variable:a.from});break;case"prompt":"url"===e[0]&&dY(s,p)&&(n="uri-component"),u(this.promptField(e,a))}p+=("text"in a?a.text:a.from).length}),o&&this.draft.note("escaped-value",{field:i}),this.target(e,a,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=>dB(t.path)===dB(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 a=dJ.has(t)?`${t}.${n}`:d_(e);if(dJ.has(t)){if(this.fields.has(a))return a}else for(let t=2;this.fields.has(a);t++)a=`${d_(e)}#${t}`;let o=this.isSecretContext(e,r)||l9(n),l="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(a,{id:a,kind:i??(o?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&l?{optional:!0}:{},targets:[]}),a}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 l9(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(dk([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&dk([t,"x"]).args[1]===l0}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,dm(`https://host.invalid/?${n}=x`,du).masked)}default:return!1}}}function dY(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 dX(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 dQ=/^[A-Za-z0-9_-]+$/;function d0(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 d1=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function d2(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=d8(t);return s&&!d1.has(s.toLowerCase())?s:d8(r)||r||s||t}let d4=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function d8(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,d4)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let d6=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function d3(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=>!d6.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let d5=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 d9(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 d7(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(!d1.has(n.toLowerCase())&&"."!==n&&".."!==n)return d8(n.replace(/_/g,"-"))||n}return""}function ce(e,t){ct(e,t)&&cn(e,Math.ceil(t/1e3),t)}function ct(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function cn(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 cr=["codemode","deferred","direct","hidden"],ci={"codemode-deferred":"codemode"},cs=["localhost","127.0.0.1","[::1]"];function ca(e){return"string"==typeof e&&cr.includes(e)?e:"string"==typeof e&&Object.hasOwn(ci,e)?ci[e]:void 0}function co(e){try{return new URL(e)}catch{return}}function cl(e){let t=co(e);return void 0!==t&&"http:"===t.protocol&&cs.includes(t.hostname)&&""===t.search&&""===t.hash}function cd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cc(e){return cd(e)&&Object.values(e).every(e=>"string"==typeof e)}function cu(e,t){if(!dQ.test(e))return{problem:"name",name:e};if(!cd(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:a,description:o}=t;if(void 0!==r&&!ca(r))return{problem:"exposure",value:String(r)};if(void 0!==a){if(!cd(a))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(a))if(!ca(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=co(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!cc(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!cd(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||!cl(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&&"auto"!==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?co(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)?co(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&cs.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(!cd(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!cs.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||cc(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let cp=/[A-Za-z_]/,ch=/[A-Za-z0-9_]/,cm=/^[A-Za-z_][A-Za-z0-9_]*$/,cg=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),cf=new Set([..."|&;<>()"]),cx=/[0-9@*#?$!-]/,cb={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function cv(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 cy(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class ck{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 cj)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new cj(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=cy(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)&&cv(e,this.index)>0)this.index+=cv(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:"`"}):cf.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||!cg.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=cy(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 cb?(t+=cb[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&&cp.test(n)){let n=this.index+1;for(;n<t.length&&ch.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&&cx.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}),cm.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 cj extends Error{constructor(e){super(e.code),this.detail=e}}function cw(e){return new ck(e).run()}function cS(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function cC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cN=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function cI(e){if(cN.some(t=>t in e))return!0;let t=e.oauth;return cC(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function c$(e){if(!cC(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]||cC(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function cE(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 cT(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 cM(e,t){let n=t?cT(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function cR(e){return e?{server:e}:{}}function cA(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function cL(e,t,n){let r;if(!cC(t))return{note:{code:"no-command-or-url",params:cR(e)}};let i=new Set,s=e=>(i.add(e),t[e]),a=n.rawPi,o=function(e,t){switch(e.flavor){case"zed":return dN;case"opencode":return dE;case"vscode":return dI;default:return cI(t)?d$:dI}}(n,t),l=s("name"),d=e??("string"==typeof l?l:void 0),c=new dK(n.source,a),u=(e,t)=>{if(a)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),dA(e,o,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...cO(p)]));let h=s("type"),m=s("command"),g=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:cR(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?cE(h):"unknown"))return{note:{code:"unsupported-transport",params:{...cR(d),type:String(h)}}};let f="string"==typeof m&&""!==m||Array.isArray(m)||cC(m),x=void 0!==g;if("sse"===r)return{note:cM(d,g)};if("ws"===r)return{note:{code:"websocket-transport",params:{...cR(d),...g?{url:g}:{}}}};if(void 0===r){if(f&&x)return{note:{code:"ambiguous-command-and-url",params:cR(d)}};if(x){if(void 0!==cT(g))return{note:cM(d,g)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!f)return{note:{code:"no-command-or-url",params:cR(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...cR(d),type:String(h)}}};if("stdio"===r&&!f||"http"===r&&!x)return{note:{code:"no-command-or-url",params:cR(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let a,o=r("args"),l=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===l&&(l=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...cR(e.name),problem:"args"}};a=n[0],o=[...n.slice(1),...Array.isArray(o)?o:[]]}else if(cC(n))for(let t of(a="string"==typeof n.path?n.path:void 0,void 0===o&&(o=n.args),void 0===l&&(l=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(a=n);if(!a)return{code:"no-command-or-url",params:cR(e.name)};let d=Array.isArray(o)?[...o]:[];if(void 0!==o&&!Array.isArray(o))return{code:"invalid-config",params:{...cR(e.name),problem:"args"}};if(0===d.length&&/\s/.test(a.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(a.trim())){let t=cw(a.trim()),n=t.ok?t.words.map(cS):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:a}),a=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(a,!1),d.entries())){let r=cA(n);if(void 0===r)return{code:"invalid-config",params:{...cR(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==l){if(!cC(l))return{code:"invalid-config",params:{...cR(e.name),problem:"env"}};for(let[t,n]of Object.entries(l)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=cA(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&&l9(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,m,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),a=i(n,!1),o=cC(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===a.length&&"text"in a[0]?dX(e,n,o):e.url=a,cC(s))for(let[t,n]of Object.entries(s)){let r=cA(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):l9(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 l=r("oauth"),d=r("auth");if(!1===l?e.note("oauth-disable-unsupported"):cC(l)?cP(e,l,i):void 0!==l&&e.note("dropped-key",{key:"oauth"}),cC(d))for(let t of(cP(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,g,s,u);let b=s("timeout");if(void 0!==b)if(a)"number"==typeof b&&b>0?c.timeout=b:c.note("timeout-dropped",{value:String(b)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(b)});else if(cI(t))ce(c,b);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?ct(c,b)&&cn(c,Math.ceil(b),void 0):!function(e,t){if(!ct(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?cn(e,Math.ceil(t/1e3),t):cn(e,Math.ceil(t),void 0)}(c,b);let v=s("enabled"),y=s("disabled");!1===v||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==v&&"boolean"!=typeof v||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==v?"enabled":"disabled"});let k=s("exposure");if(void 0!==k){let e=ca(k);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(k)})}let j=s("toolExposure");if(void 0!==j){let e=cC(j)?Object.entries(j).map(e=>{let[t,n]=e;return[t,ca(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(a||void 0===k&&void 0===j||c.note("looks-like-pi-config"),a){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(cz(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function cP(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":"auto"===s||"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&&cl(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 cz(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 a={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))a[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)a[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=a}function cO(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)cC(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=>cC(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function cW(e,t,n,r){let i=[],s=0;for(let a of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){a.index>s&&i.push({kind:"text",text:e.slice(s,a.index)});let o=cC(t)&&cC(t[a[1]])?t[a[1]]:{};i.push(cF(`${n}${a[1]}`,a[1],a[0],o,r)),s=a.index+a[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function cF(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 cD(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...dA(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 cB(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 a=i.value.slice(s+t.length);return[n,[...a?[{...i,value:a}]:[],...e.slice(r+1)]]}}let c_=/^https?:\/\//i,cH=/^wss?:\/\//i,cU={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},cq=new Set(["pi","claude","codex","gemini"]),cK=new Set(["install","remove","uninstall","update","list","config"]);function cZ(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let cV={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","oauth-client-registration":"value",exposure:"value",description:"value"},cJ=new Map([["-l","--local"]]),cG=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name","oauth-client-registration"],cY=["env","cwd"];function cX(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 a=t[s],o=a.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(a);continue}let l=o.startsWith("--")?o.indexOf("="):-1,d=l>0?o.slice(0,l):o,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(a),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=l>0?cQ(a,l+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 cQ(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 c0=/^[A-Za-z_][A-Za-z0-9_]*=/,c1=/^[^\s:]+:/;function c2(e,t,n,r){for(let i of t??[]){let t=cB(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],cD(t[1],n,!0)])}}function c4(e,t,n,r){for(let i of t??[]){let t=cB(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let a=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()&&a.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,cD(a,n,!0)])}}function c8(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function c6(e,t,n,r,i){let s,[a,o,...l]=r;if(!a||!o)return{code:"cli-usage",params:{cli:t}};e.name=a.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=c_.test(o.text)?"http":cH.test(o.text)?"ws":"stdio")&&void 0!==cT(o.text))return cM(a.text,o.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?cM(a.text,o.text):"ws"===s?{code:"websocket-transport",params:{server:a.text,url:o.text}}:"http"===s?(e.transport="http",e.url=cD(o.parts,i,!1),l.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:l.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:a.text,type:s}}:(e.transport="stdio",e.command=cD(o.parts,i,!1),e.args=l.map(e=>cD(e.parts,i,!1)),"stdio")}let c3={"-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 c5(e,t){return"env"===e?c0.test(t.text):c1.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function c9(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let c7={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function ue(e){let t,n=cS(e)??e.text;try{t=dS(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return cC(t)?{value:t}:{error:{code:"no-servers-found"}}}let ut={"--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"}},un={"-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 ur(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(ui(r),ui(i))}return t}function ui(e){try{return decodeURIComponent(e)}catch{return e}}function us(e){let t=e.trim();for(let e=0;e<4;e++)try{return dS(t)}catch{let e=ui(t);if(e===t)break;t=e.trim()}}function ua(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function uo(e){let t=e.get("config");if(!t)return ua("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:us(n);return cC(r)?{entries:[cL(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:ua("config")}function ul(e,t,n,r){return cC(e)?{entries:[cL(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:cO(r)})],notes:[]}:ua("config")}function ud(e){return{error:{code:"by-name-link",params:{name:e}}}}function uc(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function uu(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[uh(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return ua("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return uo(ur(t.search));return ua("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 ud(ui(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return ud(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return ul(us(uc(r)),"vscode-install-link");return ua(i)}case"vsweb+mcp":return ul(us(uc(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return ul(us(uc(r)),"copilot-app-install-link");return ua(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 uo(ur(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=ur(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return uu(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?ul(us(e),"vscode-install-link",t.get("name")||void 0,us(t.get("inputs")??"[]")):ua("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return ul(us(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=ur(e.search).get("open");return t?uu(t,n+1):ua("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:[uh(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let up=new Set(["localhost","127.0.0.1","[::1]"]);function uh(e,t){let n=d3(t)||void 0;if(void 0!==cT(t))return{note:cM(n,t)};let r=new dK("url",!1);return r.transport="http",dX(r,t,!1),e?.protocol!=="http:"||up.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let um=/[\u200B-\u200D\u2060\uFEFF]/g,ug=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,uf={"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 ux(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>dB(e.path))))}function ub(e){var t;let n,r,i,s,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(n=e.replace(um,"").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=dS(e)}catch(t){try{n=dS(`{${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 cL(n,r,t)});if(Array.isArray(e)){let r=e.filter(c$);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>cL(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!cC(e))return{error:{code:"no-servers-found"}};let i=cC(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?d2(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(cC):[],i=r.filter(e=>"string"==typeof e.type&&"http"===cE(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:cM(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:cR(n)}}]}return i.map(e=>{let r=new dK("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=cW(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(cC):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,cW(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[cF(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(cC(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(cC(e.servers)){let t=cO(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(cC(e.mcp)){let t=e.mcp;if(cC(t.servers)){let e=cO(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(cC(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return cC(r)&&("extension"===r.source||!c$(r))?{note:{code:"zed-extension-server",params:{server:n}}}:cL(n,cC(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(c$(e))return{entries:[cL(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(cC)&&s.some(c$)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(o,!0===a.rawPi);else if(ug.test(o)){if(!("error"in(s=uu(`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)?uu(o):(e=cw(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&&cU[i]&&e[t+1]?.text==="mcp"&&(n=t,r=cU[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 cZ(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=cJ.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 a=s.slice(2),o=cV[a];if(!o)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===o){r.set(a,!0);continue}let l=e[++t];if(void 0===l)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===o?i.set(a,[...i.get(a)??[],l]):r.set(a,l)}let[s,...a]=n,o=r.get("url");if(!s||""===s.text||void 0===o==(0===a.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let l=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===o?cG:cY).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 dK("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=cB(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=cD(o.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,cD(n,"pi",!0)]);let t=l("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=l("oauth-client-id"),r=l("oauth-client-secret"),i=l("oauth-callback-port"),s=l("oauth-client-name"),a=l("oauth-client-registration");n&&(c.oauth.clientId=cD(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=cD(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=cD(s.parts,"pi",!1)),a&&(c.oauth.clientRegistration=a.text),p.url=o.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":o.text,(i||s||a)&&(p.oauth={...n?{clientId:n.text}:{},...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{},...a?{clientRegistration:a.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,cD(n,"pi",!0)]);let[t,...n]=a;c.command=cD(t.parts,"pi",!1),c.args=n.map(e=>cD(e.parts,"pi",!1));let r=l("cwd");r&&(c.cwd=cD(r.parts,"pi",!1)),p.command=t.text}let h=l("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=ca(h.text)??h.text);let m=l("description");void 0!==m&&(p.description=m.text,c.description=m.text);let g=cu("server",p);return g?{note:{code:"invalid-config",params:{server:s.text,...g}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return cZ(function(e){let t=cX("claude",e,c3,{asArgAfter:2,variadic:c5});if("error"in t)return{error:t.error};let n=new dK("claude-mcp-add",!1),r=c6(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],dI);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=c8(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=c4(n,t.lists.get("header"),dI,"claude");if(r)return{error:r};let a=t.values.get("client-id");a&&!0!==a&&(n.oauth.clientId=cD(a.parts,dI,!1)),t.values.has("client-secret")&&c9(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=c2(n,t.lists.get("env"),dI,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return cZ(function(e){let t=cX("claude",e,c7,{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=ue(r);if("error"in s)return s;let a=cL(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in a||(a.draft.scopeHint=c8(t.values.get("scope")),t.values.has("client-secret")&&"http"===a.draft.transport&&!a.draft.oauth.clientSecret&&c9(a.draft)),a}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return cZ(function(e){let t=cX("codex",e,ut,{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,a=n.length>0?n:s,o=t.values.get("url");if(!i||void 0===o==(0===a.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let l=new dK("codex-mcp-add",!1);for(let e of(l.name=i.text,["config","enable","disable"]))t.values.has(e)&&l.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&l.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!==cT(o.text))return{note:cM(i.text,o.text)};l.transport="http",l.url=cD(o.parts,dN,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&l.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&&(l.oauth.clientId=cD(n.parts,dN,!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"}}};l.transport="stdio";let e=c2(l,r,dN,"codex");if(e)return{error:e};l.command=cD(a[0].parts,dN,!1),l.args=a.slice(1).map(e=>cD(e.parts,dN,!1))}return{draft:l}}(t));if("gemini"===r&&"add"===e)return cZ(function(e){let t=cX("gemini",e,un,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new dK("gemini-mcp-add",!1),r=c6(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],d$);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=c8(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=c4(n,t.lists.get("header"),d$,"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=c2(n,t.lists.get("env"),d$,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&ce(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 cz(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(cq.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]&&cK.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=cQ(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=ue(r);if("error"in s)return s;t.push(cL(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):cZ(function(e){let t=new dK("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,cD(r.value,dN,!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=cD(i.parts,dN,!1),t.args=e.slice(n+1).map(e=>cD(e.parts,dN,!1));let s=e.slice(n+1).map(e=>e.text),a=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>c_.test(e)):void 0;return a&&t.note("mcp-remote-bridge",{url:a}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:uf[t],params:n}:{code:uf[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let l=[...s.notes],d=[],c=[...a.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){l.push(e.note);continue}let n=function(e){let t,n=new dG(e);if("stdio"===e.transport&&e.command&&""!==dZ(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||""===dZ(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:a,clientSecret:o,callbackPort:l,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;a&&(s.clientId=n.encode(["oauth","clientId"],a)),o&&(s.clientSecret=n.encode(["oauth","clientSecret"],o)),void 0!==l&&(s.callbackPort=l),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){l.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return d3(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&&d3(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=d9(t,new Set(["-p","--package","-c","--call"]));return e?d2(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?d9(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?d2(n):""}case"uvx":case"pipx":{let e=d9("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?d2(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?d9(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?d7(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?d9(t.slice(e+1),d5):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return d8(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return d2(t[e+1].replace(/_/g,"-"));let n=d9(t,new Set(["-X","-W"]));return n?d7(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=d9("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?d7(e):""}default:return d8(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let a=(t=i,dQ.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";a!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:a}}));let o=d0(a,s?[...c,...u]:u);o!==a&&(r.notes.push({code:"name-deduplicated",params:{original:a,name:o}}),a=o),!s&&c.includes(a)&&r.notes.push({code:"name-taken",params:{name:a,suggestedName:d0(a,[...c,...u])}}),r.name=a;let p=cu(a,function(e){let t=ux(e),n=JSON.parse(JSON.stringify(e.config));t.has(dB(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(dB(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){l.push({code:"invalid-config",params:{server:a,...p}});continue}!function(e){let t=ux(e);for(let n of uN(e.config))t.has(dB(n))||e.notes.push({code:"literal-secret",params:{field:d_(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=dz(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=dz(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(a),d.push(r)}return 0===d.length?{ok:!1,notes:l.length>0?l:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:l}}let uv=/^[A-Za-z_][A-Za-z0-9_]*$/;function uy(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 uk(e){let t=ux(e);return uN(e.config).filter(e=>dH(e)&&!t.has(dB(e)))}function uj(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let uw=/^(?:bearer|basic|token)\s+/i;function uS(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],a=new Map(uk(e).map(e=>[d_(e),e])),o=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=a.get(e);r?uv.test(n)?o.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:uj(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():"";uv.test(r)?"select"!==n.kind&&n.targets.every(e=>dH(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:uj(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 l=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&&l.add(d_(e.path));let s=dB(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){uy(r,e.path,void 0);continue}let a="";for(let t of e.parts){var c,u,p,h;a+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===a,h=e.encoding,"reference"in c?`$\{${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):dH(u)?dL(c.text,{atStart:p}):c.text)}uy(r,e.path,a)}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(uw)?.[0]??"":"";uy(r,e,`${i}$\{${t}}`)}for(let e of uN(r))l.add(d_(e));return{ok:!0,config:r,secretPaths:[...l]}}let uC=["command","args","env","cwd","url","headers","oauth"];function uN(e){let t=[];for(let n of function(e){if(!dj(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(dj(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dw(i)&&""!==i&&(l9(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||dx(i,dl).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=dj(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dw(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&dm(e.url,du).masked&&t.push({kind:"url"}),"string"==typeof e.command&&dx(e.command,du).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&dk(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:""):[];dk(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>uC.indexOf(e[0])-uC.indexOf(t[0]))}let uI="PI_WEB_PASSWORD";function u$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uE(e){return u$(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function uT(e){if(!u$(e))return[];if(!("url"in e))return uE(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=uE(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=u$(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let uM={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function uR(e,t,n){let r=ub(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,a="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,a])}function uA(e,t){let n={...e,...t},r=uR(e.text,e.rawPi,e.server);if(void 0!==r&&r===uR(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function uL(e){return dC[e.code]??"warning"}function uP(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?oV(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=oV(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 a=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:a}):a}let uz={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"},uO={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"},uW=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),uF=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),uD=[{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 '${uF}'`},{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(uW)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(uF)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(uF)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(uF)}`}];function uB(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?oV(r):r.field===e.id?n:`‹${oV(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function u_(e){return"select"!==e.kind&&e.targets.every(e=>dH(e.path)&&void 0===e.encoding)}let uH=/^[A-Za-z_][A-Za-z0-9_]*$/;function uU(){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 uH.test(r)?r:void 0}let uq=/^(?:proxy-)?authorization$/i;function uK(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return uH.test(t)?t:uU(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return uU(t,...n)??uU(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(uq.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===uI?void 0:n}function uZ(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function uV(e,t){let n=e;for(let e of t)n=n.split(e).join(l0);return{text:n,masked:n!==e}}function uJ(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function uG(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(lm);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function uY(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function uX(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 uQ(e,t,n){switch(e.kind){case"trust-too-broad":return t(u1[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(u0[e.kind])}}let u0={"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"},u1={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 u2(e){return oV(ep(e))}function u4(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let u8=[{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"}],u6=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function u3(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eX.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},a=[...t].sort((e,t)=>s[uL(e)]-s[uL(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:a.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${uL(e)}`,children:uP(e,i,n)},`${t}\0${e.code}`))})}let u5={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function u9(e){let{data:t,cwd:n,draft:s,busy:a,controlsBusy:o,failure:l,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,eX.s)(),h=(0,i.useId)(),m=(0,i.useId)(),g=(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:lb(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),a=e=>ub(t.text,{rawPi:t.rawPi,takenNames:uY(n,e)}),o=a(t.scope??"global"),l=o.ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0,d=t.scope??(l?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(l=(o=a(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=lW(n.mcp);if(!l)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??l.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&u_(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(l,t),m=uk(l).map(d_),g=Object.fromEntries(m.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),f=uS(l,h,g),x={};if(!f.ok)for(let e of f.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let b=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]=uH.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=uS(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,uH.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(l,h,g),v=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,a={source:e.source,commandFields:uT(r).filter(e=>{let{value:t}=e;return dP(t)}).map(uJ),variableReferences:uT(r).map(e=>({...uJ(e),variables:dz(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=uV(r.url,i);return{...a,transport:"http",target:oV(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let o=uV(oY(r.command,r.args??[]),i);return{...a,transport:"stdio",target:o.text,...void 0!==r.cwd?{cwd:oV(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:o.masked}}(l,h,f),y=f.ok?cu(p,f.config):void 0,k="blocked"===s.kind?s.block:b.length>0?{kind:"secret",fields:b,fixed:!b.every(uZ)}:uG("project",n),j=uY(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(dQ.test(p))if(j.includes(p))i={kind:"name-taken",name:p,suggestedName:d0(p,j),...w?{path:w.path}:{}};else if(f.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:v.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of uT(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(uI):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===uI))return r}(f.config,{isCommandConfigValue:dP,getConfigValueEnvVarNames:dz}))i={kind:"web-password"};else if("project"===d&&k)i={kind:"scope",block:k};else{let e=uG(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return l.fields.find(e=>e.id===t)?.label??t},t=f.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(f.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&k?e({...t,scope:"global"},n,r):{parsed:o,server:l,name:p,scope:d,projectMode:s,...k?{projectBlock:k}:{},values:h,pasteSecrets:m,secretReferences:g,fill:f,fieldProblems:x,secretPaths:b,preview:v,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),f=(0,i.useMemo)(()=>(function(e){let t=ub(e,{rawPi:!0});if(!t.ok)return!1;let n=ub(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:b,preview:v,projectBlock:y,submitBlock:k}=g,j=b?[...b.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!g.pasteSecrets.includes(String(e.params?.field))):[],w=void 0!==s.name&&s.name!==b?.name?[]:j.filter(e=>u6.has(e.code)),S=j.filter(e=>!u6.has(e.code)),C=!a&&!o&&void 0===k,N=()=>{C&&c(uX(s,g))},I=e=>d({...s,...e}),$=t.files.find(e=>e.scope===g.scope)?.path??("project"===g.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),E=k&&(""!==s.text.trim()||"mcp-off"===k.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:oV(e.name),path:e.path?u2(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(oV).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(oV).join(", ")});case"config-invalid":return uP(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return uQ(e.block,t,u2)}}(k,p,b?.fields):void 0,T=y?.kind==="project-untrusted"&&y.trustable&&u,M=v?"http"===v.transport?v.headerNames:v.envNames:[];return(0,r.jsxs)(ag,{title:p("mcp.add.title"),catalogs:u8,target:(0,r.jsxs)(ah,{value:g.scope,label:p("config.saveTo"),options:[{value:"global",label:u4("global",p)},{value:"project",label:u4("project",p),disabled:void 0!==y&&"project"!==g.scope}],path:u2($),disabledReason:y?uQ(y,p,u2):null,onChange:e=>I({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),g.trustFolder&&"trust-and-write"===g.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:u2(g.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(uA(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?uD.map(e=>{let{source:t,text:n}=e;return{label:p(uO[t]),value:n}}):[],multiline:!0,children:[f&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(uA(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)(u3,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(al,{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(b??x.servers[0])),onChange:e=>I({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:oV(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})})]}),b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(al,{label:p("config.name"),children:(0,r.jsx)("input",{id:m,className:"mcp-add-input","aria-label":p("config.name"),value:g.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>I({name:e.target.value})})}),(0,r.jsx)(u3,{notes:w,fields:b.fields}),k?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{size:"small",onClick:()=>I({name:k.suggestedName}),children:p("mcp.add.useName",{name:oV(k.suggestedName)})})})]}),b&&v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ao,{children:p("mcp.add.preview")}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:p("mcp.add.readAs"),children:p(uO[v.source])}),(0,r.jsx)(ac,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${v.transport}`)}),(0,r.jsx)(ac,{label:"http"===v.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:v.target}),"stdio"===v.transport&&void 0!==v.cwd&&(0,r.jsx)(ac,{label:p("mcp.detail.cwd"),mono:!0,children:v.cwd}),M.length>0&&(0,r.jsx)(ac,{label:"http"===v.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(u7,{names:M})}),v.commandFields.length>0&&(0,r.jsx)(ac,{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:v.commandFields.map(e=>{let t=o0(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),v.variableReferences.length>0&&(0,r.jsx)(ac,{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"===v.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:o4(v.variableReferences).map(e=>{let{variable:t,field:n}=e,i=o0(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:oV(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[v.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),v.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(u3,{notes:S,fields:b.fields}),b.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ao,{children:p("mcp.add.fields")}),b.fields.map(e=>{var t;let n;return(0,r.jsx)(pe,{field:e,fields:b.fields,draft:s,suggestedName:(t=g.name,(n=e.targets[0])?uK(d_(n.path),t):void 0),problem:g.fieldProblems[e.id],onDraftChange:d},e.id)})]}),g.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ao,{children:p("mcp.add.secrets")}),g.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(pt,{label:e,draft:s,suggestedName:uK(e,g.name),stored:g.fill?.ok?(t=g.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(8)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice(4)]:void 0)&&dl(i)?i:void 0):void 0,problem:g.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(aj,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":a||void 0,"aria-describedby":E?h:void 0,onClick:N,children:a?p("mcp.add.adding"):g.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),E&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${k?.kind==="scope"?"is-warning":"is-dim"}`,children:E}),b&&!k&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),l&&(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(u1[e.breadth.kind],{path:u2(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(uZ)?"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:oV(e.name),path:e.path?u2(e.path):"mcp.json"});let n=e.reason?u5[e.reason]:void 0;return n?t(n,{error:oV(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):oV(e.error)}(l,p)]}),l.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:u2(l.trust?.decisionPath??n??"")})}),l.notes&&l.notes.length>0&&(0,r.jsx)(u3,{notes:l.notes,fields:b?.fields}),"name-taken"===l.reason&&l.suggestedName&&k?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{size:"small",onClick:()=>I({name:l.suggestedName}),children:p("mcp.add.useName",{name:oV(l.suggestedName)})})}),"host-env-confirm"===l.reason&&l.names&&l.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:l.names.map(oV).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{variant:"danger",size:"small",disabled:a||o||void 0!==k,onClick:()=>c(uX(s,g,l.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function u7(e){let{names:t}=e,{t:n}=(0,eX.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:oV(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function pe(e){let t,{field:n,fields:s,draft:a,suggestedName:o,problem:l,onDraftChange:d}=e,{t:c}=(0,eX.s)(),u=(0,i.useId)(),p=l?{"aria-invalid":!0,"aria-describedby":u}:{},h=u_(n),m=h?a.references[n.id]:void 0,g=void 0!==m,f=oV(n.label),x=a.values[n.id]??n.defaultValue??"",b=uz[n.reason],v=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=g?m&&!l?uB(n,s,"${"+m+"}",!0):void 0:uB(n,s,`‹${c("mcp.add.field.slot")}›`),k=e=>d({...a,values:{...a.values,[n.id]:e}}),j=e=>{let t={...a.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...a,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(al,{label:f,children:g?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:f}),value:m,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":f,value:x,...p,onChange:e=>k(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:oV(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":f,value:x,autoComplete:"off",placeholder:n.placeholder?oV(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)})}),l&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:uP(l,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:oV(n.description)}),b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(b)}),g?(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:v?c("mcp.add.field.optionalHeader",{name:oV(v)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:g,onChange:e=>j(e.target.checked?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function pt(e){let{label:t,draft:n,suggestedName:s,stored:a,problem:o,onDraftChange:l}=e,{t:d}=(0,eX.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=oV(t),m=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,l({...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=>m(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(al,{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=>m(e.target.value)})}),o&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:uP(o,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==a?d("mcp.add.secret.storedAs",{value:oV(a)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let pn=new Set(["done","failed","cancelled","expired"]);function pr(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!pn.has(t))}let pi={"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"},ps={"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"},pa={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},po={"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 pl(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,pn.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function pd(e){return"sign-in-unknown"===e.reason}async function pc(e,t,n,r){var i;let s,a;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{a=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=a)&&"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:a}:{ok:!1,error:lN(a,s.status)}}function pu(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=t.method??"GET";return lI(r=>pc(e,t,n,r),()=>({ok:!1,error:{error:`${a} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function pp(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function ph(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?ps[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pm(e){let{server:t,run:n,block:s,signOutBlock:a,controlsBusy:o,signingOut:l,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,eX.s)(),m=(0,i.useId)(),g=(0,i.useId)(),f=(0,i.useId)(),x=(0,i.useRef)(null),b=(0,i.useRef)(null),v=pr(n),y=(0,i.useRef)(v);if((0,i.useEffect)(()=>{let e=y.current;y.current=v,!e&&v?e$(document,b.current):e&&!v&&e$(document,x.current)},[v]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(ac,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:oV(t.authProvider)}):h("mcp.signIn.header")});let k=n?.flow,j=n?.starting===!0,w=void 0!==k&&(k.scope!==t.scope||k.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=j||l||void 0!==s,N=o||j||void 0!==a,I=k?.phase==="finishing";return(0,r.jsx)(ac,{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")}),k&&v&&w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:oV(k.name)})}),k&&v&&("authorize"===k.phase?(0,r.jsx)(pg,{flow:k,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,k.flowId,e)},k.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(pa[k.phase]??"mcp.signIn.phase.connecting")})),k&&v&&I&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),k&&!v&&!n?.gone&&(0,r.jsx)(pf,{flow:k,shared:w}),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")," ",ph(n.error,h)]}),v&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",ph(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")," ",ph(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:m,className:"mcp-config-line is-dim",children:h(pi[s])}),!s&&a&&S&&!v&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h(pi[a])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[v&&k?(0,r.jsx)(aj,{ref:b,size:"small",disabled:n?.cancelling===!0||I,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":I?f:void 0,onClick:()=>p(t,k.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(aj,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":j||void 0,"aria-describedby":s?m:void 0,onClick:()=>d(t),children:h(j?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!v&&(0,r.jsx)(aj,{size:"small",disabled:N,"aria-busy":l||void 0,"aria-describedby":a?s?m:g:void 0,onClick:()=>c(t),children:h(l?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!v&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!a&&!v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function pg(e){let{flow:t,pasting:n,pasteError:s,onPaste:a}=e,{t:o}=(0,eX.s)(),[l,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&&e$(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)(aO,{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:oV(p)})]}):(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oV(t.authorizationUrl??"")})]}),value:l,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:()=>a(l)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.signIn.paste.refused")," ",ph(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:oV(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.redirect",{url:oV(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.wait")})]})}function pf(e){let{flow:t,shared:n}=e,{t:i}=(0,eX.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 po[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let a=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"===a?"mcp-config-line is-error":"warning"===a?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:oV(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:oV(t.error)})]})]})}function px(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function pb(e){return oV(ep(e))}function pv(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:pb(r.path)}):t(n)}function py(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pk(e,t){return e.timedOut?t("mcp.actionTimedOut"):py(e,t)}function pj(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function pw(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a,onTrustProject:o,onProjectTrustChanged:l}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(()=>sC("mcp",t)),[g,f]=(0,i.useState)({saving:!1,error:null}),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)({}),E=(0,i.useRef)(0),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,P]=(0,i.useState)({}),z=(0,i.useRef)(L);z.current=L;let[O,W]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,_]=(0,i.useState)(uM),H=(0,i.useRef)(B);H.current=B;let[U,q]=(0,i.useState)(null),[K,Z]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let G=(0,i.useCallback)(async()=>{let e=++E.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await lR(t,void 0,n.signal);if(e===E.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}:{}}),m(e=>lx(lg(r.data,!!t),e))}},[t]),Y=ou(a);(0,i.useEffect)(()=>(G(),()=>{E.current+=1,T.current?.abort()}),[G,Y]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"preference"});let n=await lP(e,void 0,t.signal);M.current===t&&(M.current=null,f({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}),G())},[G]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"mode"});let n=await lz(e,void 0,t.signal);M.current===t&&(M.current=null,f({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),G())},[G]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"inlineBudget"});let n=await lO(e,void 0,t.signal);M.current===t&&(M.current=null,f({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),G())},[G]);(0,i.useEffect)(()=>{let e=A.current;return V.current=!0,()=>{V.current=!1,M.current?.abort(),M.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=o3(e);if(A.current.has(n))return;let r={};A.current.set(n,r),$(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,a=await lQ({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),$(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],a,e.configKey)}));let o=J.current,l="loaded"===o.state?o.data.servers.find(e=>o3(e)===n):void 0;(a.ok?l?.configKey===a.data.configKey:void 0===a.error.reason||a.error.timedOut)||G()},[t,G]),en=(0,i.useCallback)((e,n)=>{E.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),m(r=>lx(lg(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=o3(e),r=z.current[n];if(r?.starting||pr(r))return;P(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,a=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 pu("/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);V.current&&(P(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?pl({},e.data,t):{error:e.error}}(a)})),a.ok||void 0===a.error.reason||a.error.timedOut||G())},[t,G]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=o3(e);P(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 pu(pp(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&P(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?{...pl(i,n.data,r),pasteError:void 0}:pd(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=o3(e);P(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 pu(pp(e),{method:"DELETE"},t,n,r)}(t);V.current&&P(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?pl(i,n.data,r):pd(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),ea=Object.entries(L).flatMap(e=>{let[t,n]=e;return pr(n)&&n.flow?[`${t}\x01${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!ea)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of ea.split("\x02")){let[n,r]=t.split("\x01"),i=z.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 pu(pp(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;P(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?pl(e,n.data,r):pd(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}})}W(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[ea,O]);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],pr(n)&&!pr(r)})&&G()},[L,G]);let el=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,b(n);let s=J.current,a="loaded"===s.state&&s.data.project?t:null,o=await lU(e,a,void 0,i.signal);if(R.current===i)return R.current=null,b(null),o.ok?en(o.data,r?.(o.data)):G(),o},[en,t,G]),ed=(0,i.useCallback)(async(e,t)=>{let n=o3(e),r=pj();y(null),j(null);let i=await el({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),ec=(0,i.useCallback)(async(e,t)=>{let n=o3(e),r=pj();y(null),j(null);let i=await el({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),eu=(0,i.useCallback)(async(e,t)=>{let n=o3(e),r=pj();y(null),j(null);let i=await el({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}))},[el]),ep=(0,i.useCallback)(async e=>{let t=o3(e),n=pj();y(null),j(null);let r=await el({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})},[el]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=pj();y(null),j(null),S({...w,undoing:!0,error:void 0});let t=await el({action:"undo",token:w.token},"undo",e=>e.restored?o3(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[el,w]),em=(0,i.useCallback)(async e=>{let t=o3(e),n=pj();y(null),j(null),P(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await el({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(P(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();$(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})}},[el]),eg=(0,i.useCallback)(async e=>{let n=pj(),r=H.current;y(null),j(null),q(null);let i=await el(e,"add",e=>e.added?o3(e.added):void 0);if(!i)return;let s=H.current!==r;if(!i.ok){s||q(i.error),i.error.trust&&t&&l?.(t,i.error.trust),N({control:n});return}let{added:a,trust:o,trustedFolder:d}=i.data;if(D(!1),s||_(uM),N({control:null,toSelectedRow:!0}),!a)return;Z({...a,key:o3(a),...d&&t?{trustedFolder:t}:{}}),o&&t&&l?.(t,o);let c=i.data.servers.find(e=>o3(e)===o3(a));c&&!lK(c,i.data)&&et(c)},[t,l,el,et]),ef=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===ef||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===ef?null:e),ex);return()=>clearTimeout(e)},[ef,ex]);let eb=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:oc(t,n,e=>e.enabled).filter(n?l_:lB),keptOff:n?t.filter(e=>!e.enabled&&lB(e)&&!l_(e)).length:0},s=pj();if(y(null),j(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let a=await el({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!a)return;if(N({control:s}),!a.ok)return void j({scope:e,keptOff:i,failures:[],total:r.length,error:a.error});let o=a.data.results??[],l=o.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));j(l.length>0||i>0?{scope:e,keptOff:i,failures:l,total:o.length}:null)},[el]);return(0,i.useEffect)(()=>{h&&sN("mcp",h,t)},[t,h]),(0,r.jsx)(pS,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:g,busy:x,actionError:v,groupStatus:k,undo:w,focusBack:C,tests:I,signIns:L,adding:F,addDraft:B,addFailure:U,added:K,onAddOpen:()=>{D(!0),Z(null),y(null)},onAddDraftChange:e=>{H.current=e,_(e),q(null)},onAddSubmit:e=>void eg(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void em(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{m(e),y(null),D(!1),Z(t=>t?.key===e?t:null)},onRefresh:()=>void G(),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 eb(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:o,onClose:n})}function pS(e){var t,n,s,a;let o,l,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:m,codemodeSave:g={saving:!1,error:null},busy:f=null,actionError:x=null,groupStatus:b=null,undo:v=null,focusBack:y=null,tests:k={},signIns:j={},adding:w=!1,addDraft:S=uM,addFailure:C=null,added:N=null,onAddOpen:I=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:E=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:P=()=>{},onServerSwitchInProject:z=()=>{},onExposureChange:O=()=>{},onGroupSwitch:W=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:_=()=>{},onSignOut:H=()=>{},onSignInPaste:U=()=>{},onSignInCancel:q=()=>{},onTrustProject:K,onClose:Z}=e,{t:V}=(0,eX.s)(),J=(0,i.useId)(),G=(0,i.useId)(),Y="loaded"===u.state?(t=u.data,o=!1,l=t.servers.map(e=>{var t;let n=k[o3(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:l}:t):void 0,X=Y?lg(Y,!!c):[],Q=Y?{mcpAvailable:Y.mcp.available,projectServersLoad:o5(Y.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>o3(e)===p),en=N?ee.find(e=>o3(e)===N.key):void 0,er=Y?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"}}(Y.mcp):void 0,ei=er?void 0:Y?.hostInactive,es=Y?.files.find(e=>"project"===e.scope),ea=Y?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"}}(Y.project,es):void 0,eo=K&&lb(Y?.project)?K:void 0,el=ea?.kind==="untrusted"&&void 0!==eo,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(el);(0,i.useEffect)(()=>{let e=eu.current;eu.current=el,e&&!el&&e$(document,ed.current??ec.current)},[el]);let eh=(0,i.useRef)(null),em=v?.token,eg=(0,i.useRef)(em);(0,i.useEffect)(()=>{let e=eg.current;eg.current=em,void 0!==em&&em!==e?e$(document,eh.current):void 0!==e&&void 0===em&&e$(document,ed.current??ec.current)},[em]);let ef=Y?[...Y.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],ex=lf(ee),eb=Y?.files.find(e=>"global"===e.scope),ev=Y?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&o5(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}}(Y):void 0,ey=Y?(n=ee.length,s=Y.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(lm))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ek=null!==f||h||g.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ek&&ej.current!==y)if(ej.current=y,y.toSelectedRow)e$(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&e$(e,t.isConnected&&!t.disabled?t:n)}},[y,ek]);let ew=e=>Y?lF(e,Y):void 0,eS=!!Y&&lW(Y.mcp),eC=X.find(e=>"project"===e.scope)?.servers??[],eN=ew("project"),eI=ea?.kind==="untrusted"?[pv(ea,V),eN&&"mcp-off"!==eN&&eC.length>0?V(lD[eN]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(sQ,{embedded:m,title:V("settings.mcp"),subtitle:c?ep(c):void 0,closeLabel:V("i18n.close"),onClose:Z,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(af,{id:J,children:[pv(er,V),eS&&(0,r.jsxs)(r.Fragment,{children:[" ",V(lD["mcp-off"])]}),Y&&!Y.mcp.available&&Y.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oV(Y.mcp.detail)})]})]}),ei&&(0,r.jsx)(af,{children:V("mcp.hostInactive",{path:pb(ei.cwd),owner:pb(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(af,{children:V("mcp.projectNotListed",{reason:py(u.projectError,V)})}),ea?.kind==="untrusted"&&(0,r.jsx)(ax,{id:G,message:eI,trustLabel:V("mcp.trust.trustButton"),onTrust:eo}),ea?.kind==="inherited"&&(0,r.jsx)(af,{children:pv(ea,V)}),v&&(0,r.jsxs)(af,{action:v.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(aj,{ref:eh,size:"small",onClick:D,disabled:v.undoing||ek,children:v.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:oV(v.name),path:pb(v.path)}),v.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",pk(v.error,V)]})]}),N&&Y&&en&&(0,r.jsx)(pC,{added:N,cwd:c,server:en,testing:k[N.key]?.running===!0,signIn:j[N.key],signingOut:f===`sign-out:${N.key}`,signInBlock:en?lK(en,Y):void 0,onSignIn:_})]}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:V("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[V("mcp.loadFailed")," ",py(u.error,V)]}):Y&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(pN,{codemode:Y.codemode,active:!w&&p===o6,rowRef:ed,onSelect:T})}),X.map(e=>{let t=ew(e.scope);return(0,r.jsx)(pI,{group:e,context:Q,selected:w?null:p,selectedRowRef:ed,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&ea?.kind==="untrusted"?G:void 0,busy:f,controlsBusy:ek,status:b?.scope===e.scope?b:null,onSelect:T,onGroupSwitch:W},e.scope)})]}):null}),Y&&(0,r.jsx)(aS,{ref:ec,active:w,onClick:I,children:V("mcp.add.action")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:Y&&Q&&ev&&ey?w?(0,r.jsx)(u9,{data:Y,cwd:c,draft:S,busy:"add"===f,controlsBusy:ek,failure:C,onDraftChange:$,onSubmit:E,onTrustProject:eo}):p===o6?(0,r.jsx)(pF,{codemode:Y.codemode,autoEnable:ev,save:g,serverBusy:null!==f,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(pT,{server:et,context:Q,codemode:Y.codemode,toolSearchDisabled:Y.toolSearchDisabled,autoEnable:ev,block:ew(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!o5(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:o3(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,Y),inProjectBlock:ew("project"),savedWhileOff:!Y.mcp.available&&!eS,busy:f,controlsBusy:ek,actionError:x?.key===o3(et)?x.failure:null,test:(a=k[o3(et)],a&&void 0!==a.configKey&&a.configKey!==et.configKey?{running:a.running,...a.response?{response:a.response}:{}}:a),testBlock:lK(et,Y),signIn:j[o3(et)],signInBlock:lK(et,Y),signOutBlock:(d=lF(et.scope,Y))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:P,onSwitchInProject:z,onShowServer:e=>{T(e),requestAnimationFrame(()=>e$(document,ed.current??ec.current))},onExposureChange:O,onRemove:F,onTest:B,onSignIn:_,onSignOut:H,onSignInPaste:U,onSignInCancel:q},o3(et)):(0,r.jsx)(ab,{children:"mcp.empty"===ey?V(ey,{globalPath:pb(eb?.path??"~/.pi/agent/mcp.json")}):V(ey)}):null})})]}),(0,r.jsxs)(ay,{status:ef.length>0?(0,r.jsx)(ak,{tone:ef.some(e=>{let{problem:t}=e;return lm(t)})?"error":"warning",summary:1===ef.length?V("mcp.footer.fileProblem"):V("mcp.footer.fileProblems",{count:ef.length}),details:ef.map(e=>{let{file:t,problem:n}=e,i=o8(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:pb(t.path)})," ",V(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(ak,{summary:ex.total>0?V("mcp.serverCount",{enabled:ex.enabled,total:ex.total}):""}),children:[!m&&(0,r.jsx)(aj,{onClick:Z,children:V("i18n.close")}),(0,r.jsx)(aj,{variant:"secondary",onClick:M,disabled:ek,children:V("i18n.refresh")})]})]})}function pC(e){let{added:t,cwd:n,server:i,testing:s,signIn:a,signingOut:o,signInBlock:l,onSignIn:d}=e,{t:c}=(0,eX.s)(),u=oV(t.name),p="project"===t.scope&&n?oV(eh(t.path,n)):pb(t.path),h=i.status,m=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,g=a?.starting===!0||pr(a);return(0,r.jsxs)(af,{action:!m||g||o||l?void 0:(0,r.jsx)(aj,{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:pb(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),m&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function pN(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:a}=(0,eX.s)(),o=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",l=a(lw[o]);return(0,r.jsxs)(ae,{ref:n?i:void 0,active:n,"aria-label":a("mcp.codemode.rowLabel",{state:l}),onClick:()=>s(o6),children:[(0,r.jsx)(aC,{...la(lS(o))}),(0,r.jsx)(at,{className:"is-grow",children:a("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${lS(o)}`,children:l})]})}function pI(e){var t;let n,i,{group:s,context:a,selected:o,selectedRowRef:l,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:m,onGroupSwitch:g}=e,{t:f}=(0,eX.s)(),{enabled:x,total:b}=lf(s.servers),v=(t=s.servers).some(e=>e.enabled&&lB(e))&&t.every(e=>e.enabled||!l_(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(lm)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),k=h?(n=h.keptOff>0?f("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${f("mcp.actionFailed")} ${pk(h.error,f)}`:h.failures.length>0?[f("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${oV(t)}: ${pk(n,f)}`})].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)(s5,{aside:b>0?(0,r.jsx)(s9,{enabled:x,total:b,checked:v,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:f(v?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:px(s.scope,f)}),onChange:e=>g(s.scope,s.servers,e)}):void 0,children:px(s.scope,f)}),k&&(0,r.jsx)(s7,{note:k.note,error:k.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:f(y)}),s.servers.map(e=>{let t=o3(e),n=o7(e,a),i=ls(n),s=li[n],d=oV(e.name);return(0,r.jsxs)(ae,{ref:o===t?l:void 0,active:o===t,"aria-label":f("mcp.rowLabel",{name:d,state:f(ln(n,e.status))}),onClick:()=>m(t),children:[(0,r.jsx)(aC,{...la(i)}),(0,r.jsx)(at,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:f(s)})]},t)})]})}function p$(e){let{fields:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=o0(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pE(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:oV(e)},e))})}function pT(e){let{server:t,context:n,codemode:s,toolSearchDisabled:a,autoEnable:o,block:l,inProject:d,inProjectBlock:c,savedWhileOff:u,busy:p,controlsBusy:h,actionError:m,test:g,testBlock:f,signIn:x,signInBlock:b,signOutBlock:v,onSwitch:y,onSwitchInProject:k,onShowServer:j,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:I,onSignInPaste:$,onSignInCancel:E}=e,{t:T}=(0,eX.s)(),M=(0,i.useId)(),R=(0,i.useId)(),A=o7(t,n),L=oX(t),P=t.status,z=P?.origin==="test"&&"connected"===P.state&&P.toolCount>0?P:void 0,O=void 0===t.invalidError,W="http"===t.transport||void 0===t.transport&&void 0!==t.url,F=!W&&("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"===lv(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:a},o):void 0,B=(0,i.useId)(),_=(0,i.useId)(),H=o3(t),U=oV(t.name),q=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,Z=l?T(`mcp.reason.${l}`):K?T("mcp.reason.entry-not-object"):q?T("mcp.reason.web-password"):u?T("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(an,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ar,{children:[(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:t.scope,children:px(t.scope,T)}),(0,r.jsx)(aa,{children:U})]}),(0,r.jsxs)(as,{children:[(0,r.jsx)(pO,{server:t,test:g,testBlock:f,describedBy:R,onTest:C}),(0,r.jsx)(aj,{variant:"danger",size:"small",disabled:h||void 0!==l,"aria-describedby":l?M:void 0,onClick:()=>S(t),children:p===`remove:${H}`?T("i18n.removing"):T("i18n.remove")}),(0,r.jsx)(aw,{checked:t.enabled,disabled:h||void 0!==l||K||q,loading:p===`switch:${H}`,describedBy:Z?M:void 0,label:T(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:U}),onChange:e=>y(t,e)})]})]}),Z&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:Z})]}),m&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[T("mcp.actionFailed")," ",pk(m,T)]}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(pW,{server:t,state:A,test:g,testBlock:f,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(ac,{label:T("mcp.detail.description"),tone:"plain",children:oV(t.description)}),void 0!==L?(0,r.jsx)(ac,{label:W?T("mcp.detail.url"):T("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:L}):t.transport&&(0,r.jsx)(ac,{label:T("mcp.detail.transport"),children:T(`mcp.transport.${t.transport}`)}),F&&void 0!==t.cwd&&(0,r.jsx)(ac,{label:T("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:oV(t.cwd)}),F&&t.envNames.length>0&&(0,r.jsx)(ac,{label:T("mcp.detail.env"),children:(0,r.jsx)(pE,{names:t.envNames})}),W&&t.headerNames.length>0&&(0,r.jsx)(ac,{label:T("mcp.detail.headers"),children:(0,r.jsx)(pE,{names:t.headerNames})}),O&&t.commandFields.length>0&&(0,r.jsx)(ac,{label:T("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:T("mcp.server.commandFields")}),(0,r.jsx)(p$,{fields:t.commandFields})]})}),O&&t.variableReferences.length>0&&(0,r.jsx)(ac,{label:T("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:T(o1(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:o4(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=o0(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:T("mcp.server.variableIn",{variable:t,field:T(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),W&&O&&(0,r.jsx)(pm,{server:t,run:x,block:b,signOutBlock:v,controlsBusy:h,signingOut:p===`sign-out:${H}`,onSignIn:N,onSignOut:I,onPaste:$,onCancel:E}),(t.exposure||z)&&(0,r.jsx)(ac,{label:T("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":T("mcp.exposure.label",{name:U}),"aria-describedby":[B,l?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==l,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:lp.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?T("mcp.exposure.optionDefault",{label:T(lh[e])}):T(lh[e])},e))}),p===`exposure:${H}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:T("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:T(lu[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:T("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),D&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(D,T)})]}),z&&(0,r.jsx)(pz,{status:z,serverExposure:t.exposure})]})}),d&&(0,r.jsx)(ac,{label:T("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?T("mcp.inProject.overridden",{keys:d.keys.join(", ")}):T("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(aj,{size:"small",onClick:()=>j(d.key),children:T("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(aj,{size:"small",disabled:h||void 0!==c||q,"aria-describedby":[_,c||q?M:null].filter(Boolean).join(" "),onClick:()=>k(t,!t.enabled),children:p===`in-project:${H}`?T("i18n.saving"):T(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:_,className:"mcp-config-line is-dim",children:T("mcp.inProject.saved")})]})})}),(0,r.jsx)(ac,{label:T("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:pb(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[oQ(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:pv(o2(t.override.keys),T)}),t.shadowedByProject&&"replaced"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:T("mcp.server.masked")})]})]})}function pM(e){let{error:t,stderr:n}=e,{t:i}=(0,eX.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:oV(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(oV).join("\n")})]})]})}function pR(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(pP,{status:t,showState:n}):(0,r.jsx)(pL,{status:t,showState:n,entryCwd:i})}function pA(e){let{view:t}=e,{t:n}=(0,eX.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function pL(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:a}=(0,eX.s)(),o=lo(t.testedAt,a),l=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(pA,{view:t.timedOut?{key:lV.timedOut,tone:"error"}:{key:lV[t.state],tone:ls(t.state)}}),s((t.afterSignIn?lG:lJ)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:lY(t.durationMs),time:o})]}),(0,r.jsx)(pM,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:oV(l.title??l.name),version:oV(l.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:pb(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:lY(t.queuedMs)})})]})}function pP(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,eX.s)(),a=lo(t.updatedAt,s),o=void 0===t.closedAt?void 0:lo(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(pA,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:ll[t.state],tone:lc[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":ld[t.state],{path:pb(t.cwd),time:a,...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:pb(t.conflict)})]}),(0,r.jsx)(pM,{error:t.error,stderr:t.stderr})]})}function pz(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eX.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:oV(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(lh[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:oV(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 pO(e){let{server:t,test:n,testBlock:s,describedBy:a,onTest:o}=e,{t:l}=(0,eX.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&&e$(document,d.current)},[c]),(0,r.jsx)(aj,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?a:void 0,onClick:()=>o(t),children:l(c?"mcp.test.testing":"mcp.test.button")})}function pW(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:a}=e,{t:o}=(0,eX.s)(),l=t.status,d=lr[n],c="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(ac,{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-${ls(n)}`,children:o(ln(n,l))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===c?a:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oV(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===c?a:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.webPassword")," ",(0,r.jsx)(p$,{fields:[t.webPasswordField]})]}),l?(0,r.jsx)(pR,{status:l,showState:o9(l)!==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?lZ[e.reason]:void 0;return n?t(n):py(e,t)}(i.error,o)]}),s&&!c&&(0,r.jsx)("span",{id:a,className:"mcp-config-line is-dim",children:o(lq[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.serial")})]})})}function pF(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:a,onModeChange:o,onInlineBudgetSave:l}=e,{t:d}=(0,eX.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},m=function(e,t){if("automatic"===lv(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),g="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,f=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:ly[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(an,{children:[(0,r.jsx)(ar,{children:(0,r.jsx)(ai,{children:(0,r.jsx)(aa,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{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)(ap,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(lw.automatic),disabled:p},{value:"always",label:d(lw.always),disabled:p||void 0!==g}],disabledReason:g?pv(g,d):null,onChange:e=>{e!==u&&a(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:oV(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(pD,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(x,d)}),m&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(m,d)})]})}),t.mode?(0,r.jsx)(pB,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:o}):void 0!==t.modeError&&(0,r.jsx)(ac,{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:oV(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(p_,{budget:t.inlineBudget,save:i,waiting:p,onSave:l}):void 0!==t.inlineBudgetError&&(0,r.jsx)(ac,{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:oV(t.inlineBudgetError)})]})}),(0,r.jsx)(ac,{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:oV(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),f&&(0,r.jsx)(ac,{label:d("mcp.codemode.builtin"),tone:"error",children:pv(f,d)})]})]})}function pD(e){let{error:t}=e,{t:n}=(0,eX.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:oV(t.error)})}function pB(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:a}=e,{t:o}=(0,eX.s)(),l="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:lj[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===lv(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(ac,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(ap,{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)&&a(e)},children:l&&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(lk[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(e,o)},e.key)),l&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(pD,{error:i.error})]})]})})}function p_(e){let t,n,{budget:s,save:a,waiting:o,onSave:l}=e,{t:d}=(0,eX.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,m]=(0,i.useState)(p);(0,i.useEffect)(()=>{m(p)},[p]);let g=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),f=!!g.ok&&(null===g.value?void 0!==s.value||void 0!==s.invalid:g.value!==s.value),x="inlineBudget"===a.target,b=x&&a.saving,v=(0,i.useRef)(b);(0,i.useEffect)(()=>{let e=v.current;v.current=b,e&&!b&&e$(document,c.current)},[b]);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)(ac,{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(),g.ok&&f&&!o&&l(g.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":!g.ok||void 0,value:h,placeholder:String(s.default),readOnly:o,autoComplete:"off",spellCheck:!1,onChange:e=>m(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(aj,{type:"submit",size:"small",disabled:!f||o,children:d("mcp.codemode.inlineBudget.save")}),b&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!g.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:pv(e,d)},e.key)),x&&a.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(pD,{error:a.error})]})]})})}async function pH(e){let t=await fetch("/api/channels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));return{ok:t.ok,error:n.error}}function pU(e){var t;let n,{embedded:s=!0,onClose:a}=e,{t:o}=(0,eX.s)(),[l,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(""),[m,g]=(0,i.useState)(""),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),y=(0,i.useRef)(!1),k=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/channels",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return void u(t.error??`HTTP ${e.status}`);d(t),u(null),y.current||g(t.config.defaultCwd??"")}catch(e){u(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{k();let e=setInterval(()=>void k(),5e3);return()=>clearInterval(e)},[k]);let j=(0,i.useCallback)(async(e,t,n)=>{x(e),v(null);let r=await pH(t);if(x(null),!r.ok)return void v({kind:"error",message:r.error??o("telegram.actionFailed")});let i=n();i&&v(i),await k()},[k,o]),{config:w}=l??{};return(0,r.jsxs)(sQ,{embedded:s,title:o("settings.channels"),closeLabel:o("i18n.close"),onClose:()=>a?.(),children:[(0,r.jsxs)(s8,{children:[(0,r.jsx)(s6,{children:(0,r.jsx)(s3,{children:c&&!l?(0,r.jsx)("div",{role:"alert",className:"config-sidebar-message is-error",children:o("channels.loadFailed",{error:c})}):l?(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(s5,{children:o("channels.group")}),(n=l.config.tokenSet?l.config.enabled?l.lastError?{tone:"error",badge:"channels.badge.error"}:{tone:"on",badge:"channels.badge.on"}:{tone:"off",badge:"channels.badge.off"}:{tone:"off",badge:"channels.badge.unconfigured"},(0,r.jsxs)(ae,{active:!0,"aria-label":`Telegram — ${o(n.badge)}`,children:[(0,r.jsx)(aC,{..."on"===(t=n.tone)?{active:!0}:"off"===t?{active:!1}:{color:"#ef4444"}}),(0,r.jsx)(at,{className:"is-grow",children:"Telegram"}),(0,r.jsx)("span",{className:`mcp-sidebar-badge${"error"===n.tone?" is-error":""}`,children:o(n.badge)})]}))]}):(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")})})}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:l&&w?(0,r.jsxs)(r.Fragment,{children:[b&&(0,r.jsx)(af,{children:b.message}),l.lastError&&(0,r.jsx)(af,{children:o("telegram.loopError",{error:l.lastError})}),(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(aa,{children:"Telegram"})}),(0,r.jsx)(as,{children:(0,r.jsx)(aw,{checked:w.enabled,disabled:!w.tokenSet||null!==f,label:o("telegram.enabledLabel"),onChange:e=>void j("enabled",{action:"set-enabled",enabled:e},()=>null)})})]}),!w.tokenSet&&(0,r.jsx)(af,{children:o("telegram.setupHint")}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:o("telegram.botStatus"),children:l.running?o("telegram.connected",{bot:l.botUsername??""}):o("telegram.notConnected")}),(0,r.jsx)(ac,{label:o("telegram.tokenLabel"),children:(0,r.jsx)("input",{type:"password",autoComplete:"off",spellCheck:!1,className:"mcp-add-input",placeholder:w.tokenSet?o("telegram.tokenPlaceholder",{hint:w.tokenHint??""}):"1234567890:AA…","aria-label":o("telegram.tokenLabel"),value:p,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)(as,{children:[(0,r.jsx)(aj,{size:"small",disabled:""===p.trim()||null!==f,onClick:()=>void j("token",{action:"set-token",token:p.trim()},()=>(h(""),{kind:"ok",message:o("telegram.tokenSaved")})),children:o("telegram.tokenSave")}),w.tokenSet&&(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j("remove-token",{action:"remove-token"},()=>({kind:"info",message:o("telegram.tokenRemoved")})),children:o("telegram.tokenRemove")})]}),(0,r.jsx)(ao,{children:o("telegram.chatsHeading")}),(0,r.jsx)(ai,{children:o("telegram.chatsDescription")}),l.lastUnknownChat&&(0,r.jsx)(af,{action:(0,r.jsx)(aj,{size:"small",disabled:null!==f||w.allowedChats.some(e=>e.id===l.lastUnknownChat?.id),onClick:()=>void j("allow",{action:"allow-chat",chatId:l.lastUnknownChat?.id,title:l.lastUnknownChat?.title},()=>({kind:"ok",message:o("telegram.chatAllowed")})),children:o("telegram.allowChat")}),children:o("telegram.unknownChatPrompt",{title:l.lastUnknownChat.title??o("telegram.unnamedChat"),id:String(l.lastUnknownChat.id)})}),0===w.allowedChats.length?(0,r.jsx)(ab,{children:o("telegram.noChats")}):(0,r.jsx)(r.Fragment,{children:w.allowedChats.map(e=>(0,r.jsx)("div",{className:"channels-chat",children:(0,r.jsxs)(ad,{children:[(0,r.jsxs)(ac,{label:e.title??o("telegram.unnamedChat"),mono:!0,children:[e.id,(0,r.jsxs)(as,{children:[(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j(`test-${e.id}`,{action:"test-send",chatId:e.id},()=>({kind:"ok",message:o("telegram.testSent")})),children:o("telegram.testSend")}),(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j(`remove-${e.id}`,{action:"remove-chat",chatId:e.id},()=>({kind:"info",message:o("telegram.chatRemoved")})),children:o("telegram.chatRemove")})]})]}),(0,r.jsx)(ac,{label:o("telegram.chatCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:o("telegram.defaultCwdPlaceholder"),"aria-label":o("telegram.chatCwdLabel"),defaultValue:e.cwd??"",onBlur:t=>{let n=t.target.value.trim();n!==(e.cwd??"")&&j(`cwd-${e.id}`,{action:"set-chat-cwd",chatId:e.id,cwd:n},()=>({kind:"ok",message:o("telegram.chatCwdSaved")}))}},`${e.id}:${e.cwd??""}`)})]})},e.id))}),(0,r.jsx)(ao,{children:o("telegram.defaultCwdLabel")}),(0,r.jsx)(ad,{children:(0,r.jsx)(ac,{label:o("telegram.defaultCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:o("telegram.defaultCwdPlaceholder"),"aria-label":o("telegram.defaultCwdLabel"),value:m,onChange:e=>{y.current=!0,g(e.target.value)}})})}),(0,r.jsx)(as,{children:(0,r.jsx)(aj,{size:"small",disabled:null!==f,onClick:()=>void j("cwd",{action:"set-default-cwd",cwd:m.trim()},()=>({kind:"ok",message:o("telegram.defaultCwdSaved")})),children:o("telegram.defaultCwdSave")})})]}):null})})]}),(0,r.jsx)(ay,{status:l?(0,r.jsx)(ak,{tone:l.lastError?"warning":void 0,summary:l.running?o("telegram.connected",{bot:l.botUsername??""}):o("telegram.notConnected")}):void 0,children:!s&&a&&(0,r.jsx)(aj,{onClick:a,children:o("i18n.close")})})]})}let pq={minutes:6e4,hours:36e5,days:864e5};function pK(e){return String(e).padStart(2,"0")}function pZ(e){let t=new Date(e);return`${t.getFullYear()}-${pK(t.getMonth()+1)}-${pK(t.getDate())}T${pK(t.getHours())}:${pK(t.getMinutes())}`}function pV(e){if("cron"===e.kind)return{kind:"cron",expr:e.cronExpr.trim(),...""!==e.cronTz.trim()?{tz:e.cronTz.trim()}:{}};if("at"===e.kind){let t=Date.parse(e.atLocal);return Number.isFinite(t)?{kind:"at",atMs:t}:null}let t=Math.round(e.everyValue)*pq[e.everyUnit];return Number.isFinite(t)&&e.everyValue>0?{kind:"every",everyMs:t}:null}function pJ(e){if(!e)return{name:"",kind:"every",cronExpr:"0 9 * * *",cronTz:Intl.DateTimeFormat().resolvedOptions().timeZone,atLocal:pZ(Date.now()+36e5),everyValue:1,everyUnit:"hours",cwd:"",prompt:"",notify:!0,notifyChannels:[],silentWhen:""};let t=e.schedule;return{name:e.name,kind:t.kind,cronExpr:"cron"===t.kind?t.expr:"0 9 * * *",cronTz:"cron"===t.kind?t.tz??"":"",atLocal:"at"===t.kind?pZ(t.atMs):pZ(Date.now()+36e5),everyValue:"every"===t.kind?t.everyMs/pq.hours>=1&&t.everyMs%pq.hours==0?t.everyMs/pq.hours:Math.max(1,Math.round(t.everyMs/pq.minutes)):1,everyUnit:"every"===t.kind&&(t.everyMs%pq.hours!=0||t.everyMs<pq.hours)?"minutes":"hours",cwd:e.cwd,prompt:e.prompt,notify:e.notify,notifyChannels:e.notifyChannels.flatMap(e=>"telegram"===e.type&&Number.isInteger(e.chatId)?[{type:"telegram",chatId:e.chatId}]:[]),silentWhen:e.silentWhen}}function pG(e,t){if(null===e)return t("automations.neverAgain");let n=new Date(e),r=new Date().toDateString()===n.toDateString(),i=`${pK(n.getHours())}:${pK(n.getMinutes())}`;return r?i:`${pK(n.getMonth()+1)}-${pK(n.getDate())} ${i}`}async function pY(e){let t=await fetch("/api/automations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));return{ok:t.ok,error:"string"==typeof n.error?n.error:void 0,payload:n}}function pX(e){let{embedded:t=!0,onClose:n}=e,{t:s}=(0,eX.s)(),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(()=>pJ(null)),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),w=(0,i.useRef)("ok"),S=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/automations",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return;o(t.automations??[]),d(t.runs??[]),t.telegram&&u(t.telegram)}catch{}},[]);(0,i.useEffect)(()=>{S();let e=setInterval(()=>void S(),5e3);return()=>clearInterval(e)},[S]);let C=(0,i.useMemo)(()=>a?.find(e=>e.id===h)??null,[a,h]),N=(0,i.useCallback)(e=>{m(e),b(null),j(null),f(pJ(a?.find(t=>t.id===e)??null))},[a]),I=(0,i.useCallback)(()=>{m("new"),b(null),j(null),f(pJ(null))},[]);(0,i.useEffect)(()=>{let e=pV(g);if(!e)return;let t=setTimeout(()=>{pY({action:"preview",schedule:e}).then(e=>{e.ok?b({dueAt:"number"==typeof e.payload?.dueAt?e.payload.dueAt:null,problem:"string"==typeof e.payload?.problem?e.payload.problem:null}):b({dueAt:null,problem:e.error??s("automations.actionFailed")})})},400);return()=>clearTimeout(t)},[g,s]);let $=(0,i.useCallback)(async(e,t,n)=>{y(e),j(null);let r=await pY(t);return(y(null),r.ok)?(null!==n&&(w.current="ok",j(n)),await S(),!0):(w.current="error",j(r.error??s("automations.actionFailed")),!1)},[S,s]),E=()=>n?.(),T=null!==C,M=pV(g),R=""!==g.name.trim()&&""!==g.cwd.trim()&&""!==g.prompt.trim()&&null!==M&&x?.problem==null;return(0,r.jsxs)(sQ,{embedded:t,title:s("settings.automations"),closeLabel:s("i18n.close"),onClose:E,children:[(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:null===a?(0,r.jsx)("div",{className:"config-sidebar-message",children:s("i18n.loading")}):0===a.length&&null===h?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:s("automations.noneYet")}):(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(s5,{children:s("automations.group")}),a.map(e=>(0,r.jsxs)(ae,{active:h===e.id,onClick:()=>N(e.id),children:[(0,r.jsx)(aC,{active:e.enabled&&null!==e.nextDueAt}),(0,r.jsx)(at,{className:"is-grow",children:e.name}),(0,r.jsx)("span",{className:"mcp-sidebar-badge",children:e.enabled?null!==e.nextDueAt?pG(e.nextDueAt,s):"…":s("channels.badge.off")})]},e.id))]})}),(0,r.jsx)(aS,{active:"new"===h,onClick:I,children:s("automations.newAction")})]}),(0,r.jsx)(av,{children:(0,r.jsxs)(an,{className:"is-fill",children:[(null===h||"new"===h||T)&&(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)(af,{children:k}),null!==h&&"new"!==h&&T&&(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(aa,{children:C.name})}),(0,r.jsxs)(as,{children:[(0,r.jsx)(aw,{checked:C.enabled,disabled:null!==v,label:s("automations.enabledLabel"),onChange:e=>void $(`enabled-${C.id}`,{action:"set-enabled",id:C.id,enabled:e},null)}),(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==v,onClick:()=>void $(`run-${C.id}`,{action:"run-now",id:C.id},s("automations.runStarted")),children:s("automations.runNow")}),(0,r.jsx)(aj,{size:"small",variant:"danger",disabled:null!==v,onClick:()=>{$(`delete-${C.id}`,{action:"delete",id:C.id},s("automations.deleted")).then(e=>{e&&N(null)})},children:s("automations.delete")})]})]}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:s("automations.nameLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,"aria-label":s("automations.nameLabel"),value:g.name,onChange:e=>f(t=>({...t,name:e.target.value}))})}),(0,r.jsx)(ac,{label:s("automations.scheduleLabel"),children:(0,r.jsxs)("div",{className:"automations-schedule",children:[(0,r.jsxs)("select",{"aria-label":s("automations.scheduleLabel"),value:g.kind,onChange:e=>f(t=>({...t,kind:e.target.value})),children:[(0,r.jsx)("option",{value:"cron",children:s("automations.kind.cron")}),(0,r.jsx)("option",{value:"every",children:s("automations.kind.every")}),(0,r.jsx)("option",{value:"at",children:s("automations.kind.at")})]}),"cron"===g.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"0 9 * * 1-5","aria-label":s("automations.cronExpr"),value:g.cronExpr,onChange:e=>f(t=>({...t,cronExpr:e.target.value}))}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"Asia/Shanghai","aria-label":s("automations.cronTz"),value:g.cronTz,onChange:e=>f(t=>({...t,cronTz:e.target.value}))})]}),"every"===g.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"automations-number-input",type:"number",min:1,"aria-label":s("automations.everyValue"),value:g.everyValue,onChange:e=>f(t=>({...t,everyValue:Number(e.target.value)}))}),(0,r.jsxs)("select",{"aria-label":s("automations.everyUnit"),value:g.everyUnit,onChange:e=>f(t=>({...t,everyUnit:e.target.value})),children:[(0,r.jsx)("option",{value:"minutes",children:s("automations.unit.minutes")}),(0,r.jsx)("option",{value:"hours",children:s("automations.unit.hours")}),(0,r.jsx)("option",{value:"days",children:s("automations.unit.days")})]})]}),"at"===g.kind&&(0,r.jsx)("input",{className:"automations-datetime-input",type:"datetime-local","aria-label":s("automations.atTime"),value:g.atLocal,onChange:e=>f(t=>({...t,atLocal:e.target.value}))})]})}),(0,r.jsx)(ac,{label:s("automations.nextRun"),children:null===x?"…":null!==x.problem?`⚠️ ${x.problem}`:`${pG(x.dueAt,s)}`}),(0,r.jsx)(ac,{label:s("automations.cwdLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"/Volumes/…","aria-label":s("automations.cwdLabel"),value:g.cwd,onChange:e=>f(t=>({...t,cwd:e.target.value}))})}),(0,r.jsx)(ac,{label:s("automations.notifyLabel"),children:(0,r.jsxs)("div",{className:"automations-notify",children:[(0,r.jsxs)("div",{className:"automations-notify-row",children:[(0,r.jsx)(aw,{checked:g.notify,label:s("automations.notifyBrowser"),onChange:e=>f(t=>({...t,notify:e}))}),(0,r.jsx)("span",{children:s("automations.notifyBrowser")})]}),null!==c&&c.chats.map(e=>{let t=g.notifyChannels.some(t=>t.chatId===e.id);return(0,r.jsxs)("label",{className:"automations-notify-row",children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:t=>f(n=>({...n,notifyChannels:t.target.checked?[...n.notifyChannels,{type:"telegram",chatId:e.id}]:n.notifyChannels.filter(t=>t.chatId!==e.id)}))}),(0,r.jsx)("span",{children:null!==e.title&&""!==e.title.trim()?e.title:`Telegram \xb7 ${e.id}`})]},e.id)}),null!==c&&0===c.chats.length&&(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifyTelegramHint")}),(0,r.jsxs)("div",{className:"automations-notify-row is-wide",children:[(0,r.jsx)("span",{className:"automations-notify-silent-label",children:s("automations.notifySilentLabel")}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"NO_REPLY","aria-label":s("automations.notifySilentLabel"),value:g.silentWhen,onChange:e=>f(t=>({...t,silentWhen:e.target.value}))})]}),(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifySilentHint")})]})})]}),(0,r.jsx)(al,{label:s("automations.promptLabel"),children:(0,r.jsx)("textarea",{className:"automations-prompt",rows:5,spellCheck:!1,"aria-label":s("automations.promptLabel"),value:g.prompt,onChange:e=>f(t=>({...t,prompt:e.target.value}))})}),"new"===h&&(0,r.jsx)(af,{children:s("automations.disclosure")}),(0,r.jsx)(as,{children:(0,r.jsx)(aj,{disabled:!R||null!==v,onClick:()=>{$("save",{action:T?"update":"create",...T?{id:C.id}:{},name:g.name.trim(),schedule:pV(g),cwd:g.cwd.trim(),prompt:g.prompt,notify:g.notify,notifyChannels:g.notifyChannels,silentWhen:g.silentWhen.trim()},T?s("automations.saved"):s("automations.created")).then(e=>{e&&(T||m(null))})},children:T?s("automations.save"):s("automations.create")})})]}),(0,r.jsx)(ao,{children:s("automations.historyTitle")}),0===l.length?(0,r.jsx)(ab,{children:s("automations.noRuns")}):(0,r.jsx)(ad,{children:l.slice(0,12).map(e=>{let t=a?.find(t=>t.id===e.automationId),n=null!==e.finishedAt?Math.max(1,Math.round((e.finishedAt-e.startedAt)/1e3)):null;return(0,r.jsxs)(ac,{label:t?.name??s("automations.deletedAutomation"),mono:!0,children:[(0,r.jsx)(aC,{..."failed"===e.status?{color:"#ef4444"}:{active:"done"===e.status}}),s(`automations.run.${e.status}`)," \xb7 ",new Date(e.startedAt).toLocaleString(),null!==n?` \xb7 ${n}s`:"",null!==e.sessionId&&(0,r.jsx)(aj,{size:"small",variant:"secondary",onClick:()=>window.open(p(e.sessionId),"_blank"),children:s("automations.openSession")})]},e.id)})})]})})]}),(0,r.jsx)(ay,{status:null!==a?(0,r.jsx)(ak,{summary:s("automations.footerCount",{count:a.length})}):void 0,children:!t&&E&&(0,r.jsx)(aj,{onClick:E,children:s("i18n.close")})})]})}var pQ=n(75702);let p0=[{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 p1(){let{t:e}=(0,eX.s)(),t=(0,ro.VE)();return(0,r.jsx)("div",{className:"settings-font-rows",children:p0.map(n=>{let{kind:i,label:s,placeholder:a,reset:o,weightLabel:l}=n,d=t[`${i}Weight`],c=pQ.qI.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(a),maxLength:pQ.zx,"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(l)}: ${d}`,children:e(pQ.qI[c].label)}),(0,r.jsx)(aj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(o),"aria-label":e(o),disabled:!t[i]&&d===pQ.Fj,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:pQ.qI[0].value,max:pQ.qI[pQ.qI.length-1].value,step:100,value:d,"aria-label":e(l),"aria-valuetext":`${d} ${e(pQ.qI[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function p2(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"})]}):"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"})]}):"channels"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m21.5 4.5-2.9 13.2a1.6 1.6 0 0 1-2.5.9L12 15.6l-2.3 2.3a1 1 0 0 1-1.7-.5L7 13.6 3.4 12.2a.8.8 0 0 1-.1-1.5L20.2 3.2a.9.9 0 0 1 1.3 1.3Z"}),(0,r.jsx)("path",{d:"m7 13.6 11.7-8.4L9.4 14.8"})]}):"automations"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3.5 2"})]}):(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 p4(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:a}=e,{locale:o,setLocale:l,supportedLocales:d,t:c}=(0,eX.s)(),{preference:u,setThemePreference:p}=(0,sg.D)(),{width:h,setWidth:m,fontSize:g,setFontSize:f}=(0,ra.Uh)(),x=rs(),b=eY(),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(null),[E,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,_]=(0,i.useState)(null),[H,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),[Y,X]=(0,i.useState)("");(0,i.useEffect)(()=>{T((0,sI.ql)()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>V(e?.enabled===!0)).catch(()=>{})},[]);let Q=async()=>{G(!0),X("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{X(c("auth.logoutFailed"))}finally{G(!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||R(!0===n.enabled)}).catch(t=>{e||z(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/auto-title").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||W(!0===n.enabled)}).catch(t=>{e||_(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let ee=async e=>{L(!0),z(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}`);R(!0===i.enabled),t&&n()}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}},et=async e=>{D(!0),_(null);try{let t=await fetch("/api/auto-title",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);W(!0===n.enabled)}catch(e){_(e instanceof Error?e.message:String(e))}finally{D(!1)}},en=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 ic(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{j(!1)}},er=async(e,t)=>{if(v){N(!0),$(null);try{let n=t?[...v.builtinTools,e]:v.builtinTools.filter(t=>t!==e),r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({builtinTools:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i)}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(!1)}}},ei=async()=>{if(!H){U(!0),K(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 ol(o))throw Error("unsupported or not permitted");K({kind:"ok",message:c("settings.pushRegistered")})}catch(e){K({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{U(!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:sf.F$.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)(p1,{}),(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:[g,"px"]}),(0,r.jsx)(aj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:g===ra.NN,onClick:()=>f(ra.NN),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:ra.WH,max:ra.Oi,step:1,value:g,onChange:e=>f(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)(aj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:h===ra.mi,onClick:()=>m(ra.mi),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:ra.lg,max:ra.fI,step:10,value:h,onChange:e=>m(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)(aw,{checked:E,label:c("settings.thinkingExpandedDefault"),onChange:e=>{(0,sI.kF)(e),T(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)(aw,{checked:s,label:c("settings.quoteSelection"),onChange:a})]}),(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:()=>ri("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:()=>ri("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)(aw,{checked:!0===M,loading:null===M&&!P||A,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void ee(e)})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.autoTitle")}),(0,r.jsx)(aw,{checked:!1!==O,loading:null===O&&!B||F,label:c("settings.autoTitle"),describedBy:"settings-auto-title-description",onChange:e=>void et(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),P&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:P}),(0,r.jsx)("p",{id:"settings-auto-title-description",className:"settings-general-description",children:c("settings.autoTitleDescription")}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]}),(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"===b,onChange:()=>eG("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"===b,onChange:()=>eG("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")})]}),v&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.builtinTools")}),(0,r.jsx)("p",{id:"settings-builtin-tools-description",className:"settings-general-description",children:c("settings.builtinToolsDescription")}),(0,r.jsx)("div",{className:"settings-send-mode-options settings-builtin-tools",role:"group","aria-label":c("settings.builtinTools"),"aria-describedby":"settings-builtin-tools-description",children:ik.kt.map(e=>(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"checkbox",checked:v.builtinTools.includes(e),disabled:C,onChange:t=>void er(e,t.target.checked),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:"bash"===e&&v.powerShellEnabled?"powershell":e})]},e))}),I&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:I})]}),v?.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)(aw,{checked:v.powerShellEnabled,loading:k,label:c("settings.usePowerShell"),onChange:e=>void en(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}),(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:H,onClick:()=>void ei(),children:H?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),q&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===q.kind?{color:"var(--accent)"}:void 0,children:q.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:()=>l(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)})})]}),Z&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(aj,{variant:"secondary",disabled:J,onClick:()=>void Q(),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"})}),J?c("auth.loggingOut"):c("auth.logOut")]}),Y&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:Y})]})]})}let p8={home:"home",section:"home",detail:"section"},p6={home:0,section:1,detail:2},p3="cubic-bezier(0.2, 0.8, 0.2, 1)";function p5(e){let t,{cwd:n,sessionId:s,initialSection:a,openAtHome:o=!1,onClose:l,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u,projectTrust:p,onOpenTrustDialog:h,onProjectTrustChanged:m}=e,{t:g}=(0,eX.s)(),[f,x]=(0,i.useState)(a),[b,v]=(0,i.useState)(()=>new Set([f])),y=[{id:"general",label:g("settings.general")},{id:"models",label:g("common.models")},{id:"skills",label:g("common.skills")},{id:"agents",label:g("common.agents")},{id:"plugins",label:g("common.plugins")},{id:"mcp",label:g("settings.mcp")},{id:"channels",label:g("settings.channels")},{id:"automations",label:g("settings.automations")}].map(e=>({...e,requiresProject:sy(e.id)})),k=sy(f),j=(0,eQ.a)(),w=function(e,t){let[n,r]=(0,i.useState)(t?"home":"section");e||"section"===n||r("section");let s=(0,i.useRef)(n);s.current=n;let a=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;let t=()=>{0!==a.current&&(a.current-=1,r(e=>p8[e]))};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]);let o=(0,i.useCallback)(t=>{e&&(window.history.pushState(window.history.state,""),a.current+=1,r(t))},[e]);return{level:n,levelRef:s,enter:o,goUp:(0,i.useCallback)(()=>{a.current>0?window.history.back():r(e=>p8[e])},[]),dropHistory:(0,i.useCallback)(()=>{let e=a.current;a.current=0,e>0&&window.history.go(-e)},[])}}(j,o),{dropHistory:S,enter:C,goUp:N,levelRef:I}=w,$=(0,i.useRef)(null),E=(0,i.useRef)(null),T=(0,i.useRef)(w.level);(0,i.useLayoutEffect)(()=>{let e=T.current;T.current=w.level,j&&e!==w.level&&function(e,t,n,r){if(!e||"function"!=typeof e.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let i=p6[r]>p6[n];e.animate(i?[{transform:"translateX(100%)",boxShadow:"-12px 0 24px rgba(0, 0, 0, 0.12)"},{transform:"translateX(0)",boxShadow:"-12px 0 24px rgba(0, 0, 0, 0)"}]:[{transform:"translateX(-30%)",opacity:.4},{transform:"translateX(0)",opacity:1}],{duration:280,easing:p3}),t?.querySelectorAll(".settings-phone-back, .settings-dialog-title").forEach(e=>{e.animate([{opacity:0,transform:`translateX(${i?16:-16}px)`},{opacity:1,transform:"translateX(0)"}],{duration:220,easing:p3})})}(E.current,$.current,e,w.level)},[j,w.level]);let M=(0,i.useCallback)(()=>{S(),l()},[l,S]),R=y.find(e=>e.id===f)?.label??g("settings.title"),[A,L]=(0,i.useState)(null),P=(0,i.useMemo)(()=>({detailOpen:"detail"===w.level,openDetail:()=>{"section"===I.current&&(L(null),C("detail"))},closeDetail:()=>{"detail"===I.current&&N()},reportDetailTitle:L}),[C,N,w.level,I]);(0,i.useEffect)(()=>sS(a),[a]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eI(e)||(e.preventDefault(),M())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[M]);let z=(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,z.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!n&&k&&(x("general"),v(e=>new Set(e).add("general")),sS("general"))},[n,k]);let O=e=>{v(t=>new Set(t).add(e)),x(e),sS(e)},W=(e,t)=>b.has(e)?(0,r.jsx)("div",{hidden:f!==e||"home"===w.level,"data-phone-level":j?w.level:void 0,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:z,role:"dialog","aria-modal":"true","aria-label":g("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&M()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{ref:$,className:"settings-dialog-header",children:[j&&"home"!==w.level&&(t="detail"===w.level?R:g("settings.title"),(0,r.jsxs)("button",{type:"button",className:"settings-phone-back",onClick:N,"aria-label":g("settings.backTo",{name:t}),children:[(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)("span",{children:t})]})),(0,r.jsx)("strong",{className:"settings-dialog-title",children:j&&"home"!==w.level?"section"===w.level?R:A:g("settings.title")}),(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-section-tabs",children:y.map(e=>{let t=f===e.id,i=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?g("settings.projectRequired"):e.label,"aria-current":t?"page":void 0,onClick:()=>O(e.id),children:[(0,r.jsx)(p2,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:M,title:g("i18n.close"),"aria-label":g("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{ref:E,className:"settings-dialog-main",children:[j&&"home"===w.level&&(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-phone-home",children:y.map(e=>{let t=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-phone-home-item",disabled:t,"aria-describedby":t?`settings-phone-home-${e.id}-note`:void 0,onClick:()=>{O(e.id),C("section")},children:[(0,r.jsx)(p2,{section:e.id,size:20}),(0,r.jsxs)("span",{className:"settings-phone-home-label",children:[(0,r.jsx)("span",{children:e.label}),t&&(0,r.jsx)("span",{id:`settings-phone-home-${e.id}-note`,className:"settings-phone-home-note",children:g("settings.projectRequired")})]}),(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",className:"settings-phone-home-chevron",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]},e.id)})}),(0,r.jsxs)(s0.Provider,{value:P,children:[W("general",(0,r.jsx)(p4,{sessionId:s,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u})),W("models",(0,r.jsx)(oa,{embedded:!0,cwd:n,onClose:M})),n&&W("skills",(0,r.jsx)(ob,{embedded:!0,cwd:n,trust:p,onClose:M},n)),n&&W("agents",(0,r.jsx)(oM,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:M,onReloaded:d},n)),n&&W("plugins",(0,r.jsx)(oU,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:M,onReloaded:d},n)),W("mcp",(0,r.jsx)(pw,{embedded:!0,cwd:n,trust:p,onTrustProject:h,onProjectTrustChanged:m,onClose:M},n??"")),W("channels",(0,r.jsx)(pU,{})),W("automations",(0,r.jsx)(pX,{}))]})]})]})})}let p9="project-trust-mcp-status";function p7(e){let{cwd:t,busy:n,error:s,onCancel:a,onConfirm:o,onStatus:l}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(l);return(0,i.useEffect)(()=>{u.current=l},[l]),(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)(he,{cwd:t,busy:n,error:s,listing:d,onCancel:a,onConfirm:o})}function he(e){let{cwd:t,busy:n,error:s,listing:a,onCancel:o,onConfirm:l}=e,{t:d}=(0,eX.s)(),c="loading"===a.state,u="loaded"===a.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(a.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),m=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current=n,m.current=o},[n,o]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||m.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eI(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:oV(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===a.state&&void 0!==a.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:oV(a.statusError)})]}),(0,r.jsx)(hn,{listing:a})]})]}),s&&(0,r.jsx)(ht,{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:l,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?p9:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function ht(e){let{error:t}=e,{t:n}=(0,eX.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:oV(t.error)})]})}function hn(e){let{listing:t}=e,{t:n}=(0,eX.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:p9,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:oV(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)(hr,{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)(ha,{server:e},e.name))})]}):null}function hr(e){let{file:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=o8(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 hi(e){let{fields:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=o0(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function hs(e){let{server:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:o4(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=o0(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 ha(e){let t,{server:n}=e,{t:i}=(0,eX.s)(),s=oX(n),a=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:oV(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:oV(n.cwd)})}),oQ(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:oV(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(hi,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),a&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(hi,{fields:n.commandFields})]}),a&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(o1(n))," ",(0,r.jsx)(hs,{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=o2(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 ho(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function hl(e){let t=e,n=t.branchPreview,r=ho(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&ho(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function hd(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 hc(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:a,onSelect:o}=e,{node:l,skipped:d,branchPreview:c,labelEntry:u}=hl(t),p=n.has(l.entry.id),h=n.has(t.entry.id)||n.has(l.entry.id),m=c?.text??function(e){if("message"===e.type&&ho(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),g=c?c.role??null:ho(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(l.entry.id):void 0,children:[a.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"}}),g&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===g?"var(--accent)":"var(--text-dim)",background:"user"===g?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===g?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===g?"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:m})]}),l.children.map((e,t)=>(0,r.jsx)(hc,{node:e,activePathIds:n,depth:i+1,isLast:t===l.children.length-1,parentLines:[...a,!s],onSelect:o},e.entry.id))]})}function hu(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:a,containerRef:o,open:l,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:m}=(0,eX.s)(),[g,f]=(0,i.useState)(!1),x=void 0!==l?l:g,b=(0,i.useRef)(null),[v,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!a)return;let e=o?.current??b.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,a,o]);let k=(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]),w=h?void 0:j,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:m("i18n.branchesLockedWhileRunning")}),C=c?hd(t)?null:m("i18n.noBranches"):m("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=hl(e[0]).node;return t.children.length>1?t.children:[]}(t),I=!C&&N.length>0,$=(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:I?"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"})]}),E=(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 a?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:b,onClick:()=>d?d():f(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:m("i18n.branches"),"aria-label":m("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:m("i18n.branches")})]}),x&&v&&(0,r.jsx)("div",{style:{position:"fixed",top:v.top,left:v.left,width:v.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hc,{node:e,activePathIds:k,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},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:()=>f(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:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:m("i18n.branches")}),E]}),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:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hc,{node:e,activePathIds:k,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??m("i18n.noBranches")})})]})}function hp(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:`
|
|
7
|
+
${r=null===l.number?l.marker:`${String(Number(l.number)+1).padStart(l.number.length,"0")}${l.delimiter}`,`${l.indent}${r}${l.spacing}${l.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)(()=>()=>{tf.current.forEach(rz)},[]),(0,i.useLayoutEffect)(()=>{if(eq){let e=e=>{e.target!==eV.current&&(eV.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=eV.current;eV.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[eq]);let tS=(0,i.useCallback)(async e=>{if(ey.length||!e.startsWith("/")||!G)return!1;if(eZ.current)return!0;eV.current=document.activeElement===e3.current?e3.current:null,eZ.current=!0,eK(!0);try{var t,n;let r=await G(e);if(!r.handled)return!1;return r.error||(t=tg.current,n=tf.current.length,0!==n||t.trim()!==e)||tj(),!0}finally{eZ.current=!1,eK(!1)}},[ey.length,tj,G]),tC=(0,i.useCallback)(async()=>{var e;let t=ep.trim();(t||ey.length)&&(Q?.(),(!m||rC(e=t)||n6(e))&&await tS(t)||(!m||t.startsWith("!")&&!ey.length)&&(tj(),d(t,ey.length?ey:void 0)))},[ep,ey,m,tS,d,tj,Q]),tN=!ei&&ep.startsWith("/")&&!/\s/.test(ep.slice(1))?ep.slice(1).toLowerCase():null,tI=(()=>{var e;let t,n;return null===tN?[]:(e=[...m?rS.filter(e=>e.availableWhileStreaming):rS,...Z??[]],((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)===tN||t===tN?0:n.startsWith(tN)||t.startsWith(tN)?1:t.includes(tN)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return rE(t,es).toLowerCase().includes(tN)})).sort((e,t)=>e.rank-t.rank||r$[e.command.source]-r$[t.command.source]||rm.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t}))})(),{commands:t$,groups:tE}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=rN.map(i=>{let s=e.filter(e=>e.source===i),a="skill"!==i||n?s:[...s.filter(e=>!rT(e,t)),...s.filter(e=>rT(e,t))];return{source:i,items:a.map(e=>({command:e,index:r++}))}}).filter(e=>e.items.length>0);return{commands:i.flatMap(e=>e.items.map(e=>{let{command:t}=e;return t})),groups:i}}(tI,e6,tN??""),tT=1===tI.length?es(tN?"chat.match":"chat.command"):es(tN?"chat.matches":"chat.commands",{count:tI.length}),tM=!!ep.trim()||ey.length>0,tR=ei||ed&&m,tA=ey.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)&&!eF;(0,i.useEffect)(()=>{0===ey.length&&eD(!1)},[ey.length]);let tL=(0,i.useCallback)((e,t)=>{if(!en)return void eR(null);let n=t??e.length;eR((0,nX.RO)(e.slice(0,n)))},[en]),tP=eM?.query??null,tz=i.useMemo(()=>null!==tP&&eJ&&eJ.cwd===en?(0,nX.R7)(eJ.entries,tP):[],[tP,eJ,en]),tO=!!(tP&&eJ?.truncated&&eJ.cwd===en);(0,i.useEffect)(()=>{if(!tO||!en||!tP)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(en)}&q=${encodeURIComponent(tP)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e2({cwd:en,query:tP,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tO,tP,en]);let tW=tO&&null!==e1&&e1.cwd===en&&e1.query===tP,tF=tW?e1.matches:tz,tD=null===eM?null:`${eM.start}:${+!!eM.quoted}:${eM.query}`;(0,i.useEffect)(()=>{if(null===tD){eL(!1),eW(0);return}eL(!0),eW(0)},[tD]);let tB=null!==eM;(0,i.useEffect)(()=>{if(!tB||!en)return;let e=tp.current;e&&e.cwd===en&&Date.now()-e.fetchedAt<1e4||th.current===en||(th.current=en,e0(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(en)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:en,entries:(0,nX.Yh)(e.files??[]),truncated:!!e.truncated}),tp.current={cwd:en,fetchedAt:Date.now()}}).catch(()=>{tp.current=null}).finally(()=>{th.current=null,e0(!1)}))},[tB,en]);let t_=(0,i.useCallback)(e=>{if(!eM)return;let t=e3.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eM.quoted&&'"'===t.value[n]?1:0),i=(0,nX.W)(e.path,e.isDir,eM.quoted),s=eM.start+i.cursorOffset;rx(t,eM.start,r,i.text,i.cursorOffset),eR((0,nX.RO)(t.value.slice(0,s)))},[eM]);(0,i.useEffect)(()=>{eO>=tF.length&&eW(Math.max(0,tF.length-1))},[tF.length,eO]),(0,i.useEffect)(()=>{tc.current.length=tF.length},[tF.length]),(0,i.useEffect)(()=>{eA&&tc.current[eO]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eO,eA]),(0,i.useEffect)(()=>{eH>=q.length&&eU(Math.max(0,q.length-1))},[q.length,eH]),(0,i.useEffect)(()=>{tu.current.length=q.length},[q.length]),(0,i.useEffect)(()=>{eB&&tu.current[eH]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eH,eB]);let tH=(0,i.useCallback)(e=>{eh(e),e_(!1),eU(0),eR(null),requestAnimationFrame(()=>{let t=e3.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),rb(t),rv(t))})},[]),tU=(0,i.useCallback)(e=>{let t=`/${e.name} `;eh(t),eN(!1),e$(0),requestAnimationFrame(()=>{let e=e3.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),rb(e))})},[]),tq=(0,i.useCallback)(()=>{let e=ep.trim();e&&!ey.length&&p&&(tj(),p(e))},[ep,ey,p,tj]),tK=(0,i.useCallback)(e=>{let t=ep.trim();if(!t&&!ey.length)return;if(t.startsWith("!")&&!ey.length)return void tC();Q?.();let n=ey.length?ey:void 0,r=()=>{if(t.startsWith("/")&&ee){tj(),ee(t,"steer"===e?"steer":"followUp",n);return}tj(),"steer"===e&&u?u(t,n):"followup"===e&&h&&h(t,n)};!ey.length&&G&&rC(t)?tS(t):!ey.length&&G&&n6(t)?tS(t).then(e=>{e||r()},()=>r()):r()},[ep,ey,G,ee,u,h,tj,Q,tS,tC]),tZ=(0,i.useCallback)(e=>{let t=t$.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eI-1);if("right"===e)return Math.min(t,eI+1);let n=to.current[eI];if(!n)return"down"===e?Math.min(t,eI+1):Math.max(0,eI-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eI)continue;let t=to.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-s;if("down"===e?l<=4:l>=-4)continue;let d=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);d<o&&(a=n,o=d)}return a>=0?a:"down"===e?Math.min(t,eI+1):Math.max(0,eI-1)},[t$.length,eI]),tV=(0,i.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ed||"ctrlEnter"===eu?n&&(e.ctrlKey||e.metaKey):n,i=ed?r:n,s=Date.now()-tr.current<100,a=tn.current||t.isComposing||229===t.keyCode;if(i&&(a||s)){s&&e.preventDefault();return}if(eB&&!a){if("ArrowDown"===e.key){e.preventDefault(),eU(e=>Math.min(Math.max(0,q.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eU(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e_(!1);return}if(("Tab"===e.key||i)&&q[eH]){e.preventDefault(),tH(q[eH]);return}}if(eC&&null!==tN){if("ArrowDown"===e.key){e.preventDefault(),e$(tZ("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e$(tZ("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e$(tZ("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e$(tZ("left"));return}if("Escape"===e.key){e.preventDefault(),eN(!1);return}let t=t$[eI];if("Tab"===e.key&&t){e.preventDefault(),tU(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 n8(t)&&n6(e)}(ep,t,m)?(eN(!1),tC()):tU(t);return}}if(eA&&null!==eM&&!a){if("ArrowDown"===e.key){e.preventDefault(),eW(e=>rg(e,tF.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eW(e=>rg(e,tF.length,-1));return}if("Escape"===e.key){e.preventDefault(),eL(!1);return}if(("Tab"===e.key||i)&&tF[eO]){e.preventDefault(),t_(tF[eO]);return}}if("ArrowUp"===e.key&&!a&&!m&&q.length>0&&0===ep.trim().length){e.preventDefault(),eN(!1),eL(!1),eU(q.length-1),e_(!0);return}if("Escape"===e.key&&!a&&m&&c){e.preventDefault(),c();return}r&&(e.preventDefault(),m&&(u||h)?tK(e.altKey&&h||!u?"followup":"steer"):tC())},[ed,eu,m,u,h,c,eC,tN,t$,eI,tU,tK,tC,tZ,eA,eM,tF,eO,t_,eB,q,eH,tH,ep]),tJ=(0,i.useCallback)(()=>{ti.current=null;let e=e3.current;e&&rb(e)},[]),tG=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!ei&&t.length){e.preventDefault(),tb(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(r){let t=e.currentTarget,n=e.nativeEvent,i=t.selectionStart,s=t.selectionEnd,a={};ti.current=a,setTimeout(()=>{ti.current===a&&(ti.current=null,!n.defaultPrevented&&t.isConnected&&rx(t,i,s,r))},0)}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:a,occurrence:o}of t){if(!s||!a)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 l=s.replace(/([\\[\]])/g,"\\$1"),d=a.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${l}](${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 a=e.currentTarget,o=a.selectionStart,l=a.value.slice(0,o)+s+a.value.slice(a.selectionEnd);e.preventDefault(),tg.current=l,eh(l),e_(!1),tL(l,o+s.length),requestAnimationFrame(()=>{a.focus(),a.setSelectionRange(o+s.length,o+s.length),rv(a)})},[ei,tb,tL]);(0,i.useEffect)(()=>{if(null===tN){eN(!1),e$(0),ts.current=!1;return}eN(!0),e$(0),!ts.current&&J&&(ts.current=!0,Promise.resolve(J()).catch(()=>{ts.current=!1}))},[tN,J]),(0,i.useEffect)(()=>{if(!eC||!en)return;let e=!1;return e8({cwd:en,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(en)}`).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;e8({cwd:en,values:n})}).catch(()=>{e||e8({cwd:en,values:{}})}),()=>{e=!0}},[eC,en]),(0,i.useEffect)(()=>{eI>=t$.length&&e$(Math.max(0,t$.length-1))},[t$.length,eI]),(0,i.useEffect)(()=>{to.current.length=t$.length},[t$.length]),(0,i.useEffect)(()=>{eC&&to.current[eI]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eI,eC]),(0,i.useLayoutEffect)(()=>{if(!eC||null===tN)return void eT(null);let e=ta.current;if(e)return ry(e,e=>{eT(t=>t===e?t:e)})},[eC,tN]),(0,i.useLayoutEffect)(()=>{if(!eA||null===eM)return void ez(null);let e=td.current;if(e)return ry(e,e=>{ez(t=>t===e?t:e)})},[eA,eM]);let tY=b&&b.length>0?b.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})):Object.entries(x??{}).map(e=>{let[t,n]=e;return{provider:g?.provider??"unknown",modelId:t,name:n}}),tX=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,tQ=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:es("chat.compacted")} ${rw(A.tokensBefore)} -> ${rw(A.estimatedTokensAfter)} tokens (${es("chat.tokensSaved",{saved:rw(tX)})})`:null,t0=z&&"auto"!==z?z:null,t1="auto"!==(n=t0??"auto")&&D?D[n]??n:n,t2=Object.entries(rh).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",t4="chat-only"===t2?es("chat.chatOnly"):t2;(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&eg(!1),e9.current&&!e9.current.contains(e.target)&&ex(!1),e7.current&&!e7.current.contains(e.target)&&ev(!1),!te.current||te.current.contains(e.target)||e3.current?.contains(e.target)||e_(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{m&&eg(!1)},[m]);let t8=(0,i.useRef)(-1/0);(0,i.useLayoutEffect)(()=>{if(m)return()=>{t8.current=performance.now()}},[m]);let t6=e=>{var t,n;return t=e.detail,n=performance.now()-t8.current,t>0&&n<600};return(0,i.useEffect)(()=>{ed||ev(!1)},[ed]),(0,r.jsxs)("fieldset",{disabled:eq,"aria-busy":eq,className:ei?void 0:"chat-input-shell",style:{...ei?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:ei?0:"0 16px 8px",paddingRight:ei?0:ed?16:52,opacity:eq?.5:1,transition:"opacity 0.15s"},children:[!ei&&(0,r.jsx)("input",{ref:tt,type:"file",accept:er?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tv}),(0,r.jsxs)("div",{style:{...ei?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(rF,{cwd:y}),(0,r.jsx)(rD,{error:v}),(0,r.jsx)(rB,{warnings:k}),tA&&(s=b?.find(e=>e.provider===g?.provider&&e.id===g?.modelId),(0,r.jsx)(rW,{tone:"warning",title:es("chat.imageNotSupportedTitle"),body:es("chat.imageNotSupportedBody",{model:s?.name||g?.modelId||""}),onClose:()=>eD(!0)})),(U?.steering.length??0)+(U?.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:es("chat.queued",{count:(U?.steering.length??0)+(U?.followUp.length??0)})}),K&&(0,r.jsxs)("button",{onClick:K,title:es("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"})]}),es("chat.recall")]})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[U?.steering.map((e,t)=>(0,r.jsx)(rO,{kind:"steer",text:e},`steer-${t}`)),U?.followUp.map((e,t)=>(0,r.jsx)(rO,{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"})]}),es("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:R?"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:R?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:M}),R&&(0,r.jsx)(tl.R,{onClick:R,title:es("chat.dismissCompactError")})]}),ey.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ey.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(n5.k,{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:()=>ty(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:[eB&&q.length>0&&(0,r.jsxs)("div",{ref:te,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:es("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:q.map((e,t)=>{let n=t===eH;return(0,r.jsxs)("button",{ref:e=>{tu.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tH(e)},onMouseEnter:()=>eU(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}`)})})]}),eC&&null!==tN&&(0,r.jsxs)("div",{ref:ta,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===eE?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eE}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?es("chat.loadingCommands"):es("chat.slashCommands",{label:tT})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:V||0!==tI.length?tE.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:es(rI[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===eI,s=rT(t,e6);return(0,r.jsxs)("button",{ref:e=>{to.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tU(t)},onMouseEnter:()=>e$(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:es("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:rE(t,es)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:es("chat.noCommands")})})]}),eA&&null!==eM&&(a=eY&&(!eJ||eJ.cwd!==en),o=1===tF.length?es("chat.match"):es("chat.matches",{count:tF.length}),l=eJ?.truncated&&!tW?eM.query?es("chat.searchingAll"):es("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:td,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===eP?"min(48vh, 400px)":`min(48vh, 400px, ${eP}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?es("chat.loadingFiles"):es("chat.files",{label:o,hint:l})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:a||0!==tF.length?tF.map((e,t)=>{let n=t===eO,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tc.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eW(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)(n3.sj,{size:14}):(0,n3.I3)(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&&!tW?es("chat.searching"):es("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:tR?void 0:"chat-composer-row",style:{minWidth:0,display:"flex",flexDirection:tR?"column":"row",gap:8,alignItems:tR?"stretch":"center",background:"var(--bg)",border:ei?"none":`1px solid ${ew?"var(--tool-bg)":m&&(u||h)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!ei,padding:ei?0:ed?"6px 6px 6px 12px":"10px 10px 10px 14px",boxShadow:ei?"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:e3,className:"chat-input-textarea","aria-label":ei?es("chat.askInSideChat"):void 0,value:ep,onChange:e=>{tg.current=e.target.value,eh(e.target.value),e_(!1),tL(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tL(t.value,t.selectionStart)},onKeyDown:tV,onCompositionStart:()=>{tn.current=!0},onCompositionEnd:e=>{tn.current=!1,tr.current=Date.now();let t=e.currentTarget;tL(t.value,t.selectionStart)},onInput:tJ,onPaste:tG,placeholder:T?es("chat.compactingPlaceholder"):m&&(u||h)?es("chat.steerPlaceholder"):m?es("chat.agentPlaceholder"):es("chat.messagePlaceholder"),rows:1,style:{flex:tR?"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:ei?96:24,maxHeight:200,overflow:"auto"}}),m&&!ew?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[p&&(0,r.jsx)("button",{type:"button",onClick:tq,disabled:!ep.trim()||ey.length>0,title:es("chat.sideChatHint"),"aria-label":es("chat.sideChat"),className:`bg-transparent ${ep.trim()&&!ey.length?"cursor-pointer text-text-muted hover:bg-bg-hover hover:text-text":"cursor-not-allowed text-text-dim"}`,style:{width:38,display:"grid",placeItems:"center",padding:0,border:"1px solid var(--border)",borderRadius:8,transition:"background 0.12s"},children:(0,r.jsxs)("svg",{width:"17",height:"17",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:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"}),(0,r.jsx)("path",{d:"M13 8.5v7M9.5 12h7"})]})}),u&&(0,r.jsxs)("button",{onClick:()=>tK("steer"),disabled:!tM,title:es("chat.steerHint"),"aria-label":es("chat.steer"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tM?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tM?"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"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:es("chat.steer")})]}),h&&(0,r.jsxs)("button",{onClick:()=>tK("followup"),disabled:!tM,title:`${es("chat.followUpHint")} (${ed?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":es("chat.followUp"),"aria-keyshortcuts":ed?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tM?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tM?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tM?"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"})]}),(0,r.jsx)("span",{className:"chat-composer-run-label",children:es("chat.followUp")})]})]}):(0,r.jsxs)("button",{onClick:tC,disabled:!ep.trim()&&!ey.length,title:es("chat.send"),"aria-label":es("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ed?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ep.trim()||ey.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ep.trim()||ey.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ep.trim()||ey.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ep.trim()||ey.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"})]}),!ed&&es("chat.send")]})]})]}),ew&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eS?"var(--text-muted)":"var(--accent)",marginTop:4},children:[es("chat.shell")," \xb7 ",eS?es("chat.outputLocal"):es("chat.outputModel")]}),!ei&&(0,r.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ed?4:8,display:ed?"grid":"flex",gridTemplateColumns:ed?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ed?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>tt.current?.click(),title:es("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:ec,height:ec,padding:0,background:"none",border:"none",borderRadius:9,color:ey.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=ey.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ey.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:ed?18:15,height:ed?18: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"})]})}),(tY.length>0||g||v)&&S&&(0,r.jsx)(rc,{options:tY,value:g,onChange:S,onReselect:S,busy:C,isAutoSelection:f,defaultValue:N,onSetDefault:I,allOptions:j?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:w})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:e7,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto"},children:[ed&&(0,r.jsx)("button",{type:"button",title:eb?void 0:es("chat.moreControls"),"aria-label":es("chat.moreControls"),"aria-expanded":eb,"aria-hidden":eb||void 0,tabIndex:eb?-1:void 0,onClick:()=>{ev(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:ec,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eb?"default":"pointer",fontSize:12,fontWeight:500,visibility:eb?"hidden":"visible",pointerEvents:eb?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eb||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:es("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ed?eb?"flex":"none":"flex",alignItems:"center",gap:ed?1:2,...ed?{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:e9,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ex(e=>!e),title:m?es("chat.currentReasoning",{level:t1}):es("chat.changeReasoning",{level:t1}),"aria-label":es("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,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"})]}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t1})]}),ef&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ed?{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:rk.filter(e=>!F||"auto"===e||F.includes(e)).map(e=>{let t="auto"===e?O:!O&&t0===e,n=es(rj[e]),i="auto"!==e&&D?D[e]:void 0,s=null!=i&&i!==e?i:e,a=null!=i&&i!==e;return(0,r.jsxs)(rd,{active:t,onSelect:()=>{if(ex(!1),"auto"===e){O||W("auto");return}(!t||O)&&W(e)},gutter:!!_,star:_&&"auto"!==e?{isDefault:B===e,saveLabel:es("chat.saveDefaultThinking"),defaultLabel:es("chat.defaultThinking"),onSave:()=>{ex(!1),_(e)}}:void 0,children:[(0,r.jsxs)("span",{style:{flex:1},children:[s,a&&(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&&P&&(0,r.jsxs)("div",{ref:e5,style:{position:ed?"static":"relative"},children:[(0,r.jsxs)("button",{onClick:e=>{m||t6(e)||eg(e=>!e)},disabled:m,title:es("chat.changeToolPreset")+`: ${t4}`,"aria-label":es("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:em?"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=em?"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"})}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t4})]}),em&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ed?"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:rp.map(e=>{let t,n=rh[e],i=(L??"configured")===n;return t="configured"===e?es("chat.configuredTools"):"chat-only"===e?es("chat.chatOnly"):"read-only"===e?es("chat.readOnlyTools",{count:4}):"default"===e?es("chat.builtInTools",{count:4}):es("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{eg(!1),i||P(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||T)&&$&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:T?E:e=>{t6(e)||$()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ed?"0 10px":"8px 12px",width:ed?"auto":void 0,height:ec,background:T?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:T?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=T?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=T?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=T?"#ef4444":"var(--text-muted)"},title:T?es("chat.stopCompaction"):es("chat.compactContext"),"aria-label":T?es("chat.stopCompaction"):es("chat.compactContext"),children:T?(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"})}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:es("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"})]}),(!ed||eb)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:es("chat.compact")})]})})}),m&&(0,r.jsxs)("button",{onClick:c,title:es("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:ec,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"})}),es("chat.stop")]}),void 0!==X&&(0,r.jsx)("button",{onClick:X,title:Y?es("chat.disableSound"):es("chat.enableSound"),"aria-label":Y?es("chat.disableSound"):es("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:ec,height:ec,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"})]})}),ed&&eb&&(0,r.jsx)("button",{type:"button",title:es("chat.collapseControls"),"aria-label":es("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eg(!1),ex(!1),ev(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ed?ec:36,height:ec,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"})]})})]})]})]})]})]})}));var rH=n(19109),rU=n(32316),rq=n(88374),rK=n(68925);let rZ="pi-web:minimap-preview-locked";function rV(){try{return window.localStorage}catch{return null}}function rJ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rV();if(!e)return!1;try{return"true"===e.getItem(rZ)}catch{return!1}}var rG=n(88576),rY=n.n(rG);function rX(e){let{level:t,children:n,headingIndex:i,onClick:s}=e;return(0,r.jsx)("button",{type:"button",className:rY().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 rQ=[...rK.iA??[],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]:[]}}],r0=[[rq.A,{throwOnError:!1,strict:!1}]];function r1(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 r2=(0,i.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:s}=e,a=(0,i.useMemo)(()=>(0,rK.Ep)(t),[t]);return t?(0,r.jsx)("div",{className:rY().outline,children:(0,r.jsx)(rU.oz,{remarkPlugins:rQ,rehypePlugins:r0,components:{h1:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rX,{level:1,headingIndex:r1(i),onClick:n,children:t})},h2:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rX,{level:2,headingIndex:r1(i),onClick:n,children:t})},h3:e=>{let{children:t,node:i}=e;return(0,r.jsx)(rX,{level:3,headingIndex:r1(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:rY().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:a})}):null}),r4=(0,i.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:s,messageRefs:a,onRevealHistory:o,turnsBefore:l}=e,{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(600),[b,v]=(0,i.useState)(!1),[y,k]=(0,i.useState)(rJ),[j,w]=(0,i.useState)(null),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),N=(0,i.useRef)([]),I=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),$=(0,i.useRef)(null),E=(0,i.useRef)(new Map),T=(0,i.useRef)(null),M=(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,f),[p,f]),{nodes:P,gap:z}=L;I.current=L;let O=(0,i.useCallback)(e=>{M.current={index:e,until:Date.now()+1600},g(e)},[]),W=(0,i.useCallback)((e,t)=>{let n=M.current;if(n&&Date.now()<n.until)return void g(n.index);M.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void g(null);let i=e.scrollTop+.3*e.clientHeight;g(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),W(e,n)},[s,W]),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=a.current,i=e.getBoundingClientRect(),o=[],l=0,d=null,c=n();for(let t of c?[...A.current,c]:A.current){let n=(0,nb.Y0)(t);if(!n&&"assistant"!==t.role)continue;let s=r?.[l];if(l++,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 a=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=(0,nb.dQ)(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);a&&d.assistantPreviews.push({markdown:a,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),W(e,p);let m=R.current,g=m?p[m.nodeIndex]:null;if(m&&g){let t=void 0===m.assistantIndex?null:g.targetTurn.assistantPreviews[m.assistantIndex],n=g.targetTurn.scrollTop;if("assistant"===m.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===m.target){let r=void 0===m.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(m.headingIndex),s=r?.getBoundingClientRect();n=s?s.top-i.top+e.scrollTop:null}if(null===n)return;R.current=null,O(g.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,O,a,s,W]);(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 _=(0,i.useCallback)((e,t)=>{let n=s.current;if(!n)return;if(O(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})},[O,o,s]),H=(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(),a=r.getBoundingClientRect().top-i.top+n.scrollTop-.3*n.clientHeight;O(e.index),n.scrollTo({top:Math.max(0,a),behavior:"smooth"})},[O,o,s]),U=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=I.current,i=C.current?.clientHeight??0;if(0===t.length||i<=0)return null;let s=Math.max(0,Math.min(i,e*i)),a=t[0].topRatio*i,o=n>0?Math.round((s-a)/n):0,l=Math.max(0,Math.min(t.length-1,o)),d=t[l];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 a=i.querySelectorAll("h1, h2, h3").item(n);if(!a)return;let l=r.getBoundingClientRect(),d=a.getBoundingClientRect().top-l.top+r.scrollTop-.3*r.clientHeight;O(e.index),r.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[O,o,s]),K=(0,i.useCallback)(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),Z=(0,i.useCallback)(()=>{y||(K(),v(!0))},[K,y]),V=(0,i.useCallback)(()=>{let e=!y;k(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rV();if(t)try{t.setItem(rZ,String(e))}catch{}}(e),e&&(K(),v(!1),w(null))},[K,y]),J=(0,i.useCallback)(()=>{K(),T.current=setTimeout(()=>{T.current=null,v(!1),w(null)},250)},[K]);(0,i.useEffect)(()=>()=>K(),[K]);let G=(0,i.useCallback)(e=>{if(!c)return;S.current=!0,Z();let t=e.currentTarget.getBoundingClientRect();w(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&&_(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,_,Z,c]),Y=null===j?null:U(j),X=Y?.index??null;if((0,i.useEffect)(()=>{if(!b||null===X)return;let e=$.current,t=E.current.get(X);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[p,b,X]),!c)return null;let Q=Math.max(1,(P.length>0?P[P.length-1].topRatio*f:12)-12);return(0,r.jsxs)("div",{ref:C,onMouseDown:G,onMouseEnter:Z,onMouseLeave:J,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();w((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:[l>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}}),P.map(e=>{let t=b&&Y?.index===e.index,n=m===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,z),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:rY().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(),V()},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"})]})}),b&&p.length>0&&(0,r.jsxs)("div",{ref:$,className:rY().preview,"data-minimap-preview-box":"",onMouseEnter:Z,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[l>0&&(0,r.jsx)("button",{type:"button",className:rY().earlier,"data-minimap-preview-earlier":"",onClick:()=>s.current?.scrollTo({top:0,behavior:"smooth"}),children:d("chatMinimap.earlierTurns",{count:l})}),p.map(e=>{var t;let n=X===e.index;return(0,r.jsxs)("div",{ref:t=>{t?E.current.set(e.index,t):E.current.delete(e.index)},className:rY().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsxs)("span",{className:rY().number,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:String(l+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,r.jsx)("span",{className:rY().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:rY().content,children:[(0,r.jsx)("button",{type:"button",className:rY().user,"data-minimap-preview-user":e.index,onClick:()=>{_(e,"smooth")},children:(0,r.jsx)("span",{className:rY().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:rY().assistant,children:[(0,r.jsx)("button",{type:"button",className:rY().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>H(e,n),"aria-label":d("chatMinimap.locateAssistant"),title:d("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(r2,{markdown:t.markdown,onAnswerClick:()=>H(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]})});var r8=n(42790);function r6(e){let{text:t}=e,n=(0,i.useMemo)(()=>{let e=new r8.v;e.use_classes=!0;let n=t.replace(nl,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function r3(e){let t,n,s,{widgets:a,children:o}=e,{t:l}=(0,eX.s)(),d=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),[p,h]=(0,i.useState)(()=>a.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[m,g]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var e;let t=new Map(a.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(g(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),g(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[a]),(0,i.useEffect)(()=>()=>{for(let e of u.current.values())clearTimeout(e);u.current.clear()},[]),0===a.length)return null;let f=a.find(e=>e.key===p&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[f&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=a.indexOf(f),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:f.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(r6,{text:f.lines.join("\n")})})]},f.key))}),(0,r.jsxs)("div",{className:"extension-status-row",children:[(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:a.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===f?.key,s=m.has(e.key),a=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=l("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}, ${a}`,title:`${e.key} - ${o} - ${i?l("i18n.collapse"):l("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}, ${a}`,title:`${e.key} - ${o}`,children:p},e.key)})}),o]})]})}let r5="command:";function r9(e){let{statuses:t,widgets:n=[],onCommand:i,commandsDisabled:s=!1}=e,a=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(r5))return null;let t=e.slice(r5.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=nd(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else nd(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===a.length&&0===n.length)return null;let o=a.some(e=>"command"===e.kind),l=a.map(e=>"text"===e.kind?nd(e.text):e.label).join(" "),d=a.length>0?(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":l,title:l,children:(0,r.jsx)("span",{className:"extension-status-text",children:a.map((e,t)=>"text"===e.kind?(0,r.jsx)("span",{className:"extension-status-item",children:(0,r.jsx)(r6,{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":""}${a.length>0?" has-status":""}${o?" has-commands":""}`,children:n.length>0?(0,r.jsx)(r3,{widgets:n,children:d}):d})}function r7(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}function ie(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function it(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function ir(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function ii(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function is(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(!ii(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=ii(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ii(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 ia(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 io 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 il(e){return e instanceof io&&"prompt_rejected"===e.code&&!1===e.accepted}function id(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function ic(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 io(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,ia(r)??void 0);return r.data}let iu={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function ip(e,t,n){let r=await fetch(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({side:!0,...n?{name:n}:{}}),cache:"no-store"}),i=await r.json().catch(()=>null);return r.ok&&i?.sessionId&&i.session?{session:i.session}:{error:i?.code&&i.code in iu?t(iu[i.code]):i?.error??`HTTP ${r.status}`}}async function ih(e){let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE",cache:"no-store"});if(t.ok)return null;let n=await t.json().catch(()=>null);return{error:n?.error??`HTTP ${t.status}`}}function im(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let ig=new WeakMap;function ix(e){let t,n=ig.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return ig.set(e,t),t}function ib(e){let t=im().get(e);return t?Date.now()-t.savedAt>6e5?(im().delete(e),null):(im().delete(e),im().set(e,t),t):null}function iv(e){if(!e.sessionId||!e.revision)return!1;let t=im();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(ix(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=im();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+=ix(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-=ix(r))}}(),im().has(n.sessionId))}function iy(e){im().delete(e)}var ik=n(14755);let ij="pi-tool-preset";function iw(){try{return window.localStorage}catch{return null}}function iS(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 iC(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,iS(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),iS(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}var iN=n(64738);function iI(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 i$(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(iI).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let iE=(e,t)=>`live:${e??""}:${t}`;class iT 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 iM{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.endedSessionId=null,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 iT("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.endedSessionId===e||!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof iT?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new iT("closed");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 iT("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new iT("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new iT("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 iT("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),a=setTimeout(()=>{this.fail(d,new iT("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(a),n())},fail(e){i||(i=!0,clearTimeout(a),r(e))}},l=Date.now(),d={sessionId:e,source:t,attempt:o,watchdog:null,openedAt:l,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=d,t.onmessage=t=>{let n;if(this.current===d){d.lastSeenAt=Date.now();try{n=JSON.parse(t.data)}catch{return}if("session_ended"===n.type&&n.sessionId===e){this.endedSessionId=e,this.close(),this.options.onEvent(n);return}if("heartbeat"===n.type){d.lastHeartbeatAt=d.lastSeenAt;return}if("connected"===n.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??l)>e&&this.fail(d,new iT("closed"),"stale")},Math.max(1e3,Math.floor(e/3))))}else if("startup_error"===n.type){let e="string"==typeof n.errorMessage?n.errorMessage:void 0;this.fail(d,new iT("startup_error",e),"startup_error");return}d.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(d,new iT("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 iR(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}var iA=n(48495);function iL(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function iP(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 iz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let iO=/^(?:custom-ui|extension-widget):/;var iW=n(89594),iF=n(40505);function iD(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let iB={isStreaming:!1,streamingMessage:null};function i_(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 iH(){let e=iB,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=is(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 i_(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return i_(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return i_(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return i_(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return i_(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return i_(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return i_(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 i_(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 i_(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return iB;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 iU(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function iq(e,t){return e.reduce((e,n)=>"user"===n.role&&i$(n)===t?e+1:e,0)}function iK(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function iZ(e){return e&&"auto"!==e?e:null}let iV=new Map,iJ=[2e3,5e3,1e4],iG=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:200,t=new Set;return n=>!t.has(n)&&(t.add(n),t.size>e&&t.delete(t.values().next().value),!0)}();function iY(e){return new Promise(t=>setTimeout(t,e))}function iX(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iQ(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:iX(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iX(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=iX(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function i0(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 i1(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 i2=e=>e.isStreaming,i4=e=>!!e.streamingMessage?.content.length,i8=e=>e.streamingMessage;var i6=n(70843),i3=n(36690);let i5=null,i9=null;function i7(e){let{label:t}=e,[n,s]=(0,i.useState)(()=>i9);if((0,i.useEffect)(()=>{if(i9)return;let e=!1;return(i5??=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=>(i9=e,e)).catch(()=>(i5=null,null))).then(t=>{!e&&t&&s(t)}),()=>{e=!0}},[]),!n)return null;let a=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:a,"aria-label":a,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 se(e){let{messageCount:t,toolCallCount:n,durationMs:s,cacheMisses:a,defaultExpanded:o=!1,reveal:l=!1,children:d,t:c}=e,[u,p]=(0,i.useState)(o);(0,i.useLayoutEffect)(()=>{l&&p(!0)},[l]);let h=[`${t} ${c(1===t?"chat.message":"chat.messages")}`];n>0&&h.push(`${n} ${c(1===n?"chat.toolCall":"chat.toolCalls")}`),void 0!==s&&h.push(c("chat.turnDuration",{time:(0,nL.J)(s)}));let m=a&&!(u||l)?(0,i3.YL)(c,a):void 0;return(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u||l,"aria-label":[c("chat.processDetails"),...h,...m?[m]:[]].join(" \xb7 "),onClick:()=>p(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:c(u?"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:u?"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:[h.join(" \xb7 "),m&&(0,r.jsx)("span",{style:{color:i3.lV},children:` \xb7 ${m}`})]})]}),(u||l)&&(0,r.jsx)("div",{style:{marginTop:8},children:d})]})}function st(e){var t;let s,{session:o,searchTarget:d,onSearchTargetHandled:c,initialScrollPosition:u,onScrollPositionChange:p,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:g,newSessionContextBar:f,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:v,onSessionEnded:y,onToolEnd:k,onAttentionNeeded:j,onSessionCreated:w,onSessionForked:S,panel:C=!1,onSideSession:N,modelsRefreshKey:I,chatInputRef:$,onBranchDataChange:E,onSystemPromptChange:T,onSystemToolsChange:M,onSystemInfoLoaderChange:R,onDebugSnapshotReaderChange:A,onSessionStatsChange:L,onSessionStatsPanelOpen:P,onOpenSettings:z,onContextUsageChange:O,onOpenFile:W,onFilesUploaded:F,onOpenSubagent:D,onEnterSubagent:B,quoteSelectionEnabled:_=!1,initialPrompt:H,onInitialPromptConsumed:U,soundEnabled:q=!0,onSoundToggle:K,playDoneSound:Z=()=>{},unlockAudio:V,holdAudio:J}=e,{t:G}=(0,eX.s)(),Y=(0,eQ.a)(),X=!l(o?.relation),Q=(0,i.useRef)(Z);Q.current=Z;let ee=(0,i.useRef)(q);ee.current=q;let et=(0,i.useRef)(!1),en=(0,i.useCallback)(e=>{X&&ee.current&&!e.aborted&&!e.subagentsActive&&Q.current(),v?.(e)},[X,v]),er=(0,i.useRef)(d?null:u??null),[ei,es]=(0,i.useState)(()=>{let e=er.current;return e&&!e.atBottom?e:null}),[ea,eo]=(0,i.useState)(!1),{loading:el,error:ed,messages:ec,activeToolResults:eu,toolClocks:ep,entryIds:eh,messageKeys:em,historyCursor:eg,hasEarlierMessages:ef,earlierTurnCount:ex,streamingStore:eb,agentRunning:ev,bashRunning:ey,pendingBash:ek,modelNames:ej,modelList:ew,modelError:eS,missingCwd:eC,modelScopeWarnings:eN,isModelScopeActive:eI,allModelList:e$,modelThinkingLevels:eT,modelThinkingLevelMaps:eM,toolPreset:eR,thinkingLevel:eA,retryInfo:eL,contextUsage:eP,forkingEntryId:ez,isCompacting:eO,compactError:eW,compactResult:eF,displayModel:eD,modelSwitching:eB,sessionStats:e_,slashCommands:eH,slashCommandsLoading:eU,queuedMessages:eq,notices:eK,extensionDialog:eZ,waitingExtensionDialogCount:eV,extensionCustomUi:eJ,waitingExtensionCustomUiCount:eG,extensionStatuses:eY,extensionWidgets:e0,respondToExtensionUi:e2,sendExtensionCustomInput:e4,setNoticePaused:e8,addNotice:e6,isAutoModelSelection:e3,isAutoThinkingSelection:e9,defaultModel:e7,savedDefaultThinkingLevel:te,agentPhase:tt,isNew:tn,editEntryId:tr,showScrollToBottom:ti,sessionIdRef:ts,scrollContainerRef:ta,lastUserMsgRef:to,promptAnchorActive:tl,handleSend:td,handleAbort:tu,startSideChat:tp,handleFork:th,handleEditContent:tm,cancelEdit:tg,handleModelChange:tf,handleCompact:tx,handleSteer:tb,handleFollowUp:tv,handlePromptWithStreamingBehavior:ty,handleAbortCompaction:tk,dismissCompactError:tj,handleRecallQueue:tw,handleBuiltinSlashCommand:tS,handleToolPresetChange:tC,handleThinkingLevelChange:tN,handleSetDefaultModel:tI,handleSetDefaultThinkingLevel:t$,loadSlashCommands:tE,loadAllModels:tT,scrollUserMsgToTop:tM,loadContext:tR,activeLeafId:tA,scrollToBottom:tL,scrollToMessage:tP}=function(e){var t;let r,s,{session:a,newSessionCwd:o,newSessionDraftKey:l,onAgentEnd:d,onSessionEnded:c,onToolEnd:u,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:m,onSideSession:g,modelsRefreshKey:f,onBranchDataChange:x,onSystemPromptChange:b,onSystemToolsChange:v,onSystemInfoLoaderChange:y,onSessionStatsPanelOpen:k,onOpenSettings:j,onDebugSnapshotReaderChange:w}=e,S=null===a&&null!==o,C=S?e.initialNewSessionChoices??null:null,[N,I]=(0,i.useState)(null),[$,E]=(0,i.useState)(!S),[T,M]=(0,i.useState)(null),[R,A]=(0,i.useState)(null),[L,P]=(0,i.useState)([]),[z,O]=(0,i.useState)(new Map),[W,F]=(0,i.useState)(iF.HP),[D,B]=(0,i.useState)([]),[_,H]=(0,i.useState)(()=>new Map),[U,q]=(0,i.useState)(null),[K,Z]=(0,i.useState)(!1),[V,J]=(0,i.useState)(0),[G]=(0,i.useState)(iH),Y=G.dispatch,[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(!1),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)({}),[ea,eo]=(0,i.useState)([]),[el,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,eg]=(0,i.useState)([]),[ef,ex]=(0,i.useState)(!1),[eb,ev]=(0,i.useState)(null),ey=(0,i.useRef)(null),[ek,ej]=(0,i.useState)({}),[ew,eS]=(0,i.useState)({}),[eC,eN]=(0,i.useState)(()=>C?.model??null),[eI,e$]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(ik.Q8),[eR,eA]=(0,i.useState)(()=>C?.thinkingLevel??null),[eL,eP]=(0,i.useState)(null),[ez,eO]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(null),[eD,eB]=(0,i.useState)(null),[e_,eH]=(0,i.useState)(null),[eU,eq]=(0,i.useState)(null),[eK,eZ]=(0,i.useState)(null),eV=(0,i.useRef)(0),eJ=(0,i.useRef)(0),[eG,eY]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(null),[e3,e5]=(0,i.useState)(!1),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!0),[tn,tr]=(0,i.useState)(null),[ti,ts]=(0,i.useState)(null),[ta,to]=(0,i.useState)(null),[tl,td]=(0,i.useState)(!1),[tu,tp]=(0,i.useState)(!1),[th,tm]=(0,i.useState)([]),[tg,tf]=(0,i.useState)(!1),[tx,tb]=(0,i.useReducer)(iQ,{visible:[],pending:[]}),[tv,ty]=(0,i.useState)(null),[tk,tj]=(0,i.useState)([]),[tw,tS]=(0,i.useState)([]),[tC,tN]=(0,i.useState)([]),[tI,t$]=(0,i.useState)([]),[tE,tT]=(0,i.useState)({steering:[],followUp:[]}),tM=(0,i.useRef)(null),tR=(0,i.useRef)(null),tA=(0,i.useRef)(0),tL=(0,i.useRef)(!1),tP=(0,i.useRef)(!1),[tz,tO]=(0,i.useState)(0),tW=(0,i.useRef)(null),tF=(0,i.useRef)(()=>{}),tD=(0,i.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tB=(0,i.useRef)({count:0,lastAt:null}),t_=(0,i.useRef)({count:0,lastAt:null,lastReason:null}),tH=(0,i.useRef)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(!1),tK=(0,i.useRef)(0),tZ=(0,i.useRef)(a?.id??null),tV=(0,i.useRef)(null),tJ=(0,i.useRef)(a?.id??null),tG=(0,i.useRef)(!1),tY=(0,i.useRef)(!1),tX=(0,i.useRef)(!1),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(-1),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(0),t4=(0,i.useRef)(0),t8=(0,i.useRef)(null),t6=(0,i.useRef)(!!e.deferInitialScroll),t3=(0,i.useRef)(null),t5=(0,i.useRef)(!1),t9=(0,i.useRef)(!0),t7=(0,i.useRef)(0),ne=(0,i.useRef)(null),nt=(0,i.useRef)(void 0),nn=(0,i.useRef)(void 0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(null),ns=(0,i.useRef)([]),na=(0,i.useRef)(null),no=(0,i.useRef)(0),nl=(0,i.useRef)(!1),nc=(0,i.useRef)(C?.model??null),nu=(0,i.useRef)(C?.thinkingLevel??null),np=(0,i.useRef)({}),nh=(0,i.useRef)(null),nm=(0,i.useRef)(0),ng=(0,i.useRef)(null),nf=(0,i.useRef)(null),nx=(0,i.useRef)(null),nv=(0,i.useRef)(0),ny=(0,i.useRef)(null),nk=(0,i.useCallback)(()=>{nf.current=nm.current,nx.current?.runId===nm.current&&(nx.current=null)},[]),nw=(0,i.useRef)(!1),nS=(0,i.useRef)(new Map),nC=(0,i.useRef)(!0),nN=(0,i.useRef)(new Map),nI=(0,i.useRef)(null),nE=(0,i.useRef)([]),nT=(0,i.useRef)([]),nM=(0,i.useRef)(null),nR=(0,i.useRef)(null),nA=(0,i.useRef)(!1),nL=(0,i.useRef)(0);tJ.current=a?.id??null,nI.current=N,nE.current=L,nT.current=D,nM.current=R,nR.current=U,nA.current=K,nL.current=V,tq.current=e9,tK.current=tk.length+tw.length;let nP=(0,i.useCallback)(e=>nC.current&&tV.current!==e&&tZ.current===e&&(tY.current||tL.current||tJ.current===e&&!tP.current),[]);tM.current||(tM.current=new iM({createSource:e=>(0,eE.Lf)("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent((0,eE.nU)())}`),e),onEvent:e=>t8.current?.(e),shouldMaintain:nP,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nz=e.setToolPreset??eM,nO=a?.id;(0,i.useLayoutEffect)(()=>{(nO||S&&!tZ.current)&&nz(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:iw();if(!e)return ik.Q8;try{let t=e.getItem(ij);return(0,ik.sn)(t)?t:ik.Q8}catch{return ik.Q8}}())},[nO,S,nz]);let nW=e.onNewSessionChoicesChange;(0,i.useEffect)(()=>{S&&nW?.({model:eC,thinkingLevel:eR})},[S,eC,eR,nW]);let nF=(0,i.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=nr.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),t7.current=t.scrollTop)},[]),nD=e0??e2??N?.context.model??e8??null,nB=S?eC??eI:nD??(N?.context.messages.length===0?eI:null),nH=iZ(N?.context.thinkingLevel&&"off"!==N.context.thinkingLevel?N.context.thinkingLevel:null),nU=S?eR??eL:eW??eD??nH??(N?.context.messages.length===0?eL:null),nV=a?.id??l??void 0,nJ=(0,i.useCallback)(e=>{e4(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eB(iZ(e.thinkingLevel))},[]),nX=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nS.current.get(t);if(!e)break;t=e}return t},[]),nQ=(0,i.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=nX(r);if(!nC.current&&!nl.current&&r===l)return;let a=e.chatInputRef?.current;a?a.restoreSubmission(t,i,s):s&&nG(s,t,i)},[l,e.chatInputRef,nX]),[n0,n1]=(0,i.useState)(()=>{let e=a?.id;return e&&!nq(e)&&iV.delete(e),e&&iV.get(e)||null}),n2=(0,i.useCallback)(e=>{a?.id&&(e?iV.set(a.id,e):iV.delete(a.id),n1(e))},[a?.id]),n4=(0,i.useCallback)((t,n)=>{a?.id&&(e.chatInputRef?.current?.replaceMessage(t),n2(n))},[e.chatInputRef,a?.id,n2]),n6=(0,i.useCallback)(()=>n2(null),[n2]),n3=(0,i.useMemo)(()=>{let e=N?.totalActiveMs,t=eK&&eK.sessionId===N?.sessionId?eK.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(tv)return{...tv,totalActiveMs:n,...eU?{contextUsage:eU}:{}};let r=N?.stats,i=function(e,t,n){let r=iC(n);if(!e)return r;let i=iC(t),s=(e,t)=>Math.max(0,e-t),a={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 a.total=a.input+a.output+a.cacheRead+a.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:a,cost:e.cost+s(r.cost,i.cost)}}(r,N?.context.messages??[],L);return 0!==i.tokens.total||0!==L.length||r?{sessionFile:N?.filePath||void 0,sessionId:tZ.current??a?.id??"",sessionName:a?.name,...i,totalActiveMs:n,...eU?{contextUsage:eU}:{}}:null},[L,tv,eU,eK,N?.sessionId,N?.context.messages,N?.filePath,N?.totalActiveMs,N?.stats,a?.id,a?.name]),n5=(0,i.useCallback)((e,t,n,r)=>{nC.current&&tZ.current===t&&nm.current===n&&!(r<=eJ.current)&&(eJ.current=r,e?.contextUsage!==void 0&&eq(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&eZ({sessionId:t,value:e.totalActiveMs}))},[]),n9=(0,i.useCallback)(async e=>{let t=nm.current,n=++eV.current;try{let r=await fetch(id(e));if(!r.ok)return;let i=await r.json();n5(i.state,e,t,n)}catch{}},[n5]),n7=(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:nN.current.get(i);if(s)return await s;let a=(async()=>{let i=!1,s=++nv.current,a=!tY.current;try{t&&E(!0);let o=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&o.set("force","1");let l=await fetch(`/api/sessions/${encodeURIComponent(e)}?${o}`);if(404===l.status)return t&&(I(null),A(null),P([]),B([]),q(null),Z(!1),J(0),M(null)),iy(e),null;if(!l.ok)throw Error(`HTTP ${l.status}`);let d=await l.json();if(tZ.current!==e)return null;(ny.current?.seq??0)<s&&(ny.current={sid:e,seq:s,messages:d.context.messages,entryIds:d.context.entryIds??[]});let c=ib(e),u=!!(d.snapshotRevision&&c?.revision===d.snapshotRevision&&c.entryIds.length>=(d.context.entryIds??[]).length),p=u?nE.current:d.context.messages;if(I(u?{...d,context:{...d.context,messages:nE.current,entryIds:nT.current,oldestEntryId:nR.current,hasMore:nA.current,turnsBefore:nL.current}}:d),A(d.leafId),u)iv({sessionId:e,revision:d.snapshotRevision,messages:nE.current,entryIds:nT.current,leafId:d.leafId,oldestEntryId:nR.current,hasMore:nA.current,turnsBefore:nL.current,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:nT.current});else{let e={messages:nE.current,entryIds:nT.current},t={messages:p,entryIds:d.context.entryIds??[]};H(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],a=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===a&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var o,l;let d=t.entryIds[a+n];if(void 0===d||(o=e.messages[i+n],l=t.messages[a+n],o.role!==l.role||("user"===o.role?i$(o)!==i$(l):"custom"===o.role?o.customType!==l.customType:o.timestamp!==l.timestamp)))break;r.set(d,iE(s,n))}return r})({...e,aliases:n},t)),P(t.messages),B(t.entryIds),q(d.context.oldestEntryId),Z(d.context.hasMore),J(d.context.turnsBefore??0)}if(tG.current=void 0!==d.toolNames,nz(void 0!==d.toolNames?(0,ik.YO)(d.toolNames):ik.Q8),e1(e=>nw.current?e:null),eF(null),M(null),"summary"===d.treeFormat&&d.snapshotRevision&&iv({sessionId:e,revision:d.snapshotRevision,messages:p,entryIds:d.context.entryIds??[],leafId:d.leafId,oldestEntryId:d.context.oldestEntryId,hasMore:d.context.hasMore,turnsBefore:d.context.turnsBefore??0,summaryTree:d.tree,thinkingLevel:d.context.thinkingLevel,model:d.context.model,stats:d.stats,totalActiveMs:d.totalActiveMs,loadedEntryIds:d.context.entryIds??[]}),d.wrapperRebuilt&&(tM.current?.close("rebuilt"),tM.current?.maintain(e)),!n&&d.context.thinkingLevel&&"off"!==d.context.thinkingLevel&&eB(iZ(d.context.thinkingLevel)),i=!0,a&&s>t2.current&&er(e=>e?.result?null:e),t&&E(!1),!n)return null;try{let t=nm.current,n=++eV.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(tZ.current!==e)return null;let s=i.state;return nJ(s),s?(n5(s,e,t,n),void 0!==s.systemPrompt&&eY(s.systemPrompt??null),void 0!==s.extensionStatuses&&tN(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&t$(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tT(iK(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tt(s.autoCompactionEnabled??!0)):i.running||tT({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return M(String(e)),"error"}finally{t&&!i&&E(!1)}})();return nN.current.set(i,a),a.finally(()=>{nN.current.get(i)===a&&nN.current.delete(i)}),await a},[n5,nz,nJ]),re=(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}`,a=await fetch(s,{signal:r?.signal});if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json();if(tZ.current!==e||r?.signal?.aborted||!nC.current)return;return q(o.context.oldestEntryId),Z(o.context.hasMore),J(o.context.turnsBefore??0),I(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?(P(e=>[...o.context.messages,...e]),B(e=>[...o.context.entryIds,...e])):(P(o.context.messages),B(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),rt=(0,i.useCallback)(async e=>{try{let t=await ic(e,{type:"get_tools"});if(!t||!nC.current||tZ.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nz(tG.current?r(t):ik.Q8),v?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[v,nz]),rn=(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)",r=tZ.current;if(S&&o&&r&&!nl.current&&(nl.current=!0,l)){if(l!==r){nS.current.set(l,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(l,r):nY(l,r)}h?.({id:r,path:"",cwd:o,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},l)}},[S,o,l,h,e.chatInputRef]),rr=(0,i.useCallback)(async()=>{if(tZ.current||!S||!o)return tZ.current;if(ni.current)return ni.current;let e=(async()=>{let e=nc.current,t=nu.current;e&&e6(e);let n=(0,ik.xG)(eT);tG.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:o,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok){let e=await r.json().catch(()=>null),t="string"==typeof e?.error?e.error:`HTTP ${r.status}`,n=ia(e);throw n?new io(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return tZ.current=s,i.model&&nc.current===e&&(e6(i.model),e||e$(i.model)),i.thinkingLevel&&nu.current===t&&(eB(iZ(i.thinkingLevel)),t||eP(iZ(i.thinkingLevel))),s})();ni.current=e;try{return await e}finally{ni.current=null}},[S,o,eT]),ri=(0,i.useCallback)(async()=>{let e=tZ.current??await rr();if(!e)return;let[t]=await Promise.all([ic(e,{type:"get_state"}),rt(e)]);nC.current&&tZ.current===e&&(nJ(t),eY(t.systemPrompt??""))},[rr,rt,nJ]),rs=(0,i.useCallback)(e=>{ns.current=e,tm(e)},[]),ra=(0,i.useCallback)(()=>{no.current+=1,na.current=null,rs([])},[rs]),ro=(0,i.useCallback)(()=>{let e=++no.current,t=(async()=>{let t=tZ.current??await rr();if(!t)return no.current===e&&rs([]),[];tf(!0);try{let n=await ic(t,{type:"get_commands"}),r=n?.commands??[];return no.current===e&&rs(r),r}catch(t){return console.error("Failed to load slash commands:",t),no.current===e&&rs([]),null}finally{no.current!==e&&na.current||tf(!1)}})();na.current=t;let n=()=>{na.current===t&&(na.current=null)};return t.then(n,n),t},[rr,rs]),rl=(0,i.useCallback)(async()=>await ro()??[],[ro]),rd=(0,i.useCallback)(async()=>{let e=na.current,t=ns.current;return!e&&t.length>0?t:await (e??ro()).catch(()=>null)??(t.length>0?t:null)},[ro]),rc=(0,i.useCallback)(()=>{tA.current+=1,tL.current=!1,tU.current=null,tR.current&&(clearTimeout(tR.current),tR.current=null)},[]),ru=(0,i.useCallback)(e=>{tM.current?.close(e)},[]),rp=(0,i.useCallback)(e=>tM.current.ensureConnected(e),[]),rh=(0,i.useCallback)(e=>{tM.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=a?.id;if(e)return nC.current=!0,tP.current=!1,rh(e),()=>{tZ.current===e&&tM.current?.close("deselected")}},[rh,a?.id]);let rm=(0,i.useCallback)(e=>{let t=tW.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,a=Date.now();tD.current.inFlightSince=a,tD.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 s=n.signal.aborted||e instanceof TypeError?"unanswered":null}finally{clearTimeout(r),tW.current===i&&(tW.current=null);try{let e=tD.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-a),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tW.current=i,i.promise},[]),rg=!X&&!ee&&!e9&&0===tk.length&&0===tw.length;(0,i.useEffect)(()=>{let e=a?.id;if(!e||!rg)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tP.current&&tZ.current===e&&tJ.current===e&&!tY.current&&!t1.current,i=async()=>{if(n=null,tH.current=null,!r())return;let t=await rm(e);if(r()){if(!("unanswered"===t||t&&!iR(t)))return void s();tP.current=!0,tB.current={count:tB.current.count+1,lastAt:Date.now()},ru("released")}},s=()=>{null===n&&(n=setTimeout(()=>void i(),iA.P),tH.current=Date.now()+iA.P)},o=()=>{"hidden"===document.visibilityState?s():n&&(clearTimeout(n),n=null,tH.current=null)};return"hidden"===document.visibilityState&&s(),document.addEventListener("visibilitychange",o),()=>{t=!0,n&&clearTimeout(n),tH.current=null,document.removeEventListener("visibilitychange",o)}},[ru,rg,tz,rm,a?.id]);let rf=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(tj(t=>ir(t,e.id)),n)try{await ic(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),rx=(0,i.useCallback)(async(e,t)=>{let n=tZ.current;if(n)try{await ic(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rb=(0,i.useCallback)(e=>{let t=e.message.trim();t&&tb({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"}})},[]),rv=(0,i.useRef)(e.t);rv.current=e.t;let ry=(0,i.useCallback)((e,t)=>rv.current(e,t),[]),rk=(0,i.useCallback)(()=>{rb({type:"warning",message:ry("chat.sendUnconfirmed")})},[rb,ry]),rj=(0,i.useCallback)(e=>{nC.current&&P(t=>iU(t,e.bubble));let t=ib(e.sid);t?.messages.includes(e.bubble)&&iv({...t,messages:iU(t.messages,e.bubble)})},[]),rw=(0,i.useCallback)((e,t,n)=>{let r=nx.current;if(!r||r.runId!==t||r.sid!==e)return;nx.current=null;let i=ny.current,s=i?.sid===e&&i.seq>n?i:null,a=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&a>=0&&iq(s.messages.slice(a),r.key)>r.sameTextAfterSend||(nQ(r.message,r.images,r.draftKey),s&&rj(r),rb(s&&!r.command&&a===s.entryIds.length?{type:"error",message:ry("chat.sendNotReceived")}:{type:"warning",message:ry("chat.sendUnconfirmed")}))},[rb,rj,nQ,ry]),rS=(0,i.useCallback)(()=>{let e=nx.current;if(nx.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});nG(e.parkedDraftKey,e.message,t)}else nQ(e.message,e.images,e.draftKey);rj(e)}},[rj,nQ]),rC=(0,i.useRef)(rS);rC.current=rS;let rN=(0,i.useCallback)(t=>{switch(ie(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tj(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!iG(t.id))break;rb({id:t.id,message:nd(t.message),type:t.notifyType??"info"});break;case"setStatus":tN(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":t$(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=nd(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(nd(t.text));break;case"custom":tS(e=>{let n;return t.closed?ir(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)})}},[rb,p,e.chatInputRef]),rI=(0,i.useCallback)(()=>{let e=tY.current;return tY.current=!1,Q(!1),to(null),eH(null),O(new Map),F(iF.HP),Y({type:"end"}),e},[Y]),r$=(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 t0.current!==e&&(t0.current=e,d?.({aborted:t,...n?{subagentsActive:n}:{}}),!0)},[d]),rE=(0,i.useCallback)(e=>{if(tJ.current===e)return void rc();rc(),tL.current=!0;let t=tA.current,n=async()=>{if(t===tA.current&&tZ.current===e&&tL.current)try{let r=await fetch(id(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==tA.current||tZ.current!==e||!tL.current)return;let s=i.state;if(nJ(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tL.current=!1,tR.current=null,tU.current=null,tX.current=!!s?.isStreaming,tQ.current=!!s?.isPromptRunning,tY.current=!0,Q(!0),to(e=>r7(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){e7(!0),tR.current=setTimeout(()=>void n(),600),tU.current=Date.now()+600;return}tL.current=!1,tR.current=null,tU.current=null,ru("grace_end")}catch{if(t!==tA.current||tZ.current!==e||!tL.current)return;tR.current=setTimeout(()=>void n(),600),tU.current=Date.now()+600}};tR.current=setTimeout(()=>void n(),3e4),tU.current=Date.now()+3e4},[rc,ru,nJ]),rT=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tZ.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nm.current;if(nm.current!==t)return;let n=nv.current;try{e&&await n7(e)}finally{if(nm.current!==t)return;e&&rw(e,t,n);let r=tQ.current,i=tX.current;tQ.current=!1,tX.current=!1,ng.current=null;let s=rI();r?r$(t):i&&s&&d?.({aborted:!1}),e&&rE(e)}},[n7,r$,d,rE,rI,rw]),rM=(0,i.useCallback)(async(e,t)=>{await iY(800);let n=Date.now();for(;tY.current&&Date.now()-n<2e4;){if(void 0!==t&&nm.current!==t)return;try{let n=await fetch(id(e));if(n.ok){let r=await n.json(),i=r.state;if(nJ(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rT(e,t)}}catch{}await iY(600)}},[rT,nJ]),rR=(0,i.useCallback)(async e=>{let t=t4.current+1;for(t4.current=t;t1.current&&t4.current===t&&tZ.current===e;){await iY(1e3);try{let n=await fetch(id(e));if(!n.ok)continue;let r=await n.json();if(nJ(r.state),r.state?.isBashRunning)continue;if(await n7(e),t4.current!==t||tZ.current!==e)return;t1.current=!1,et(!1),er(null);return}catch{}}},[n7,nJ]),rA=(0,i.useCallback)(async e=>{if(!tY.current||tZ.current!==e)return;let t=nm.current,n=++eV.current;try{let r=await fetch(id(e));if(!r.ok)return;let i=await r.json();if(tZ.current!==e||nm.current!==t)return;let s=i.state;if(n5(s,e,t,n),nJ(s),e7(s?.isCompacting??!1),tt(s?.autoCompactionEnabled??!0),tT(iK(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){tX.current=!!s.isStreaming,tQ.current=!!s.isPromptRunning;return}if(!tY.current)return;s&&(void 0!==s.extensionStatuses&&tN(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&t$(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nC.current&&tZ.current===e&&t.state?.systemPrompt!==void 0&&eY(t.state.systemPrompt??null)}).catch(()=>{})),await rT(e,t)}catch{}},[n5,rT,nJ]);(0,i.useEffect)(()=>{if(!X)return;let e=()=>{let e=tZ.current;e&&rA(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)}},[X,rA]),(0,i.useEffect)(()=>{tY.current=X},[X]);let rL=(0,i.useCallback)(e=>nC.current&&tZ.current===e&&!tY.current,[]),rP=(0,i.useRef)(null),rz=(0,i.useRef)(null),rO=(0,i.useCallback)(async e=>{var t;let n,r=new URLSearchParams({deferThinking:"1",deferMedia:"1",tail:"1"}),i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let{context:s,leafId:a}=await i.json();if(!rL(e))return;let o=nT.current.at(-1),l=nE.current.at(-1),d=void 0!==o&&nE.current.length===nT.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(o))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!d)return void await n7(e);if(0===d.entryIds.length)return;if(t1.current&&d.messages.some(e=>"bashExecution"===e.role)){rz.current=e;return}nT.current=[...nT.current,...d.entryIds],nE.current=[...nE.current,...d.messages],B(e=>e.at(-1)===o?[...e,...d.entryIds]:e),P(e=>e.at(-1)===l?[...e,...d.messages]:e),a&&(rP.current={base:nM.current,lastEntryId:d.entryIds.at(-1),leafId:a});let c=ib(e);c&&iv({...c,loadedEntryIds:[...c.loadedEntryIds,...d.entryIds]})},[rL,n7]),rW=(0,i.useRef)(rO);rW.current=rO;let rF=(0,i.useRef)(null);rF.current??=(t={pendingReads:e=>[nN.current.get(e),nN.current.get(`force:${e}`)],read:e=>rW.current(e),wanted:rL,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,s=null,e=>{s=e,r||(r=!0,(async()=>{try{for(;null!==s;){let e=s;if(s=null,t.wanted(e))try{await Promise.allSettled(t.pendingReads(e)),t.wanted(e)&&await t.read(e)}catch(e){t.onError?.(e)}}}finally{r=!1}})())}),t8.current=(0,i.useCallback)(t=>{if(!tV.current)switch(t.type){case"session_ended":{let e=tZ.current;if(!e||t.sessionId!==e)return;tV.current=e,rc(),tM.current?.close(),iy(e),c?.(e);return}case"connected":if(Y({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tj(t=>it(t,e)),tS(t=>it(t,e))}F(iF.E),!0===t.isStreaming&&(rc(),tX.current=!0,tY.current=!0,Q(!0),to({kind:"waiting_model"})),tZ.current&&n9(tZ.current);break;case"agent_start":nk(),rc(),tX.current=!0,tY.current=!0,Q(!0),to({kind:"waiting_model"}),eH(null),Y({type:"start"});break;case"agent_end":if(!tY.current)break;if(to(null),eH(null),Y({type:"end"}),tZ.current){let e=tZ.current,t=nm.current,n=++eV.current;n7(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nC.current&&tZ.current===e&&nm.current===t&&(nJ(r.state),n5(r.state,e,t,n),r.state?.systemPrompt!==void 0&&eY(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tN(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&t$(r.state.extensionWidgets??[]),tT(iK(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=tX.current;if(tX.current=!1,!e||tQ.current)break;let n=tZ.current,r=rI();e7(!1),n&&(n7(n),rE(n)),r&&d?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{}});break}case"prompt_done":{nk();let e=nm.current,n=tQ.current;tQ.current=!1,ng.current=null;let r=r$(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=tZ.current;i&&n7(i),!tX.current&&(rI(),i&&rE(i))}break;case"prompt_error":rb({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rb({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!iO.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!tY.current||iP(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(Y({type:"snapshot",message:e}),e.content.length>0&&to(null)):e&&to(null)}else{let e=t.assistantMessageEvent;e&&(Y({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&to(null))}!t5.current&&t9.current&&null===ne.current&&(ne.current=requestAnimationFrame(()=>{ne.current=null,t9.current&&nF("auto")}));break;case"message_end":{if(!tY.current){let e=t.message;e?.role==="custom"&&!(0,nb.zZ)(e)&&tZ.current&&rF.current?.(tZ.current);break}if(iP(t))break;let e=t.message;if(e&&"user"===e.role){let t=is(e),n=i$(t),r=ng.current;ng.current=null,r&&nk(),P(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&i$(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(P(t=>[...t,(0,iW.mO)(is(e),n)]),"toolResult"===e.role){let t=e.toolCallId;F(e=>(0,iF.vx)(e,t))}if("assistant"===e.role){let e=tZ.current;e&&n9(e)}}Y({type:"end"}),to({kind:"waiting_model"});break}case"tool_execution_start":{if(iL(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();F(e=>(0,iF.Ho)(e,t,r)),to(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[];return r.some(t=>t.id===e)||r.push({id:e,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{if(iL(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content;Array.isArray(i)&&("bash"===n||"powershell"===n||n===nj.sp||(0,n$.G)(r?.details))&&O(t=>{let s=new Map(t);return s.set(e,{role:"toolResult",toolCallId:e,toolName:n,content:i,isError:r?.isError,details:r?.details}),s});let s=n===nj.sp?(0,nj.ky)(t.partialResult):function(e){if(!iz(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>iz(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)}`}(t.partialResult);to(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),a={id:e,name:n||i?.name||"tool",progress:s??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),a]}});break}case"tool_execution_end":{if(iL(t))break;let e=t.toolCallId;u?.(t.toolName);let n=performance.now();F(e=>(0,iF.Ho)(e,t,n)),O(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n}),to(t=>{if(t?.kind!=="running_tools")return t;let n=t.tools.filter(t=>t.id!==e);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":nk(),tT({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":eH({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":eH(null);break;case"auto_compaction_start":case"compaction_start":e7(!0),tr(null),ts(null);break;case"auto_compaction_end":case"compaction_end":e7(!1),eH(null),t.errorMessage?(tr(t.errorMessage),ts(null)):!t.aborted&&(ts(i0(t.result,t.reason??"auto")),tZ.current&&n7(tZ.current));break;case"bash_output":{let e=t.output;if(!t1.current||"string"!=typeof e)break;er(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(nd(t.text));break;case"extension_ui_request":rN(t);break;case"extension_ui_closed":tj(e=>ir(e,t.id))}},[rb,n5,e.chatInputRef,rc,Y,rN,n7,nk,r$,d,c,u,n9,rE,nF,rI,nJ]);let rD=(0,i.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(t1.current||tY.current&&!r){t1.current&&r&&rb({type:"warning",message:ry("chat.bashAlreadyRunning")}),nQ(e,t,nV);return}if(n0&&(n2(null),!await nn.current?.(n0))){n2(n0),nQ(e,t,nV);return}let i=!t?.length&&n.startsWith("/");if(r){let r=n.startsWith("!!"),i=(r?n.slice(2):n.slice(1)).trim();return i?void await nt.current?.(i,r):void nQ(e,t,nV)}let s=nm.current+1;rc(),tQ.current=!0;let l=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),d={role:"user",content:l?.length?[...e.trim()?[{type:"text",text:e}]:[],...l]:e,timestamp:Date.now()},c=i$(d),u=nT.current,p=u.at(-1)??null,h=iq(nE.current.slice(u.length),c);P(e=>[...e,d]),ng.current=c,nm.current=s,tY.current=!0,Q(!0),to(i?{kind:"running_command"}:{kind:"waiting_model"}),Y({type:"start"}),t5.current=!0,td(!0);let m=()=>{P(e=>{let t=e.lastIndexOf(d);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),ng.current=null},g=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),f=null,x=!1;try{if(S&&o){let t=tZ.current??await ni.current,n=t??await rr();if(!n)throw Error("Unable to create a session for the prompt");f=n,eC&&(e6(eC),t&&await ic(n,{type:"set_model",provider:eC.provider,modelId:eC.modelId})),nC.current&&await rp(n).catch(e=>{if(nC.current)throw e}),x=!0;let r=await ic(n,{type:"prompt",message:e,...g?.length?{images:g}:{}});r?.queued&&m(),rn(1,e)}else if(a){f=a.id,await rp(a.id),x=!0;let t=await ic(a.id,{type:"prompt",message:e,...g?.length?{images:g}:{}});t?.queued&&m()}else throw Error("No active session for the prompt");eh(null),i&&f&&rM(f,s)}catch(n){if(console.error("Failed to send message:",n),!(!x||il(n))&&f){nf.current!==s&&(nx.current={runId:s,sid:f,message:e,images:t,draftKey:nV,parkedDraftKey:S&&o?n_(o):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:d,key:c,command:i},nC.current||rS()),rM(f,s);return}if(tQ.current=!1,P(e=>iU(e,d)),n instanceof io&&n.missingCwd?eh(n.missingCwd):rb({type:"error",message:n instanceof Error?n.message:String(n)}),nQ(e,t,nV),ng.current=null,f)return void rA(f);tY.current=!1,ru("send_failed"),Q(!1),to(null),Y({type:"end"})}},[S,o,eC,a,rr,rp,rn,rM,rb,rS,rc,ru,nV,Y,rA,nQ,n0,n2,ry]);nt.current=(0,i.useCallback)(async(e,t)=>{if(t1.current)return;let n=`${t?"!!":"!"}${e}`;t1.current=!0;let r=Date.now();er({command:e,excludeFromContext:t,startedAt:r}),et(!0);let i=null;try{let s=tZ.current??a?.id??await rr();if(!s)throw Error("Unable to create a session for the shell command");await rp(s).catch(()=>{});let o=await ic(s,{type:"bash",command:e,excludeFromContext:t});tY.current&&o?(i={command:e,excludeFromContext:t,startedAt:r,result:o},t2.current=nv.current):(await n7(s),rn(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof io&&"extension_reported"===e.code||rb({type:"error",message:e instanceof Error?e.message:String(e)}),nQ(n,void 0,nV)}finally{t1.current=!1,er(i),et(!1);let e=rz.current;rz.current=null,e&&rF.current?.(e)}},[rb,nV,rp,rr,n7,rn,nQ,a]);let rB=en?.result;(0,i.useEffect)(()=>{if(X||!rB)return;let e=tZ.current;e&&n7(e,!1,!1,{force:!0})},[X,rB,n7]);let r_=(0,i.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?nQ(n,t.images,nV):n&&e.chatInputRef?.current?.prependText(n)},[nV,e.chatInputRef,nQ]),rH=(0,i.useCallback)(async()=>{let e=tZ.current;if(e){if(t1.current&&!tY.current){try{await ic(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await ic(e,{type:"abort"});t&&tT({steering:[],followUp:[]}),r_(t)}catch(e){console.error("Failed to abort:",e)}}},[r_]),rU=(0,i.useCallback)(async(e,t)=>{if(t1.current)return;let n=tZ.current;if(n){eQ(e);try{let{cancelled:r,newSessionId:i}=await ic(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&nK(i,t),m?.(i))}catch(e){console.error("Fork failed:",e),rb({type:"error",message:e instanceof Error?e.message:String(e)})}finally{eQ(null)}}},[rb,m]),rq=(0,i.useCallback)(async e=>{if(t1.current)return!1;let t=tZ.current;if(!t)return!1;try{let n=await ic(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||tZ.current!==t)return!1;return await n7(t),tZ.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[n7]);nn.current=rq;let rK=(0,i.useCallback)(async e=>{if(t1.current||tY.current||e9)return;A(e);let t=tZ.current;t&&(await re(t,e),e&&ic(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[e9,re]),rZ=(0,i.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};nc.current=n,eN(n),e6(n),null===nu.current&&eP(iZ(np.current[`${e}/${t}`])??nh.current);let r=tZ.current??await ni.current;if(!r)return;try{await ic(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tZ.current;if(!n||nw.current)return;nw.current=!0,e1({provider:e,modelId:t}),e5(!0);let r=tY.current||t1.current,i=async()=>{let e=await fetch(id(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nC.current&&tZ.current===n&&nJ(t.state)};try{let s=await ic(n,{type:"set_model",provider:e,modelId:t});e4({provider:s.provider,modelId:s.id}),nw.current=!1,r?(e1(null),await i()):await n7(n)}catch(e){console.error("Failed to set model:",e),nw.current=!1,e1(e0),rb({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await n7(n,!1,!0)}finally{nw.current=!1,e5(!1)}},[rb,e0,S,n7,eN,nJ]),rV=(0,i.useCallback)(async e=>{let t=tZ.current;if(!t||e9)return!0;e7(!0),tr(null),ts(null);try{let n=await ic(t,{type:"compact",...e?{customInstructions:e}:{}});return ts(i0(n,"manual")),await n7(t)&&rn(),!0}catch(e){return tr(e instanceof Error?e.message:String(e)),ts(null),!1}finally{e7(!1)}},[e9,n7,rn]),rJ=(0,i.useCallback)(()=>tr(null),[]),rG=(0,i.useCallback)(async e=>{let t,n=o??a?.cwd??"",r=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",i=null;try{let n=await fetch(r,e?{signal:e}:void 0);if(!n.ok){let e="";try{let t=await n.json();t&&"object"==typeof t&&"error"in t&&"string"==typeof t.error&&(e=t.error),i=ia(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${n.status})`)}t=await n.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||(eu(i),ed(i?null:t instanceof Error?t.message:String(t))),t}eu(null),es(t.models),ed(t.modelError??null),eg(t.modelScopeWarnings??[]),ex(!!t.isScoped),ev(null),ey.current=null,ej(t.thinkingLevels??{}),eS(t.thinkingLevelMaps??{});let s=t.modelList??[];eo(s);let l=t.defaultModel?s.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(e$(l?{provider:l.provider,modelId:l.id}:null),np.current=t.thinkingLevelPins??{},nh.current=iZ(t.defaultThinkingLevel),eO(iZ(t.savedDefaultThinkingLevel)),S&&!tZ.current){let e=nc.current,n=e&&(0===s.length||!!t.isScoped||s.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(nc.current=null,eN(null));let r=n?e:l&&{provider:l.provider,modelId:l.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nu.current&&eP(iZ(i)??nh.current)}},[S,o,a?.cwd]),rY=(0,i.useCallback)(()=>{if(ey.current)return;let e={};ey.current=e;let t=o??a?.cwd??"";fetch(`/api/models?scope=all${t?`&cwd=${encodeURIComponent(t)}`:""}`).then(async t=>{if(!t.ok)throw Error(`Failed to load models (HTTP ${t.status})`);let n=await t.json();ey.current===e&&(es(e=>({...n.models,...e})),ej(e=>({...n.thinkingLevels,...e})),eS(e=>({...n.thinkingLevelMaps,...e})),ev(n.modelList??[]))}).catch(t=>{ey.current===e&&(ey.current=null,rb({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rb,o,a?.cwd]);(0,i.useEffect)(()=>{!ef||!nB||eb||ea.some(e=>e.provider===nB.provider&&e.id===nB.modelId)||rY()},[eb,nB,ef,rY,ea]);let rX=(0,i.useCallback)(async e=>{let t=o??a?.cwd,n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},...e})});if(n.ok)return;let r="";try{let e=await n.json();e&&"object"==typeof e&&"error"in e&&"string"==typeof e.error&&(r=e.error)}catch{}throw Error(r||`HTTP ${n.status}`)},[o,a?.cwd]),rQ=(0,i.useCallback)(()=>{rG().catch(()=>{})},[rG]),r0=(0,i.useCallback)(async(e,t)=>{try{await rX({provider:e,modelId:t})}catch(e){rb({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rb({type:"success",message:`Default model: ${e}/${t}`}),e$({provider:e,modelId:t}),(nB?.provider!==e||nB?.modelId!==t)&&await rZ(e,t),rQ()},[rb,nB,rZ,rQ,rX]),r1=(0,i.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return ry(iu[r]);let i=tZ.current;if(!i)return ry("sideChat.error.noSession");let s=await ip(i,ry,n);return"error"in s?s.error:(g?.(s.session,t),null)},[g,e.session?.relation?.kind,ry]),r2=(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(),a=tZ.current??await rr(),o=e=>(e.handled&&(e.error?rb({type:"error",message:e.error}):e.action||rb({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!a||e9)return o({handled:!0,error:"No active session to compact"});return rV(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),o({handled:!0,action:"compact"});case"auto-compact":{if(!a)return o({handled:!0,error:"No active session"});let e=await ic(a,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await ic(a,{type:"set_auto_compaction",enabled:t}),tt(t),o({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!a)return o({handled:!0,error:"No active session to reload"});return await ic(a,{type:"reload"}),await Promise.all([n7(a,!1,!0),rt(a),rl(),rG()]),o({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return o({handled:!0,error:"No active session to name"});if(!s)return o({handled:!0,error:"Usage: /name <name>"});return await ic(a,{type:"set_session_name",name:s}),await n7(a)&&rn(),o({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return o({handled:!0,error:"No active session"});if(!k)return o({handled:!0,message:(0,iN.C$)(n3,ry)});let e=await ic(a,{type:"get_session_stats"});return e&&ty(e),k(),o({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!j)return{handled:!1};let e=await rd();if(!e||!(e.some(n8)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return j("mcp"),o({handled:!0,action:"openSettings"})}case"copy":{if(!a)return o({handled:!0,error:"No active session"});let e=await ic(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return o({handled:!0,error:"No assistant message to copy"});return await (0,tc.D)(t),o({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!a)return o({handled:!0,error:"No active session to clone"});if(tY.current||t1.current)return o({handled:!0,error:"Cannot clone while the session is running"});let e=rP.current,t=await ic(a,{type:"clone",leafId:e?.base===R&&e.lastEntryId===nT.current.at(-1)?e.leafId:R});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return o({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=o({handled:!0,message:"Cloned current session branch"});return m?.(t.newSessionId),n}case"side":{let e=await r1(s||null);return o(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return o({handled:!0,error:e instanceof Error?e.message:String(e)})}},[R,rb,rr,rV,e9,rG,n7,rl,rt,rn,j,m,k,e.chatInputRef,n3,rd,r1,ry]),r4=(0,i.useCallback)(async(e,t,n)=>{let r=tZ.current;if(n0)return void nQ(e,n,nV);if(!r){nQ(e,n,nV),rb({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 ic(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),nQ(e,n,nV),t instanceof io&&t.missingCwd)return void eh(t.missingCwd);il(t)?rb({type:"error",message:t.message}):rk()}},[rb,rk,nV,n0,nQ]),r8=(0,i.useCallback)(async(e,t)=>{await r4(e,"steer",t)},[r4]),r6=(0,i.useCallback)(async(e,t,n)=>{await r4(e,t,n)},[r4]),r3=(0,i.useCallback)(async(e,t)=>{await r4(e,"followUp",t)},[r4]),r5=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{await ic(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),r9=(0,i.useCallback)(async()=>{let e=tZ.current;if(e)try{let t=await ic(e,{type:"clear_queue"});tT({steering:[],followUp:[]}),r_(t)}catch(e){console.error("Failed to recall queued messages:",e),rb({type:"error",message:"Failed to recall queued messages"})}},[rb,r_]),ii=(0,i.useCallback)(async e=>{if("auto"===e){nu.current=null,eA(null),eF(null);return}S?(nu.current=e,eA(e)):eF(e);let t=tZ.current??await ni.current;if(t)try{await ic(t,{type:"set_thinking_level",level:e}),nC.current&&tZ.current===t&&(eB(e),eF(null))}catch(e){console.error("Failed to set thinking level:",e),eF(null)}},[S]),ih=(0,i.useCallback)(async e=>{try{await rX({thinkingLevel:e})}catch(e){rb({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rb({type:"success",message:`Default reasoning level: ${e}`}),eO(e),nU!==e&&await ii(e),rQ()},[rb,nU,ii,rQ,rX]),im=(0,i.useCallback)(async e=>{let t=(0,ik.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:iw();if(t)try{t.setItem(ij,e)}catch{}}(e),nz(e);let n=tZ.current??await ni.current;if(!n){tG.current=void 0!==t;return}try{let e=await ic(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tG.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rc(),ru("set_tools"),tj([]),tS([]),tZ.current=r,e?.recreated&&tJ.current===r&&rh(r)),ra(),tN([]),t$([]);let[i]=await Promise.all([ic(r,{type:"get_state"}),rt(r)]);nC.current&&tZ.current===r&&(eY(i.systemPrompt??""),nJ(i))}catch(e){console.error("Failed to set tools:",e)}},[rc,ra,ru,rt,rh,nz,nJ]),ig=(0,i.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=nr.current;n&&(null!==ne.current&&(cancelAnimationFrame(ne.current),ne.current=null),t6.current=!0,t5.current=!1,t9.current=!1,td(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),t7.current=n.scrollTop)},[]),ix=(0,i.useCallback)(()=>{let e=nr.current,t=t3.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!==ne.current&&(cancelAnimationFrame(ne.current),ne.current=null),t9.current=!0,t7.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),iS=(0,i.useCallback)(()=>{let e=nr.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tY.current,s=t9.current,a=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!iD(n,r,i)||!(n<t)&&(!!(!e&&n>t&&iD(n,r,i,s))||e)}(s,t7.current,t,n,r,i?96:8);t9.current=a,t7.current=t;let o=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!iD(e,t,n,r)}(t,n,r);tp(e=>e===o?e:o),!s&&a&&i?nF("auto"):a||null===ne.current||(cancelAnimationFrame(ne.current),ne.current=null)}},[nF]),iI=(0,i.useCallback)((e,t)=>{t?.running&&(rt(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(tX.current=!!t.state.isStreaming,tQ.current=!!t.state.isPromptRunning,tY.current=!0,Q(!0),to(e=>r7(e,t.state?.isStreaming===!0)),Y({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rM(e)),t.state?.isBashRunning&&(t1.current=!0,et(!0),rR(e))),t?.state&&(void 0!==t.state.isCompacting&&e7(t.state.isCompacting),void 0!==t.state.systemPrompt&&eY(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tN(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&t$(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tT(iK(t.state.queuedMessages)))},[Y,rt,rR,rM]);tF.current=(e,t)=>{!tP.current||tV.current===e||(tP.current=!1,t_.current={count:t_.current.count+1,lastAt:Date.now(),lastReason:t},tO(e=>e+1),nC.current&&tZ.current===e&&tJ.current===e&&(rh(e),n7(e,!1,!0).then(t=>{nC.current&&tZ.current===e&&iI(e,t)})))},(0,i.useEffect)(()=>{let e=a?.id;if(!e)return;let t=!1,n=tD.current,r=async()=>{let n=await rm(e);!t&&"hidden"===document.visibilityState&&iR(n)&&tF.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let s=()=>{"visible"===document.visibilityState&&(tF.current(e,"visible"),r())};return document.addEventListener("visibilitychange",s),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",s)}},[rm,a?.id]),(0,i.useEffect)(()=>{if(nC.current=!0,eJ.current=eV.current,a){tZ.current=a.id;let e=ib(a.id);e&&(I({sessionId:a.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}),A(e.leafId),P(e.messages),B(e.entryIds),q(e.oldestEntryId),Z(e.hasMore),J(e.turnsBefore),M(null),E(!1)),n7(a.id,!e,!0,{force:!0}).then(e=>{iI(a.id,e)})}return()=>{nC.current=!1;let e=S?l:null;e&&queueMicrotask(()=>{nC.current||nl.current||nZ(e)});let t=tZ.current,n=nI.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=ib(t),r=nT.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)?iv({sessionId:t,revision:n.snapshotRevision,messages:nE.current,entryIds:nT.current,leafId:nM.current,oldestEntryId:nR.current,hasMore:nA.current,turnsBefore:nL.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nT.current}):iy(t)}rC.current(),null!==ne.current&&(cancelAnimationFrame(ne.current),ne.current=null),t4.current+=1,rc(),ru()}},[]),(0,i.useEffect)(()=>{b?.(eG)},[eG,b]),(0,i.useEffect)(()=>(y?.(ri),()=>y?.(null)),[ri,y]);let iT=(0,i.useCallback)(()=>{let e=null;try{e=tM.current?.snapshot?.()??null}catch{e=null}let t=tZ.current,n=tD.current,r=t_.current;return{pageId:(0,eE.kz)(),sessionId:t,selectedSessionId:tJ.current,mounted:nC.current,wantsStream:null!==t&&nP(t),connection:e,released:{active:tP.current,...tB.current},reattached:{...r},hiddenReleaseDueAt:tH.current,hiddenGraceMs:iA.P,graceDueAt:tU.current,run:{agentRunning:tY.current,bashRunning:t1.current,compacting:tq.current,dialogs:tK.current},lease:{renewIntervalMs:3e4,renewStartedAt:n.renewStartedAt,inFlightSince:n.inFlightSince,requests:n.requests,unanswered:n.unanswered,errors:n.errors,last:n.last&&{...n.last,reply:n.last.reply&&{...n.last.reply}}}}},[nP]);(0,i.useEffect)(()=>(w?.(iT),()=>w?.(null)),[iT,w]);let iB=X||ee||e9;(0,i.useEffect)(()=>{x&&x(N?.tree??[],R,rK,iB)},[N?.tree,R,rK,iB,x]),(0,i.useEffect)(()=>{let e=nr.current;if(e)return t7.current=e.scrollTop,e.addEventListener("scroll",iS,{passive:!0}),()=>{e.removeEventListener("scroll",iS)}},[L.length,$,iS]),(0,i.useEffect)(()=>{X||td(!1)},[X]),(0,i.useLayoutEffect)(()=>{L.length>0&&(t5.current?(t5.current=!1,t6.current=!0,ix()):t6.current?!tY.current&&t9.current&&nF("auto"):(t6.current=!0,nF("instant")))},[L.length,X,nF,ix]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await rG(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=iJ.length||(await iY(iJ[t]),e.signal.aborted))return}})(),()=>e.abort()},[rG,f]),(0,i.useEffect)(()=>{if(!ti)return;let e=setTimeout(()=>ts(null),6e3);return()=>clearTimeout(e)},[ti]);let[i_,iX]=(0,i.useState)(null),i1=(0,i.useRef)(5e3),i2=(0,i.useRef)(null),i4=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(0===tx.visible.length){i4.current=null;return}let e=tx.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tb({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tx.visible[0];if(!t||(i4.current!==t.id&&(i4.current=t.id,i1.current=5e3),tx.visible.some(e=>e.id===i_)))return;i2.current=Date.now();let n=setTimeout(()=>{tb({type:"mark_oldest_exiting"})},i1.current);return()=>{clearTimeout(n),null!==i2.current&&(i1.current=Math.max(0,i1.current-(Date.now()-i2.current)),i2.current=null)}},[tx.visible,i_]),(0,i.useEffect)(()=>{ty(null)},[L.length,eU?.tokens,eU?.percent,eU?.contextWindow]);let i8=nU??"auto",i6=tk[0]??null,i3=Math.max(0,tk.length-1),i5=tw[0]??null,i9=Math.max(0,tw.length-1),i7=(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?iE(r,s-e.length):n.get(t)??t)}return i})(D,L.length,_),[D,L.length,_]);return{data:N,loading:$,error:T,activeLeafId:R,messages:L,activeToolResults:z,toolClocks:W,entryIds:D,messageKeys:i7,historyCursor:U,hasEarlierMessages:K,earlierTurnCount:V,streamingStore:G,agentRunning:X,modelNames:ei,modelList:ea,modelError:el,missingCwd:ep??ec,modelScopeWarnings:em,isModelScopeActive:ef,allModelList:eb,modelThinkingLevels:ek,modelThinkingLevelMaps:ew,newSessionModel:eC,toolPreset:eT,thinkingLevel:i8,retryInfo:e_,contextUsage:eU,systemPrompt:eG,forkingEntryId:eX,isCompacting:e9,compactError:tn,compactResult:ti,currentModel:nD,displayModel:nB,modelSwitching:e3,sessionStats:n3,autoCompactionEnabled:te,slashCommands:th,slashCommandsLoading:tg,queuedMessages:tE,notices:tx.visible,extensionDialog:i6,waitingExtensionDialogCount:i3,extensionCustomUi:i5,waitingExtensionCustomUiCount:i9,extensionStatuses:tC,extensionWidgets:tI,respondToExtensionUi:rf,sendExtensionCustomInput:rx,isAutoModelSelection:S&&null===eC,isAutoThinkingSelection:S&&null===eR,defaultModel:eI,savedDefaultThinkingLevel:ez,agentPhase:ta,isNew:S,editEntryId:n0,promptAnchorActive:tl,showScrollToBottom:tu,sessionIdRef:tZ,scrollContainerRef:nr,lastUserMsgRef:t3,pendingScrollToUserRef:t5,initialScrollDoneRef:t6,handleSend:rD,handleAbort:rH,startSideChat:r1,handleFork:rU,handleNavigate:rq,handleModelChange:rZ,handleCompact:rV,handleSteer:r8,handleFollowUp:r3,handlePromptWithStreamingBehavior:r6,handleAbortCompaction:r5,dismissCompactError:rJ,handleRecallQueue:r9,handleBuiltinSlashCommand:r2,handleEditContent:n4,cancelEdit:n0?n6:void 0,addNotice:rb,setNoticePaused:iX,handleToolPresetChange:im,handleThinkingLevelChange:ii,handleSetDefaultModel:r0,handleSetDefaultThinkingLevel:ih,loadTools:rt,loadSlashCommands:rl,loadAllModels:rY,setActiveLeafId:A,setData:I,setMessages:P,loadContext:re,scrollToBottom:nF,scrollUserMsgToTop:ix,scrollToMessage:ig,dispatch:Y,setAgentRunning:Q,setForkingEntryId:eQ,bashRunning:ee,pendingBash:en,handleAgentEventRef:t8}}({session:o,sessionRunning:h,newSessionCwd:m,newSessionDraftKey:g,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:en,onSessionEnded:y,onToolEnd:k,onAttentionNeeded:j,onSessionCreated:w,onSessionForked:S,onSideSession:N,modelsRefreshKey:I,chatInputRef:$,onBranchDataChange:E,onSystemPromptChange:T,onSystemToolsChange:M,onSystemInfoLoaderChange:R,onSessionStatsPanelOpen:P,onOpenSettings:z,onDebugSnapshotReaderChange:A,t:G,deferInitialScroll:!!ei}),tz=i1(eb,i2),tO=i1(eb,i4),tW=(0,i.useCallback)(()=>eb.getState().streamingMessage,[eb]),tF=ev||ey,tD=(0,i.useCallback)((e,t)=>{th(e,{value:rL(t),images:rP(t)})},[th]);(0,i.useEffect)(()=>{if(ev&&J)return J()},[ev,J]);let[tB,t_]=(0,i.useState)(null),[tH,tU]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(!1),[tZ,tV]=(0,i.useState)(null),tJ=(0,i.useRef)(null),tG=(0,i.useRef)(null),tY=(0,i.useCallback)(()=>{t_(null),tU(!1),tV(null)},[]);(0,i.useEffect)(()=>{_||tY()},[_,tY]);let tX=(0,i.useCallback)(()=>{if(!_||tH)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=t5.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void t_(null);let r=e.toString().trim();if(!r)return void t_(null);let i=t.getBoundingClientRect();t_({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))})},[_,tH]);(0,i.useEffect)(()=>{tH&&tB&&tG.current?.insertIfEmpty(nP(tB.text))},[tH,tB]),(0,i.useLayoutEffect)(()=>{let e=tJ.current;if(!e||!tB)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(tB.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tB.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)}},[tB,tH,tZ]),(0,i.useEffect)(()=>{if(!tB)return;let e=e=>{tH||tJ.current?.contains(e.target)||tY()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tq||tY())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tB,tH,tq,tY]);let tQ=(0,i.useCallback)(()=>{tB&&($?.current?.insertQuote(nP(tB.text)),tY())},[$,tB,tY]),t0=(0,i.useCallback)(async e=>{if(!tq&&e.trim()&&tB){tK(!0),tV(null);try{let t=await tp(e,tB.text);if(!t)return void tY();tG.current?.restoreSubmission(e),tV(t)}catch(t){tG.current?.restoreSubmission(e),tV(t instanceof Error?t.message:String(t))}finally{tK(!1)}}},[tB,tq,tY,tp]),t1=(0,i.useCallback)(async e=>{let t;try{t=await tp(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&($?.current?.restoreSubmission(e),e6({type:"error",message:t}))},[e6,$,tp]),t2=(0,i.useRef)(!1);(0,i.useEffect)(()=>{el||ed||!H||t2.current||(t2.current=!0,U?.(),td(H))},[H,el,ed,td,U]),(0,i.useEffect)(()=>{let e=!!eZ&&!et.current;et.current=!!eZ,X&&e&&Q.current()},[X,eZ]),(0,i.useEffect)(()=>{C||(a=tF?tu:null)},[C,tF,tu]);let[t4,t8]=(0,i.useState)(50),[t6,t3]=(0,i.useState)(null),t5=(0,i.useRef)(null),t9=(0,i.useRef)(null),t7=(0,i.useRef)(!1),ne=(0,i.useRef)(!1),nt=(0,i.useRef)(ei);nt.current=ei;let[nn,nr]=(0,i.useState)(null),ni=ec[eh.indexOf(nn?.entryId??"")],na=ni?.role==="assistant"?nn?.blockIndex===void 0?ni.content.find(e=>"text"===e.type):ni.content[nn.blockIndex]:void 0,no=(0,i.useRef)({entryIds:eh,historyCursor:eg,hasEarlierMessages:ef});no.current={entryIds:eh,historyCursor:eg,hasEarlierMessages:ef};let nl=(0,i.useRef)(null),nc=(0,i.useCallback)(async(e,t,n)=>{nl.current=t;let r=await tR(e,tA,t,n);return r||nl.current!==t||(nl.current=null),r},[tA,tR]);(0,i.useEffect)(()=>{eg!==nl.current&&(nl.current=null)},[eg]),(0,i.useLayoutEffect)(()=>{let e=o?.id,t=ta.current,n=t5.current;if(e&&p&&t&&n)return()=>{if(nt.current)return;if(iD(t.scrollTop,t.clientHeight,t.scrollHeight))return void p(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&&p(e,{atBottom:!1,...i,oldestEntryId:no.current.historyCursor})}},[el,p,ta,o?.id]),(0,i.useEffect)(()=>{d&&es(null)},[d]),(0,i.useEffect)(()=>{let e=o?.id;if(!ei||!e||el||d||ne.current)return;ne.current=!0;let t=new AbortController;return(async()=>{let n=no.current;if(n.entryIds.includes(ei.anchorEntryId)){t8(e=>Math.max(e,2*n.entryIds.length)),eo(!0);return}t7.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nc(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){tL("instant"),es(null);return}if(t8(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(ei.anchorEntryId))return void eo(!0);if(n.oldestEntryId===ei.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(tL("instant"),es(null))}finally{t7.current=!1}})(),()=>{t.abort(),es(null)}},[tA,nc,el,ei,tL,d,o?.id]),(0,i.useLayoutEffect)(()=>{let e=t5.current;if(!ei||!e||d)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===ei.anchorEntryId);if(t instanceof HTMLElement){tP(t,ei.anchorOffset),es(null);return}ea&&(tL("instant"),es(null))},[eh,ei,ea,tL,tP,d,t4]),(0,i.useEffect)(()=>{if(!d||el)return;let e=new AbortController;return(async()=>{let t=no.current,n=t.entryIds.includes(d.entryId);if(!n&&!tF&&t.hasEarlierMessages&&t.historyCursor&&!t7.current){t7.current=!0;let r=ta.current;r&&(t9.current=r.scrollHeight-r.scrollTop);let i=await nc(d.sessionId,t.historyCursor,{tail:200,signal:e.signal});t7.current=!1,n=!!i?.entryIds.includes(d.entryId)}e.signal.aborted||(n?(t9.current=null,t8(e=>Math.max(e,(no.current.entryIds.length+200)*2)),nr(d)):c?.(d))})(),()=>e.abort()},[d,el,tF,nc,c,ta]),(0,i.useLayoutEffect)(()=>{if(!nn||nn!==d)return;let e=`[data-entry-id="${CSS.escape(nn.entryId)}"]`,t=ta.current?.querySelector(ni?.role==="user"?e:`${e} [data-search-target]`);t&&(tP(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),nr(null),c?.(nn)},[nn,d,ni,ta,tP,c]),(0,i.useEffect)(()=>{let e=ta.current;if(!t6||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||t7.current)return;if(!ef){t9.current=e.scrollHeight-e.scrollTop,t8(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eg||eg===nl.current)return;let n=o?.id??ts.current;n&&(t7.current=!0,t9.current=e.scrollHeight-e.scrollTop,nc(n,eg).finally(()=>{t7.current=!1}))},{root:e,threshold:0});return t.observe(t6),()=>t.disconnect()},[t6,t4,eg,ef,o,nc,ts,ta]),(0,i.useEffect)(()=>{t8(e=>Math.max(e,ec.length))},[ec.length]),(0,i.useEffect)(()=>{if(null==t9.current)return;let e=ta.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-t9.current),t9.current=null}},[t4,ta]);let nu=e_?[e_.sessionId,e_.sessionFile??"",e_.sessionName??"",e_.userMessages,e_.assistantMessages,e_.toolCalls,e_.toolResults,e_.totalMessages,e_.tokens.input,e_.tokens.output,e_.tokens.cacheRead,e_.tokens.cacheWrite,e_.tokens.total,e_.cost??0,e_.totalActiveMs??0].join("|"):null,np=(0,i.useRef)(e_);np.current=e_,(0,i.useEffect)(()=>{L?.(np.current)},[nu,L]),(0,i.useEffect)(()=>()=>{L?.(null)},[L]);let nh=eP?`${eP.percent??"null"}|${eP.contextWindow}|${eP.tokens??"null"}`:null,nm=(0,i.useRef)(eP);nm.current=eP,(0,i.useEffect)(()=>{O?.(nm.current)},[nh,O]),(0,i.useEffect)(()=>()=>{O?.(null)},[O]);let ng=(0,i.useCallback)(async e=>{let t=o?.cwd??m;if(!t)return void e6({type:"warning",message:G("chat.dropNeedsCwd")});try{let{status:n,data:r}=await (0,nO.Zn)(t,e,"skip");if(200!==n&&207!==n)throw Error(r.error??`HTTP ${n}`);let i=r.uploaded??[],s=r.skipped??[],a=(0,nO.JI)(e,[...i,...s]);for(let e of(a&&$?.current?.insertText(a),i.length>0&&(e6({type:"success",message:G("chat.dropUploaded",{count:i.length})}),F?.()),s.length>0&&e6({type:"warning",message:G("chat.dropAlreadyExists",{names:s.join(", ")})}),r.errors??[]))e6({type:"error",message:G("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){e6({type:"error",message:G("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[e6,$,m,F,o?.cwd,G]),nf=(0,i.useCallback)(e=>{let{images:t,files:n,folders:r}=(0,nO.H7)(e);t.length>0&&$?.current?.addImages(t),r.length>0&&e6({type:"warning",message:G("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&ng(n)},[e6,$,G,ng]),nx=(0,i.useCallback)(e=>{nf(e.map(e=>({kind:"file",file:e})))},[nf]),{isDragOver:nv,handleDragEnter:ny,handleDragOver:nk,handleDragLeave:nw,handleDrop:nS}=(0,i6.J)(nf),nC=ec.filter(e=>(0,nb.Y0)(e)||"assistant"===e.role),nz=(0,i.useMemo)(()=>{let e=new Map(eu);for(let t of ec)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eu,ec]),nF=(0,i.useMemo)(()=>new WeakMap,[]),nD=(0,i.useMemo)(()=>(0,nI.n_)(ec),[ec]),nB=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ec.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}(ec[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ec]),nH=(t=nC.length,(s=(0,i.useRef)([])).current=Array(t).fill(null).map((e,t)=>s.current[t]??null),s),nU=(0,i.useCallback)(()=>{t8(e=>Math.max(e,2*ec.length))},[ec.length]),nV=tn&&0===ec.length&&!tz&&!tF;e1(ta,!!o?.id||!nV);let nJ=o?.cwd??m??void 0,nX=function(e,t,n){let[r,s]=(0,i.useState)(()=>new Map);return(0,i.useEffect)(()=>{let r=nE(e,t);if(0===r.length)return;let i=!1;return Promise.allSettled(r.map(async e=>({sessionId:e.sessionId,entry:await function(e,t,n){let r=nM.get(e);if(r)return r;let i=nR.get(e);if(void 0!==i&&Date.now()-i<3e4)return Promise.resolve(null);let s=(async()=>{try{var r;let{messages:i,cwd:s}=await nT(e,5),a=new Map;for(let e of i)"toolResult"===e.role&&a.set(e.toolCallId,e);return{files:(r=t??s??n,nN(i.flatMap(e=>"assistant"===e.role?e.content??[]:[]),a,r))}}catch{return nR.set(e,Date.now()),null}})();return nM.set(e,s),s.catch(()=>nR.set(e,Date.now())),s}(e.sessionId,e.cwd,n)}))).then(e=>{i||s(t=>{let n=null;for(let r of e){if("fulfilled"!==r.status)continue;let{sessionId:e,entry:i}=r.value;!i||t.get(e)||(n??=new Map(t)).set(e,i.files)}return n??t})}),()=>{i=!0}},[e,t,n]),r}(ec,nz,nJ),nQ=(0,i.useRef)(null),n0=(0,i.useRef)(0),n1=(0,i.useRef)(null),n2=(0,i.useRef)(!1),n4=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nQ.current;if(!ev||!tl){n4.current=null,n0.current=0,n2.current=!1,e&&(e.style.height="");return}let t=ta.current,n=t5.current,r=to.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let a;if(i||ta.current!==t||t5.current!==n||to.current!==r||nQ.current!==e)return;let o=t.getBoundingClientRect().top,l=Math.max(0,r.getBoundingClientRect().top-o+t.scrollTop-16),d=e.getBoundingClientRect().top-o+t.scrollTop,c=(s=t.clientHeight,0===(a=Math.max(0,l))?0:Math.max(0,Math.ceil(a+s-Math.max(0,d)))),u=!n2.current;u&&(n2.current=!0),c!==n0.current&&(n0.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tM())};n4.current=s,s();let a="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==n1.current||(n1.current=requestAnimationFrame(()=>{n1.current=null,s()}))});return a?.observe(t),a?.observe(n),a?.observe(r),()=>{i=!0,n4.current===s&&(n4.current=null),a?.disconnect(),null!==n1.current&&(cancelAnimationFrame(n1.current),n1.current=null)}},[ev,to,ec.length,tl,ta,tM]);let n6=(0,i.useCallback)(()=>{n4.current?.()},[]);(0,i.useLayoutEffect)(n6,[tz,tO,n6]);let n3=eD?eT[`${eD.provider}:${eD.modelId}`]??null:null,n5=eD?eM[`${eD.provider}:${eD.modelId}`]??null:null,n9=(0,r.jsx)(r_,{ref:$,onSend:td,onAbort:tu,onSideChat:N&&!l(o?.relation)?t1:void 0,onSteer:ev?tb:void 0,onFollowUp:ev?tv:void 0,onPromptWithStreamingBehavior:ev?ty:void 0,isStreaming:tF,model:eD,isAutoModelSelection:e3,modelNames:ej,modelList:ew,modelError:eS,missingCwd:eC,modelScopeWarnings:eN,allModelList:e$,onLoadAllModels:eI?tT:void 0,onModelChange:tf,modelSwitching:eB,defaultModel:e7,onSetDefaultModel:tI,onCompact:o||tn?tx:void 0,onAbortCompaction:tk,isCompacting:eO,compactError:eW,onDismissCompactError:tj,compactResult:eF,toolPreset:eR,onToolPresetChange:o&&!l(o.relation)||tn?tC:void 0,thinkingLevel:eA,isAutoThinkingSelection:e9,onThinkingLevelChange:o||tn?tN:void 0,availableThinkingLevels:n3,thinkingLevelMap:n5,savedDefaultThinkingLevel:te,onSetDefaultThinkingLevel:o||tn?t$:void 0,retryInfo:eL,queuedMessages:eq,inputHistory:nB,onRecallQueue:tw,slashCommands:eH,slashCommandsLoading:eU,onLoadSlashCommands:tE,onBuiltinCommand:tS,soundEnabled:q,onSoundToggle:K,onAudioUnlock:V,draftKey:o?.id??g??void 0,cwd:o?.cwd??m,onAttachFiles:nx});return el?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:G("chat.loadingSession")}):ed?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ed}):(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:ny,onDragOver:nk,onDragLeave:nw,onDrop:nS,children:[nv&&(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*!Y,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(si,{notices:eK,floating:!0,onPauseChange:e8})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eZ&&(0,r.jsx)(so,{request:eZ,waitingCount:eV,onRespond:e2},eZ.id),eJ&&(0,r.jsx)(sl,{request:eJ,waitingCount:eG,onInput:e4},eJ.id),!nV&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:ta,className:"scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:ei?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:t5,onPointerUp:tX,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=ec.length-1;e>=0;e--)if("user"===ec[e].role){s=e;break}let a=-1;for(let e=ec.length-1;e>=0;e--)if((0,nb.Y0)(ec[e])){a=e;break}let l=new Map,d=0;ec.forEach((e,t)=>{((0,nb.Y0)(e)||"assistant"===e.role)&&l.set(t,d++)});let c=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??ec[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,r.jsx)(sn,{},"side-chat-divider");if((0,nb.zZ)(n))return null;let a=!1===t.withNotices?[]:(0,iW.YQ)(ec[e]),d=(0,nb.Y0)(n)||"assistant"===n.role,c=l.get(e),u=t.keyPrefix??"message",p=em[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<ec.length;t++){let e=ec[t].role;if("user"===e)break;if("assistant"===e){h=!1;break}}h&&tz&&e===ec.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let m=(0,r.jsx)(nW.Dx,{message:n,toolResults:nz,toolClocks:ep,modelNames:ej,cwd:nJ,onOpenFile:W,onOpenSubagent:D,onEnterSubagent:B,entryId:eh[e],searchBlock:eh[e]===nn?.entryId?na:void 0,onFork:ey||tn?void 0:tD,forking:ez===eh[e],onEditContent:tF?void 0:tm,onCancelEdit:tg,isEditing:tr===eh[e],showTimestamp:h,prevTimestamp:e>0?ec[e-1].timestamp:void 0,sessionId:o?.id??ts.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tx:void 0,isCompacting:t.recoverTruncation?eO:void 0,compactError:t.recoverTruncation?eW:void 0},`${u}-view-${p}`),g=a.length>0?(0,r.jsx)(i3.yt,{notices:a},`${u}-notices-${p}`):null;return d&&void 0!==c?(0,r.jsxs)("div",{"data-entry-id":eh[e],ref:!1===t.attachRef?void 0:t=>{nH.current[c]=t,e===s&&(to.current=t)},children:[m,g]},`${u}-${p}`):(0,r.jsxs)(i.Fragment,{children:[m,g]},`${u}-${p}`)},u=[];for(let e=0;e<ec.length;){let t,n=ec[e],i=(0,nb.Y0)(n);if(!i&&0!==e){u.push(c(e)),e+=1;continue}let s=i?e:-1,o=i?e:0,d=e+1;for(;d<ec.length&&!(0,nb.Y0)(ec[d]);)d+=1;let p=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&(0,nb.dQ)(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}(ec,s,d);if(-1===p||(tF||tz)&&d===ec.length&&s===a){for(let e=o;e<d;e++)u.push(c(e));e=d;continue}i&&u.push(c(s));let h=i&&eh[s]?(0,nL.G)(ec,s,d):void 0,m=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=(0,nb.dQ)(t),i=r.length>0||(0,nb.mc)(t)||(0,nb.PC)(t)||(0,nb.oG)(t)?nA(t,r):null,s=t.content.indexOf(r[0]),a={answer:i,process:nA(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,a),a}(nF,ec[p]),g=m.answer,f=[],x=0,b=0,v=!1;for(let e=s+1;e<=p;e++){let n=ec[e];if("custom"===n.role){if((0,nb.zZ)(n))continue;v||=!!(nn&&nn.entryId===eh[e]),x+=1,f.push(c(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let i=e===p?m.process:n,s=e!==p||!g,a=(0,nb.TC)(i);if(0===a.length){let t=s?(0,iW.YQ)(n):[];t.length>0&&f.push((0,r.jsx)(i3.yt,{notices:t},`process-notices-${em[e]}`));continue}t??=l.get(e),b+=(0,nb._q)(a),x+=1,v||=!!(nn&&eh[e]===nn.entryId&&(!na||a.includes(na))),f.push(c(e,{attachRef:!1,keyPrefix:"process",messageOverride:i,showTimestamp:!1,withNotices:s}))}if(0===x)u.push(...f);else if(f.length>0){let e=(0,nb.sE)(g),n=(0,iW.Uv)(ec.slice(s+1,g?p:p+1));u.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nH.current[t]=e},children:(0,r.jsx)(se,{messageCount:x,toolCallCount:b,durationMs:h,cacheMisses:n,defaultExpanded:!e,reveal:v,t:G,children:f},e?"answered":"unanswered")},`process-group-${em[o]}`))}if(g){let e=[];for(let t=s+1;t<=p;t++){let n=ec[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=nN(e,nz,nJ);for(let e of nE(ec.slice(s+1,p+1),nz))for(let n of nX.get(e.sessionId)??[])t.some(e=>e.filePath===n.filePath)||t.push(n);let n=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)}(m,t);u.push(c(p,{messageOverride:g,writtenFiles:n,turnDurationMs:0===f.length?h:void 0,recoverTruncation:d===ec.length&&!tz&&!(0,nb.D6)(g)}))}for(let e=p+1;e<d;e++)u.push(c(e));e=d}let{startIndex:p}=(t=Math.min(Math.max(t4,0),Math.max(e=u.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||ef;return(0,r.jsxs)(r.Fragment,{children:[h&&(0,r.jsx)("div",{ref:t3,className:"py-3 text-center text-xs text-text-muted",children:G("chat.loadEarlier")}),u.slice(p)]})})(),tz&&tO&&(0,r.jsx)(sr,{store:eb,onCommit:n6,toolResults:nz,modelNames:ej,cwd:nJ,onOpenFile:W,onOpenSubagent:D,onEnterSubagent:B}),(ev||eO)&&!tO&&(tt||eO)&&(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}(tt,G,eO,(eq?.steering.length??0)+(eq?.followUp.length??0))})}),ey&&!ek&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:G("chat.runningCommand")})}),ek&&(0,r.jsx)(nW.Dx,{message:{role:"bashExecution",command:ek.command,output:"",...ek.result,excludeFromContext:ek.excludeFromContext,timestamp:ek.startedAt},sessionId:o?.id??ts.current??void 0,onOpenSubagent:D,onEnterSubagent:B}),ek?.liveOutput&&!ek.result&&(0,r.jsx)("div",{"aria-live":"off",className:"rounded-md border border-border px-2.5 py-1.5 font-mono text-[12px] leading-[1.45] text-text-muted",style:{marginTop:-2,background:"var(--tool-bg)"},children:(0,r.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:`${1.45*nb.OP}em`},children:(0,r.jsx)("span",{children:(0,nb.Kj)(ek.liveOutput)})})}),(0,r.jsx)("div",{ref:nQ,"aria-hidden":"true"})]})})}),Y||ei?null:(0,r.jsx)(r4,{messages:ec,getStreamingMessage:tW,scrollContainer:ta,messageRefs:nH,onRevealHistory:nU,turnsBefore:ex})]})]}),_&&tB&&(0,e5.createPortal)((0,r.jsx)("div",{ref:tJ,role:tH?"dialog":"toolbar","aria-label":G(tH?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:tB.top,left:tB.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tH?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tH?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tH?(0,r.jsxs)("fieldset",{disabled:tq,"aria-busy":tq,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:G("chat.askInSideChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:G("i18n.close"),"aria-label":G("i18n.close"),disabled:tq,onClick:tY,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)(r_,{ref:tG,compact:!0,onSend:t0,onAbort:tY,isStreaming:!1}),tZ&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tZ})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:G("chat.quoteSelection"),"aria-label":G("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:tQ,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:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}),(0,r.jsx)("path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"})]}),(0,r.jsx)("span",{children:G("chat.quoteSelection")})]}),N&&!l(o?.relation)&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:G("chat.askInSideChat"),"aria-label":G("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tU(!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.jsx)("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:"M21 12a8 8 0 0 1-8 8H5.5a2 2 0 0 1-1.4-3.4A8 8 0 1 1 21 12z"})}),(0,r.jsx)("span",{children:G("chat.askInSideChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!nV&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:36*!Y,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${ti&&!ei?" is-visible":""}`,title:G("chat.scrollToLatest"),"aria-label":G("chat.scrollToLatest"),onClick:()=>tL("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"})})})}),nV&&(0,r.jsx)("div",{className:"new-session-hero",style:{paddingLeft:16,paddingRight:Y?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)(ns.A,{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.16.2"]}),(0,r.jsx)(i7,{label:e=>G("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.5.2"]})]})]})]}),f]})}),(0,r.jsx)(rH.Z,{snapshot:nD}),n9,(0,r.jsx)(r9,{statuses:eY,widgets:e0,onCommand:td,commandsDisabled:tF})]}),nV&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function sn(){let{t:e}=(0,eX.s)();return(0,r.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,r.jsx)("span",{children:e("sideChat.divider")}),(0,r.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let sr=(0,i.memo)(function(e){let{store:t,onCommit:n,toolResults:s,modelNames:a,cwd:o,onOpenFile:l,onOpenSubagent:d,onEnterSubagent:c}=e,u=i1(t,i8);return((0,i.useLayoutEffect)(n,[u,n]),u)?(0,r.jsx)(nW.Dx,{message:u,toolResults:s,isStreaming:!0,modelNames:a,cwd:o,onOpenFile:l,onOpenSubagent:d,onEnterSubagent:c}):null});function si(e){let{notices:t,floating:n=!1,onPauseChange:s}=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,a)=>{var o;let l,d,c,u="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>s?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||s?.(null)},onFocus:()=>s?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||s?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(a!==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:u,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:(o=e.message,l=[],d=(e,t)=>{if(!t)return;let n=l[l.length-1];n?.kind===e?n.text+=t:l.push({kind:e,text:t})},c=!1,o.split("\n").forEach((e,t)=>{let n=nh.test(e);t>0&&d(n&&c?"art":"text","\n"),d(n?"art":"text",e),c=n}),l).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):(0,r.jsx)(i.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(nm)){let i=function(e){let t=0,n=0;for(let r of e)"("===r?t+=1:")"===r&&(n+=1);let r=e.length;for(;r>0;){let i=e[r-1];if(ng.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/.test(i))continue;let s=r.index??0;s>n&&t.push({kind:"text",text:e.slice(n,s)}),t.push({kind:"link",text:i}),n=s+i.length}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t})(e.text).map((e,n)=>"link"===e.kind?(0,r.jsx)("a",{href:e.text,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,wordBreak:"break-all"},children:e.text},`${t}-${n}`):e.text)},t))})]},e.id)})})}function ss(e){let{count:t}=e,{t:n}=(0,eX.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 sa(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 so(e){let{request:t,waitingCount:n,onRespond:s}=e,{t:a}=(0,eX.s)(),[o,l]=(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,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),x=(0,i.useCallback)(()=>f(e=>!e),[]),[b,v]=(0,i.useState)(()=>Date.now()),y=(0,i.useCallback)(e=>e?.focus(),[]),k=function(e){if("select"===e.method&&e.options.length>0)return nd(e.options[0]);if("confirm"===e.method){let t=nd(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-b)/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&&m(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(()=>v(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let w=null!==j&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:a("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:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:nd(t.title)}),k&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:k}),(0,r.jsx)(ss,{count:n}),w,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("chat.extensionExpand")})]}):(0,r.jsxs)("div",{ref:u,role:"dialog","aria-label":nd(t.title),style:{pointerEvents:"auto",width:g?"100%":`min(${h??560}px, 100%)`,maxHeight:g?"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:nd(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:a("chat.extensionRequest")}),(0,r.jsx)(ss,{count:n}),w]})]}),(0,r.jsx)("button",{type:"button",onClick:x,title:a(g?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":a(g?"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)(sa,{expanded:g})}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:a("chat.extensionCollapse"),"aria-label":a("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)(nF.m,{children:nd(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":nd(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)(nF.m,{children:nd(e)})})},e))}),"input"===t.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:t.placeholder,onChange:e=>l(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=>l(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:a("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:a("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:a("chat.submit")}):null]})]})})}function sl(e){let{request:t,waitingCount:n,onInput:s}=e,{t:a}=(0,eX.s)(),o=(0,i.useRef)(null),l=(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(nl,""),i=nd(e).trimEnd();if(t.test(i))continue;let s=e,a=np(s);("│"===a||"┃"===a)&&" "===np(s=nu(s,0))&&(s=nu(s,0));let o=function(e){let t=nc(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),l=o>=0?nc(s)[o]?.char:void 0;("│"===l||"┃"===l)&&(s=nu(s,o)),n.push(function(e){let t=e;for(;;){let e=nc(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&&""===nd(n[0]).trim();)n.shift();for(;n.length>0&&""===nd(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(nl,""))}(t.lines),p=u.map(nd).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:a("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:a("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)(ss,{count:n}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:a("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":a("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(l.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=nx[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":" ":nf[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),s(t,n))},onInput:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&s(t,n)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.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:a("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(ss,{count:n}),(0,r.jsx)("button",{type:"button",onClick:()=>c(!0),"aria-expanded":!0,title:a("chat.extensionCollapse"),"aria-label":a("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:a("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)(r6,{text:u.join("\n")})})]})})}let sd=null,sc="";function su(e){let{context:t,mobile:n,initialFocus:s,onInitialFocusDone:a,onPick:o,onUseDefaultDirectory:l,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u}=e,{t:p}=(0,eX.s)(),[h,m]=(0,i.useState)(()=>sc),g=(0,i.useRef)(null),f=(0,i.useRef)(s),x=(0,i.useRef)(a);return x.current=a,(0,i.useEffect)(()=>{if(sc)return;let e=!1;return(sd??=fetch("/api/home").then(e=>e.json()).then(e=>sc=e.home??"").catch(()=>(sd=null,""))).then(t=>{!e&&t&&m(t)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=f.current;if(!e)return;f.current=null,x.current();let t=g.current;e$(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,r.jsx)("div",{className:"new-session-context",children:(0,r.jsx)(tY,{handleRef:g,layout:"inline",context:t,mobile:n,label:p("workspace.newSessionContext"),homeDir:h,newWorktreeTitle:p("sidebar.newWorktreeForSession"),onPick:o,onUseDefaultDirectory:l,onOpenFolder:d,onRefreshWorktrees:c,onCreateWorktree:u})})}var sp=n(30392),sh=n(90137),sm=n(88545),sg=n(96793),sf=n(68929);let sx=["general","models","skills","agents","plugins","mcp","channels","automations"],sb="pi-web:settings-navigation",sv=new Set(["skills","agents","plugins"]);function sy(e){return sv.has(e)}function sk(){try{return window.localStorage}catch{return null}}function sj(e){let t=e.getItem(sb);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 sw(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e||"channels"===e||"automations"===e?e:null}function sS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sk();if(t)try{let n=sj(t);n.section=e,t.setItem(sb,JSON.stringify(n))}catch{}}function sC(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:sk();if(!n)return null;let r=sw(e,t);if(!r)return null;try{let e=sj(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function sN(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:sk();if(!r||!t)return;let i=sw(e,n);if(i)try{let e=sj(r);e.selections={...e.selections,[i]:t},r.setItem(sb,JSON.stringify(e))}catch{}}var sI=n(61958);let s$="llama.cpp";function sE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class sT extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function sM(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 sR={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class sA extends Error{constructor(e,t){super(sR[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function sL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sP(e){return!sL(e)||"string"!=typeof e.id||e.id.trim().length>0}function sz(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sO(e){let t=sz(e.inputLimits)?e.inputLimits.images:void 0,n=sz(t)?t.resize:void 0;return sz(n)?n.maxBytes:void 0}function sW(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 sF(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 sD 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 sB=["input","output","cacheRead","cacheWrite"];function s_(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 sH(e){if(!sU(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 sU(e){return sB.some(t=>""!==e[t].trim())}function sq(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function sK(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function sZ(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function sV(e,t,n,r){let i=e.providers??{},s=i[n],a=s?.models;if(!a||r.every((e,t)=>e===t))return null;let o=t.get(n);return o&&t.set(n,r.map(e=>o[e]??null)),{config:{...e,providers:{...i,[n]:{...s,models:r.map(e=>a[e])}}},providerName:n,order:r}}function sJ(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 sG(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function sY(e){return e.name?.trim()||e.id}function sX(e){let t=new Map;for(let[n,r]of Object.entries(e.providers??{}))"string"==typeof r.name&&t.set(n,r.name);return t}function sQ(e){let{embedded:t,title:n,subtitle:i,closeLabel:s="Close",onClose:a,children:o,width:l=900,height:d="78vh"}=e,c=t?void 0:{"--config-panel-width":`${l}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||a()},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:a,title:s,"aria-label":s,children:"\xd7"})]}),o]})})}let s0=(0,i.createContext)(null);function s1(){return(0,i.useContext)(s0)??s2}let s2={detailOpen:!1,openDetail:()=>{},closeDetail:()=>{},reportDetailTitle:()=>{}};function s4(e,t){let{detailOpen:n,reportDetailTitle:r}=s1(),s=(0,i.useRef)(null);return(0,i.useLayoutEffect)(()=>{let t=s.current;if(!e||!n||!t||t.closest("[hidden]"))return;let i=(t.querySelector(".config-sidebar-text")??t).textContent?.trim();i&&r(i)}),e=>{s.current=e,"function"==typeof t?t(e):t&&(t.current=e)}}function s8(e){let{children:t}=e,n=(0,i.useContext)(s0);return(0,r.jsx)("div",{className:"config-split-view","data-pane":n?n.detailOpen?"detail":"list":void 0,children:t})}function s6(e){let{children:t}=e;return(0,r.jsx)("aside",{className:"config-sidebar",children:t})}function s3(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-sidebar-list",children:t})}function s5(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 s9(e){let{enabled:t,total:n,checked:i,label:s,disabled:a=!1,loading:o=!1,describedBy:l,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)(aw,{checked:i??(n>0&&t===n),disabled:a,loading:o,label:s,describedBy:l,onChange:d})]})}function s7(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 ae(e){let{active:t=!1,className:n,children:i,onClick:s,ref:a,...o}=e,{openDetail:l}=s1(),d=s4(t,a);return(0,r.jsx)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||l()},"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:i})}function at(e){let{className:t,...n}=e;return(0,r.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function an(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function ar(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function ai(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function as(e){let{className:t,...n}=e;return(0,r.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function aa(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-title",children:t})}function ao(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-section-title",children:t})}function al(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 ad(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-detail-grid",children:t})}function ac(e){let{label:t,tone:n="muted",mono:i=!1,className:s,style:a,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:a,children:o})]})}function au(e){let{scope:t,children:n}=e;return(0,r.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function ap(e){let{value:t,options:n,label:s,disabledReason:a,size:o="default",onChange:l,children:d}=e,c=(0,i.useId)(),u=a&&n.some(e=>e.disabled)?a: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||l(e.value)},children:e.label},e.value))}),d]}),u&&(0,r.jsx)("span",{id:c,className:"config-scope-switch-reason",children:u})]})}function ah(e){let{value:t,options:n,label:s,path:a,disabledReason:o,onChange:l,children:d}=e;return(0,r.jsxs)("div",{className:"config-save-target",children:[(0,r.jsx)(ap,{value:t,options:n,label:s,disabledReason:o,size:"small",onChange:l,children:(0,r.jsx)("span",{className:"config-save-target-path",children:"string"==typeof a?a.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,r.jsxs)(i.Fragment,{children:[e,(0,r.jsx)("wbr",{})]},t):e):a})}),d]})}function am(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)(aa,{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 ag(e){let{title:t,catalogs:n,target:s,inputLabel:a,inputId:o,placeholder:l,value:d,canSubmit:c,normalizeValue:u,onValueChange:p,onSubmit:h,examplesLabel:m,examples:g,error:f,multiline:x=!1,children:b}=e,v=(0,i.useRef)(null),y=(0,i.useRef)(null);(0,i.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():v.current?.focus()},[x]);let k=e=>{if(!u)return;let t=e.clipboardData.getData("text"),n=u(t);n!==t&&(e.preventDefault(),p(n))};return(0,r.jsxs)(an,{className:"is-fill",children:[(0,r.jsx)(am,{title:t,catalogs:n,target:s}),(0,r.jsx)(al,{label:a,children:x?(0,r.jsx)("textarea",{id:o,ref:y,value:d,"aria-label":a,className:"config-add-source-input is-multiline",placeholder:l,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:k,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:v,value:d,"aria-label":a,className:"config-add-source-input",placeholder:l,onChange:e=>p(e.target.value),onPaste:k,onBlur:e=>{u&&p(u(e.currentTarget.value))},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&"Enter"===e.key&&c&&h()}})}),b,g.length>0&&(0,r.jsxs)("div",{className:"config-add-source-examples",children:[(0,r.jsx)("div",{className:"config-add-source-examples-label",children:m}),(0,r.jsx)("div",{className:"config-add-source-example-list",children:g.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))})]}),f&&(0,r.jsx)("div",{role:"alert",className:"config-add-source-error",children:f})]})}function af(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 ax(e){let{id:t,message:n,trustLabel:i,trusting:s=!1,onTrust:a}=e;return(0,r.jsx)(af,{id:t,action:a&&i?(0,r.jsx)(aj,{size:"small",onClick:a,disabled:s,children:i}):void 0,children:n})}function ab(e){let{children:t}=e;return(0,r.jsx)("div",{className:"config-empty-state",children:t})}function av(e){let{children:t,style:n}=e;return(0,r.jsx)("div",{className:"config-detail",style:n,children:t})}function ay(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 ak(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 aj(e){let{variant:t="secondary",size:n="default",className:i,children:s,...a}=e;return(0,r.jsx)("button",{type:"button",...a,className:["config-button",`config-button-${t}`,`config-button-${n}`,i].filter(Boolean).join(" "),children:s})}function aw(e){let{checked:t,disabled:n=!1,loading:i=!1,size:s="default",label:a,describedBy:o,onChange:l}=e,d=n||i;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":i||void 0,"aria-label":a,"aria-describedby":o,title:a,disabled:d,className:`config-switch${"small"===s?" is-small":""}${i?" is-loading":""}`,onClick:()=>l(!t),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function aS(e){let{active:t=!1,children:n,className:i,onClick:s,ref:a,...o}=e,{openDetail:l}=s1(),d=s4(t,a);return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...o,ref:d,onClick:e=>{s?.(e),e.defaultPrevented||l()},"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 aC(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 aN(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 aI(e,t){let n=aN(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 a$(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function aE(e,t){return e?.providers.find(e=>e.id===t)}function aT(e){let{modelName:t,effective:n,value:i,onChange:s,disabled:a=!1,describedBy:o}=e,{t:l}=(0,eX.s)(),d=void 0!==i&&void 0===sM(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:l("models.contextWindow"),"aria-label":l("models.contextForModel",{model:t}),"aria-invalid":d||void 0,"aria-describedby":o,disabled:a,onChange:e=>s(""===e.target.value.trim()?void 0:e.target.value)})}let aM={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function aR(e){let{controller:t}=e,{t:n}=(0,eX.s)(),{view:i,pending:s}=t;if(!i)return null;let a=!i.allEnabled,o=i.stalePatterns.length;return a||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)(aj,{size:"small",onClick:t.pruneStale,disabled:null!==s,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),i.editable&&a&&(0,r.jsx)(aj,{size:"small",onClick:t.clearScope,disabled:null!==s,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function aA(e){let{providerId:t,controller:n,noteId:i}=e,{t:s}=(0,eX.s)(),{view:a,loading:o,pending:l,failure:d}=n,c=aE(a,t),u=d?d.messageKey?s(d.messageKey):d.message:null,p=aL(n,t)?i:void 0;if(o&&!a)return null;if(!c)return(0,r.jsx)(aw,{checked:!1,disabled:!0,label:s("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=aI(a,c);return(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,r.jsx)(aw,{checked:h.checked,loading:l===`provider:${c.id}`,disabled:null!==l||h.blocked,label:s("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function aL(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=aE(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=aI(n,i);return s?aM[s]:null}function aP(e){let{providerId:t,controller:n,id:i}=e,{t:s}=(0,eX.s)(),a=aL(n,t);return a?(0,r.jsx)("div",{id:i,className:"config-detail-heading-note",children:s(a)}):null}function az(e){var t;let n,{providerId:s,controller:a,contextSettings:o,emptyCatalogHint:l}=e,{t:d}=(0,eX.s)(),[c,u]=(0,i.useState)(""),{view:p,loading:h,pending:m,failure:g}=a,f=aE(p,s)??(l&&!g?{id:s,models:[],enabledCount:0}:void 0),x=function(e,t){let[n,r]=(0,i.useState)(!1),[s,a]=(0,i.useState)(null);return(0,i.useEffect)(()=>a(null),[e]),{refreshing:n,note:s,refresh:(0,i.useCallback)(()=>{r(!0),a(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?a("models.catalogOffline"):r.completed?a(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):a("models.catalogUnreachable"),r.changed&&t()}catch{a("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(s,a.refresh),b=(0,i.useId)();if((0,i.useEffect)(()=>u(""),[s]),h&&!p)return(0,r.jsx)("div",{className:"enabled-models-empty",children:d("agents.modelsLoading")});if(!f)return g?.message?(0,r.jsx)("div",{className:"enabled-models-error",children:g.message}):(0,r.jsx)("div",{className:"enabled-models-empty",children:d("models.enabledUnavailable")});let v=(t=f.models,(n=c.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),y=aN(p,v),k=v.length!==f.models.length,j=null!==m,w=`provider:${f.id}`,S=p?.editable===!0,C=`${b}-scope`,N=`${b}-last`,I=`${b}-context`,$=S&&!y.canDisable&&y.disableRefs.length>0,E=$||S&&v.some(e=>a$(p,e)),T=(e,t)=>{k?a.setModels(w,t,e):a.setProvider(f.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:d("models.enabledSection")}),(0,r.jsx)("span",{className:"enabled-models-count",children:d("models.enabledCount",{enabled:f.enabledCount,total:f.models.length})}),(0,r.jsx)(aj,{size:"small",disabled:j||!y.canEnable,"aria-describedby":S?void 0:C,onClick:()=>T(!0,y.enableRefs),children:k?d("models.enableShown"):d("models.enableAll")}),(0,r.jsx)(aj,{size:"small",disabled:j||!y.canDisable,"aria-describedby":S?$?N:void 0:C,onClick:()=>T(!1,y.disableRefs),children:k?d("models.disableShown"):d("models.disableAll")}),(0,r.jsx)(aj,{size:"small",disabled:j||x.refreshing,title:d("models.refreshCatalogHint"),onClick:x.refresh,children:x.refreshing?d("models.refreshingCatalog"):d("models.refreshCatalog")})]}),x.note&&(0,r.jsx)("div",{className:"enabled-models-note",children:d(x.note)}),!S&&(0,r.jsx)("div",{id:C,className:"enabled-models-note",children:d("models.enabledProjectScope")}),E&&(0,r.jsx)("div",{id:N,className:"enabled-models-note",children:d("models.enabledLastModel")}),g&&(0,r.jsx)("div",{className:"enabled-models-error",children:g.messageKey?d(g.messageKey):g.message}),f.models.length>8&&(0,r.jsx)("input",{value:c,onChange:e=>u(e.target.value),placeholder:d("models.enabledFilterPlaceholder",{count:f.models.length}),"aria-label":d("models.enabledFilter"),className:"enabled-models-filter"}),o&&f.models.length>0&&(0,r.jsx)("div",{id:I,className:"enabled-models-note",children:d("models.contextOverrideHelp")}),(0,r.jsx)("div",{className:"enabled-models-list",children:0===v.length?(0,r.jsx)("div",{className:"enabled-models-empty",children:0===f.models.length&&l||d("models.enabledNoMatches")}):v.map(e=>{let t=a$(p,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:d("models.enabledPinHint"),children:e.thinkingPin}),o&&(0,r.jsx)(aT,{modelName:e.name,effective:e.contextWindow,value:i,disabled:o.disabled,describedBy:I,onChange:t=>o.onChange(e.id,t)}),(0,r.jsx)(aw,{checked:e.enabled,loading:m===e.ref,disabled:j||!p?.editable||t,label:d("models.enabledToggle",{model:e.name}),describedBy:S?t?N:void 0:C,onChange:t=>a.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function aO(e){let{message:t,hint:n,value:i,placeholder:s,submitLabel:a,inputLabel:o,disabled:l=!1,plainEnterSubmits:d=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!l&&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:l||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:a})]})]})}let aW={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},"llama.cpp":{symbol:"llama-cpp",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},Strata:{symbol:"strata",color:!1},strata:{symbol:"strata",color:!1}};function aF(e){let{id:t,size:n}=e,i=aW[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 aD=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],aB="pi-web:provider-usage:";function a_(e){let{providerId:t,enabled:n}=e;return aD.includes(t)?(0,r.jsx)(aH,{providerId:t,enabled:n}):null}function aH(e){let{providerId:t,enabled:n}=e,[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),{locale:m,t:g}=(0,eX.s)();(0,i.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),a(null);try{let e=localStorage.getItem(`${aB}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&a(t)}}catch{try{localStorage.removeItem(`${aB}${t}`)}catch{}}return c(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let f=(0,i.useCallback)(async()=>{l(!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){a(n);try{localStorage.setItem(`${aB}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else c(n.message??g("providerUsage.queryFailed"))}catch(e){c(e instanceof Error?e.message:g("providerUsage.queryFailed"))}finally{l(!1)}},[t,g]),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:g("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:f,disabled:!n||o,title:g(o?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":g(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(m),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:g("providerUsage.updated",{time:(0,tm.ob)(x.capturedAt,m)})})]}),!x&&!d&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:g("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 ":"$"}${aU(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${aU(e.remaining)} / ${aU(e.limit)}`:e.period??t}(e,g("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 aU(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function aq(){let e=sC("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 aK(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let aZ=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],aV={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function aJ(e){let{label:t,children:n}=e;return(0,r.jsx)(al,{label:t,children:n})}let aG={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 aY(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:{...aG,fontFamily:s?"var(--font-mono)":"inherit"}})}function aX(e){let{value:t,onChange:n,placeholder:s,mono:a,onKeyDown:o,autoComplete:l="off",spellCheck:d=!1,style:c}=e,[u,p]=(0,i.useState)(!1),{t:h}=(0,eX.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:{...aG,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:l,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 aQ(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?{...aG,borderColor:"#ef4444"}:aG})}function a0(e){let{value:t,onChange:n,options:i,required:s}=e,{t:a}=(0,eX.s)();return(0,r.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...aG,color:t?"var(--text)":"var(--text-dim)"},children:[!s&&(0,r.jsxs)("option",{value:"",children:["— ",a("i18n.default")," / none —"]}),i.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function a1(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 a2(e){let{children:t}=e;return(0,r.jsx)(ao,{children:t})}function a4(e){let{name:t,editingName:n,fallbackLabel:s,provider:a,onChange:o,onEditingNameChange:l,onRename:d,onDelete:c,onAddModels:u,enabledModels:p}=e,{t:h}=(0,eX.s)(),[m,g]=(0,i.useState)({phase:"idle"}),[f,x]=(0,i.useState)(""),[b,v]=(0,i.useState)([]),y=(0,i.useRef)(0),k=(0,i.useRef)(null),j=(0,i.useId)(),w=(e,t)=>o({...a,[e]:t});(0,i.useEffect)(()=>{y.current+=1,g({phase:"idle"}),x(""),v([])},[t,a.baseUrl,a.api,a.apiKey]);let S=(0,i.useCallback)(async()=>{if("loading"===m.phase)return;let e=++y.current;g({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:{...a,models:void 0}})}),r=await n.json();if(e!==y.current)return;if(!n.ok||r.error||!r.models)return void g({phase:"error",message:r.error??`HTTP ${n.status}`});g({phase:"success",models:r.models,endpoint:r.endpoint??a.baseUrl??""})}catch(t){if(e!==y.current)return;g({phase:"error",message:t instanceof Error?t.message:String(t)})}},[m.phase,t,a]),C=new Set((a.models??[]).map(e=>e.id)),N="success"===m.phase?m.models:[],I=f.trim().toLocaleLowerCase(),$=N.filter(e=>!I||e.id.toLocaleLowerCase().includes(I)||e.name?.toLocaleLowerCase().includes(I)),E=$.slice(0,300),T=E.filter(e=>!C.has(e.id)).map(e=>e.id),M=b.filter(e=>!C.has(e)).length,R=T.length>0&&T.every(e=>b.includes(e)),A=!R&&T.some(e=>b.includes(e));return(0,i.useEffect)(()=>{k.current&&(k.current.indeterminate=A)},[A]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:h("i18n.provider")})}),(0,r.jsxs)(as,{children:[(0,r.jsx)(aA,{providerId:t,controller:p,noteId:j}),(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:c,children:h("i18n.delete")})]})]}),(0,r.jsx)(aP,{providerId:t,controller:p,id:j})]}),(0,r.jsxs)(aJ,{label:h("i18n.providerId"),children:[(0,r.jsx)(aY,{value:n,onChange:l,placeholder:"provider-id",mono:!0}),n!==t&&n.trim()&&(0,r.jsx)("button",{onClick:()=>d(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:h("i18n.rename")})]}),(0,r.jsx)(aJ,{label:h("models.providerDisplayName"),children:(0,r.jsx)(aY,{value:a.name??"",onChange:e=>o(function(e,t){if(!t.trim()){let t={...e};return delete t.name,t}return"name"in e?{...e,name:t}:{name:t,...e}}(a,e)),placeholder:s})}),(0,r.jsx)(aJ,{label:"Base URL",children:(0,r.jsx)(aY,{value:a.baseUrl??"",onChange:e=>w("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsx)(aJ,{label:"API Key",children:(0,r.jsx)(aX,{value:a.apiKey??"",onChange:e=>w("apiKey",e||void 0),placeholder:h("models.apiKeyPlaceholder"),mono:!0})}),(0,r.jsx)(aJ,{label:"API",children:(0,r.jsx)(a0,{value:a.api??"",onChange:e=>w("api",e||void 0),options:aZ})}),(0,r.jsx)(aJ,{label:"Headers",children:(0,r.jsx)(oe,{headers:a.headers,onChange:e=>w("headers",e)})}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==m.phase&&(0,r.jsx)("button",{onClick:S,disabled:"loading"===m.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"loading"===m.phase?"var(--text-dim)":"var(--text-muted)",cursor:"loading"===m.phase?"not-allowed":"pointer",fontSize:11},children:"loading"===m.phase?h("models.discoveryFetching"):h("models.discoveryFetch")}),"error"===m.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:m.message}),"success"===m.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:f,onChange:e=>x(e.target.value),placeholder:h("models.discoveryFilterPlaceholder",{count:m.models.length}),"aria-label":h("models.discoveryFilter"),style:{...aG,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:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:k,type:"checkbox",checked:R,disabled:0===T.length,onChange:()=>{let e=new Set(T);v(t=>R?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),h("models.discoverySelectShown")]}),0===E.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:h("models.discoveryNoMatches")}):E.map((e,t)=>{let n=C.has(e.id),i=b.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:h("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:m.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:$.length>E.length?h("models.discoveryShowing",{shown:E.length,total:$.length}):h("models.discoveryFetched",{count:m.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==m.phase)return;let e=new Set(b),t=m.models.filter(t=>e.has(t.id)&&!C.has(t.id));0!==t.length&&(u(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?h("models.discoveryAddSelectedCount",{count:M}):h("models.discoveryAddSelected")})]})]})]})]})}let a8=["off","minimal","low","medium","high","xhigh","max"],a6={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function a3(e){let{value:t,onChange:n}=e,{t:i}=(0,eX.s)(),s=t??{},a=(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:a8.map(e=>{let t=s[e],n=e in s?null===t?"null":"string":"omit",o="string"==typeof t?t:"",l=a6[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:l,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:()=>a(e,"omit"),style:{...d,..."omit"===n?c:{}},children:i("i18n.default")}),(0,r.jsx)("button",{onClick:()=>a(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:()=>a(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=>a(e,t.target.value),onFocus:()=>{"string"!==n&&a(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 a5={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function a9(e){return e.compat?.thinkingFormat==="deepseek"}function a7(e,t){return{...e.compat??{},...t.compat??{}}}function oe(e){let{headers:t,onChange:n}=e,{t:s}=(0,eX.s)(),[a,o]=(0,i.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),l=(0,i.useRef)(a.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(a.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:[a.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:{...aG,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:{...aG,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void d(a.filter(e=>e.id!==t))},style:u,children:"✕"})]},e.id)),(0,r.jsxs)("button",{onClick:()=>o(e=>[...e,{id:l.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 ot(e){let{providerName:t,provider:n,model:s,onChange:a,onDelete:o}=e,[l,d]=(0,i.useState)({phase:"idle"}),{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(()=>s_(s.cost)),x=(0,i.useRef)(g),[b,v]=(0,i.useState)(!1),y=(0,i.useRef)(0),k=s.baseUrl??n.baseUrl,j=(0,i.useRef)(0),w=(0,i.useRef)(null),S=(0,i.useRef)(s.cost),C=(e,t)=>a({...s,[e]:t}),N=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return c("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[c("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,l.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"}),w.current=null},[t,k,s.id]);let I=(0,i.useCallback)(async()=>{if(!s.id.trim()||"testing"===l.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,l.phase]),$=(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"});k?.trim()&&r.set("baseUrl",k.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 l=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 a=sH(s_(i));s>0&&a&&(n.cost={...i,...a},r+=s)}return{model:n,appliedCount:r}}(s,o.recommendation.preset);l.appliedCount>0&&(w.current=s,a(l.model)),m(!1),p({phase:"success",recommendation:o.recommendation,appliedCount:l.appliedCount})}catch(e){if(n!==j.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,s,a,k,t]),E=(()=>{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}`})(),T="error"===u.phase?u.message:E,M="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;a9(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 P=sO(s),z=sW(P),O=[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!==z?c("models.imageMaxBytesSummary",{size:sF(z)}):null].filter(e=>!!e),W=O.length?O.join(" \xb7 "):c("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:c("i18n.model")})}),(0,r.jsxs)(as,{children:[N&&(0,r.jsx)("span",{title:N,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.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)(aj,{size:"small",variant:"success"===l.phase?"primary":"secondary",onClick:"success"===l.phase?()=>d({phase:"idle"}):I,disabled:!s.id.trim()||"testing"===l.phase,title:c("i18n.testConnection"),className:"success"===l.phase?"is-success":void 0,children:["success"===l.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"===l.phase?c("i18n.checking"):"success"===l.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)(aj,{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)(aJ,{label:"ID *",children:(0,r.jsx)(aY,{value:s.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(aJ,{label:"Name",children:(0,r.jsx)(aY,{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 $(),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")})]}),T&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:T,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),w.current&&(0,r.jsx)("button",{onClick:()=>{let e=w.current;e&&(w.current=null,a(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)(a2,{children:c("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(a1,{label:c("models.reasoning"),checked:s.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(a1,{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)(a2,{children:c("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(h)return void m(!1);S.current=s.cost;let e=s_(s.cost);x.current=e,f(e),m(!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)(aJ,{label:c("models.contextWindow"),children:(0,r.jsx)(aQ,{value:void 0!==s.contextWindow?String(s.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(aJ,{label:c("models.maxOutputTokens"),children:(0,r.jsx)(aQ,{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)(aJ,{label:n,children:(0,r.jsx)(aQ,{value:g[t],onChange:e=>{let n,r,i;return r=sH(n={...x.current,[t]:e}),i={...s},void(x.current=n,f(n),r?(i.cost={...S.current??{},...r},S.current=i.cost):delete i.cost,a(i))},placeholder:"0"})},t)}),sU(g)&&!sH(g)&&(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,a=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:a?"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:()=>v(e=>!e),"aria-expanded":b,"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:W})]}),(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:b?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(aJ,{label:c("models.baseUrlOverride"),children:(0,r.jsx)(aY,{value:s.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??c("models.providerDefaults"),mono:!0})}),(0,r.jsx)(aJ,{label:c("models.apiOverride"),children:(0,r.jsx)(a0,{value:s.api??"",onChange:e=>C("api",e||void 0),options:aZ})}),(0,r.jsxs)(aJ,{label:c("models.headers"),children:[(0,r.jsx)(oe,{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!==P)&&(0,r.jsxs)(aJ,{label:c("models.imageMaxBytes"),children:[(0,r.jsx)(aQ,{value:void 0===P?"":String(P),onChange:e=>{var t;let n,r,i,o;return a((t=e.trim()||void 0,n={...sz(s.inputLimits)?s.inputLimits:{}},r={...sz(n.images)?n.images:{}},i={...sz(r.resize)?r.resize:{}},void 0===t?delete i.maxBytes:i.maxBytes=sW(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===z&&void 0!==P}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==z&&`${sF(z)} \xb7 `,c("models.imageMaxBytesHelp",{size:sF(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)(a2,{children:c("models.compatibility")}),(0,r.jsx)(a1,{label:c("models.deepSeekThinkingCompat"),checked:a9(s),onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...a5}};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)(a1,{label:c("models.developerRole"),checked:!1!==a7(n,s).supportsDeveloperRole,onChange:e=>a(sq(s,"supportsDeveloperRole",e))}),(s.api??n.api)==="anthropic-messages"&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,r.jsx)(a1,{label:c("models.adaptiveThinking"),checked:!0===a7(n,s).forceAdaptiveThinking,onChange:e=>a(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return sq(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)(a2,{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)(a3,{value:s.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function on(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,[o,l]=(0,i.useState)({phase:"idle"}),{t:d}=(0,eX.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)(()=>{l({phase:"idle"}),u(""),p.current?.close(),p.current=null},[t.id]),(0,i.useEffect)(()=>()=>{p.current?.close()},[]);let m=(0,i.useCallback)(()=>{p.current?.close(),l({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?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({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?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(e.close(),l({phase:"success"}),n()):"error"===r.type?(e.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(e.close(),l({phase:"idle"}))},e.onerror=()=>{e.close(),l(e=>"success"===e.phase?e:{phase:"error",message:d("models.connectionLost")})}},[t.id,n,d]),g=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),l({phase:"idle"}),n()},[t.id,n]),f=(0,i.useCallback)(async(e,n)=>{if(n.trim()){l({phase:"progress",message:d("models.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(()=>({}));l({phase:"error",message:e.error??d("models.serverError",{status:r.status})});return}u("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}}},[t.id,d]),x=(0,i.useCallback)(async(e,n)=>{l({phase:"progress",message:d("i18n.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(()=>({}));l({phase:"error",message:e.error??d("models.serverError",{status:r.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:d("i18n.networkError")})}},[t.id,d]),b="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)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:d("i18n.subscription")})}),(0,r.jsxs)(as,{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:t.loggedIn?d("i18n.connected"):d("i18n.notConnected")})]}),b?(0,r.jsx)(aj,{size:"small",onClick:()=>{p.current?.close(),l({phase:"idle"})},children:d("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aj,{variant:"primary",size:"small",onClick:m,children:t.loggedIn?d("i18n.relogin"):d("i18n.login")}),t.loggedIn&&(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:g,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)(aO,{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 f(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?` ${d("models.deviceCodeExpires",{minutes:Math.ceil(o.expiresInSeconds/60)})}`:""]})]}),"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)(a_,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,r.jsx)(az,{providerId:t.id,controller:s,contextSettings:a})]})}let or="http://127.0.0.1:8080";function oi(e){let{provider:t,onRefresh:n,enabledModels:s,contextSettings:a}=e,o=t.id===s$,[l,d]=(0,i.useState)(o&&!t.configured?or:""),[c,u]=(0,i.useState)(""),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(!1),{t:y}=(0,eX.s)(),k=!!(o?l.trim():c.trim());async function j(){if(k&&!p){h(!0),x(null),v(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:c.trim(),...o?{serverUrl:l.trim()}:{}})}),r=await e.json();!e.ok||r.error?x(r.error??`HTTP ${e.status}`):(u(""),o&&(d(""),s.refresh(),r.catalog?.completed||x(y(r.catalog?.reason==="offline"?"models.catalogOffline":"models.catalogUnreachable"))),v(!0),setTimeout(()=>v(!1),2e3),n())}catch(e){x(String(e))}finally{h(!1)}}}let w=(0,i.useCallback)(async()=>{g(!0),x(null);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"DELETE"}),r=await e.json();!e.ok||r.error?x(r.error??`HTTP ${e.status}`):n()}catch(e){x(String(e))}finally{g(!1)}},[t.id,n]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(a2,{children:o?t.displayName:"API Key"})}),(0,r.jsxs)(as,{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:t.configured?y("i18n.configured"):y("i18n.notConfigured")})]}),t.configured&&(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:w,disabled:m,children:m?y("i18n.removing"):y("i18n.disconnect")})]})]}),o&&(0,r.jsxs)("label",{style:{display:"grid",gap:6},children:[y("models.llamaRouterUrl"),(0,r.jsx)("input",{type:"url",style:aG,value:l,placeholder:or,onChange:e=>d(e.target.value),spellCheck:!1})]}),!o&&!t.configured&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:1===t.modelCount?y("models.apiKeyEnableOne",{provider:t.displayName}):y("models.apiKeyEnable",{provider:t.displayName,count:t.modelCount})}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(aX,{value:c,onChange:u,onKeyDown:e=>{"Enter"===e.key&&j()},placeholder:o?y("models.optionalApiKey"):t.configured?y("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:j,disabled:p||!k||b,style:{padding:"6px 12px",background:b?"#16a34a":k?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:b?"#fff":k?"var(--accent-contrast)":"var(--text-dim)",cursor:p||!k||b?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[b&&(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"})}),b?y("i18n.saved"):p?y("i18n.saving"):y("i18n.save")]})]}),f&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:f}),(0,r.jsx)(a_,{providerId:t.id,enabled:t.configured}),t.configured&&(0,r.jsx)(az,{providerId:t.id,controller:s,contextSettings:a,emptyCatalogHint:o?y("models.llamaEmptyCatalog"):void 0})]})}function os(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:s,onSelectApiKey:a,onAddCustom:o,onClose:l}=e,[d,c]=(0,i.useState)(""),{t:u}=(0,eX.s)(),p=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=d.trim().toLowerCase(),m=t.filter(e=>!e.loggedIn&&sG(h,e.id,e.name)),g=n.filter(e=>!e.configured&&sG(h,e.id,e.displayName)),f=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=m.length+g.length+ +!!f,b={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&&l()},onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),l())},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:[f&&(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")}),f&&(0,r.jsxs)("button",{onClick:()=>{o(),l()},style:b,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"})]})})]}),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("i18n.subscriptions")}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),l()},style:b,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)(aF,{id:e.id,size:28})]},e.id)),g.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(m.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),g.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),l()},style:b,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:e.id===s$?u("models.optionalApiKey"):u(1===e.modelCount?"models.modelCountOne":"models.modelCount",{count:e.modelCount})})]}),(0,r.jsx)(aF,{id:e.id,size:28})]},e.id))]})})]})})}function oa(e){let{onClose:t,embedded:n=!1,cwd:s=null}=e,{t:a}=(0,eX.s)(),{openDetail:o,closeDetail:l}=s1(),d=function(e){let[t,n]=(0,i.useState)(null),[r,s]=(0,i.useState)(!0),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),[h,m]=(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 g=(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?aM[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=g;let f=(0,i.useCallback)((e,t,n)=>{g(e,{op:"models",refs:t,enabled:n})},[g]),x=(0,i.useCallback)((e,t)=>{g(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[g]),b=(0,i.useCallback)(()=>g("clear",{op:"clear"}),[g]),v=(0,i.useCallback)(()=>g("prune",{op:"prune"}),[g]),y=(0,i.useCallback)(()=>m(e=>e+1),[]),k=(0,i.useCallback)((e,n)=>{g("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)})},[g,t]);return{view:t,loading:r,pending:a,failure:l,setModels:f,setProvider:x,clearScope:b,pruneStale:v,refresh:y,resync:k}}(s),[c,u]=(0,i.useState)({providers:{}}),[p,h]=(0,i.useState)(!0),[m,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(!1),[j,w]=(0,i.useState)(aq),[S,C]=(0,i.useState)([]),[N,I]=(0,i.useState)([]),[$,E]=(0,i.useState)({}),[T,M]=(0,i.useState)(()=>new Map),[R,A]=(0,i.useState)(!1),[L,P]=(0,i.useState)(!1),z=(0,i.useRef)(new Set),O=(0,i.useRef)(new Map),W=(0,i.useRef)(new Map),F=(0,i.useRef)(new WeakMap),D=(0,i.useRef)(0),B=(0,i.useRef)(null),[_,H]=(0,i.useState)(null),[U,q]=(0,i.useState)(null),K=(0,i.useCallback)(()=>fetch("/api/auth/providers").then(e=>e.json()).then(e=>(Array.isArray(e.oauthProviders)&&C(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&I(e.apiKeyProviders),E(e.providerNames??{}),!0)).catch(()=>!1).finally(()=>A(!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:{}};u(t),z.current=new Set(Object.keys(t.providers??{})),W.current=sK(t),M(sX(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=>v(e instanceof Error?e.message:String(e))).finally(()=>h(!1)),K()},[K]),(0,i.useEffect)(()=>{j&&sN("models",JSON.stringify(j))},[j]),(0,i.useEffect)(()=>{if(j?.type!=="provider")return;let e=c.providers?.[j.name];!(!e||!aK(e)||T.has(j.name))&&(S.some(e=>e.id===j.name)?w({type:"oauth",providerId:j.name}):N.some(e=>e.id===j.name)&&w({type:"apikey",providerId:j.name}))},[N,c.providers,S,T,j]);let Z=e=>({overrides:c.providers?.[e]?.modelOverrides,disabled:p||m||null!==b,onChange:(t,n)=>{try{u(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},a={...s.modelOverrides},o=Object.hasOwn(a,n)?a[n]:void 0;if(void 0!==o&&!sE(o))throw Error("Model override must be an object");let l={...o};return void 0===r?delete l.contextWindow:l.contextWindow=r,Object.keys(l).length?Object.defineProperty(a,n,{value:l,enumerable:!0,configurable:!0}):delete a[n],Object.keys(a).length?s.modelOverrides=a:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(c,e,t,n)),k(!1),x(null)}catch(e){x(String(e))}}}),V=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;u(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),w({type:"provider",name:e})},[c.providers]),J=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),G=(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:a}=t,o=sJ(t,n);o===r?s.delete(o):null!==o&&s.set(o,r);let l=a.get(n);l&&(a.delete(n),a.set(r,l));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:z.current,renames:O.current,slots:W.current},t,n);return r?(u(r),q(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},[]),Y=(0,i.useCallback)((e,t)=>{G(c,e,t)?x(null):x(a("models.providerIdTaken",{name:t}))},[G,c,a]),X=(0,i.useCallback)(e=>{var t;let n,r,i=(null!==(n=sJ(t={savedProviders:z.current,renames:O.current,slots:W.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...c.providers??{}},delete r[e],{...c,providers:r}),s=Object.keys(i.providers??{});q(t=>t?.provider===e?null:t),u(i),w(s.length>0?{type:"provider",name:s[0]}:null),l()},[c,l]),Q=(0,i.useCallback)(e=>{sZ(W.current,e,1),u(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),u(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return w({type:"model",providerName:e,index:n}),t})},[]),ee=(0,i.useCallback)((e,t)=>{u(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));sZ(W.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],a=new Set(s.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),et=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]],a=F.current.get(s[t]);return a&&F.current.set(n,a),s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),en=(0,i.useCallback)(e=>{e&&(u(e.config),k(!1),x(null),w(t=>t?.type==="model"&&t.providerName===e.providerName?{...t,index:e.order.indexOf(t.index)}:t))},[]),er=(0,i.useCallback)((e,t,n)=>{m||b||en(function(e,t,n,r,i){let s=e.providers?.[n]?.models??[];if(r<0||r>=s.length||i<0||i>=s.length)return null;let a=[...s.keys()];return a.splice(r,1),a.splice(i,0,r),sV(e,t,n,a)}(c,W.current,e,t,n))},[en,c,b,m]),ei=(0,i.useCallback)(e=>{if(!m&&!b){var t;let n,r;en((t=W.current,n=c.providers?.[e]?.models??[],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sV(c,t,e,[...n.keys()].sort((e,t)=>r.compare(sY(n[e]),sY(n[t]))))))}},[en,c,b,m]),es=(0,i.useCallback)((e,t)=>{W.current.get(e)?.splice(t,1),u(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}),l()},[l]),ea=(0,i.useCallback)(async()=>{if(b)return;g(!0),x(null),k(!1);let e=c,t=U?.name.trim();if(U&&t&&c.providers?.[U.provider]){let n=G(c,U.provider,t);if(!n){x(a("models.providerIdTaken",{name:t})),g(!1);return}e=n}try{var n=e=function(e){let t=structuredClone(e);if(!sE(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(sE(n)&&sE(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!sE(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=sM(r.contextWindow);if(void 0===n)throw new sT(`${e}/${t}`);r.contextWindow=n}return t}(e);if(sL(n.providers))for(let[e,t]of Object.entries(n.providers)){if(!sL(t))continue;if(t.oauth&&!t.baseUrl)throw new sA(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(sP),r=sL(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 sA(e,"empty")}var r=e;if(sz(r.providers)){for(let[e,t]of Object.entries(r.providers))if(sz(t)&&Array.isArray(t.models))for(let n of t.models){if(!sz(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=sO(n);if(void 0!==t&&void 0===sW(t))throw new sD(`${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)x(i.error??`HTTP ${t.status}`);else{k(!0),setTimeout(()=>k(!1),2e3);let t=[...O.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 a=e[s];a&&t.id&&a!==t.id&&i.push({from:`${r(n)}/${a}`,to:`${n}/${t.id}`})})}return i}(e,W.current,O.current);z.current=new Set(Object.keys(e.providers??{})),W.current=sK(e),O.current.clear(),d.resync(t,n);let r=sX(e);K().then(e=>{e&&M(r)})}}catch(e){e instanceof sA?(x(a(aV[e.problem],{provider:e.provider})),w({type:"provider",name:e.provider})):e instanceof sT?x(a("models.contextInvalid",{model:e.model})):x(e instanceof sD?a("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{g(!1)}},[G,c,d,b,U,K,a]),eo=Object.entries(c.providers??{}).filter(e=>{let[t,n]=e;if(!aK(n)||T.has(t))return!0;let r=S.some(e=>e.id===t)||N.some(e=>e.id===t);return R&&!r}),el=(e,t)=>{var n,r,i;return n=$[e]??d.view?.providers.find(t=>t.id===e)?.name,i=void 0!==(r=T.get(e))&&n?.trim()===r.trim()?void 0:n,t.name?.trim()||i?.trim()||e},ed=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=aE(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(d.view,e);return t?(0,r.jsx)("span",{className:"models-sidebar-badge",children:t}):null},ec=S.filter(e=>e.loggedIn),eu=N.filter(e=>e.configured),ep=(()=>{if(!j)return null;if("oauth"===j.type){let e=S.find(e=>e.id===j.providerId);return e?(0,r.jsx)(on,{provider:e,onRefresh:K,enabledModels:d,contextSettings:Z(e.id)},e.id):null}if("apikey"===j.type){let e=N.find(e=>e.id===j.providerId);return e?(0,r.jsx)(oi,{provider:e,onRefresh:K,enabledModels:d,contextSettings:Z(e.id)},e.id):null}if("provider"===j.type){let e=c.providers?.[j.name];return e&&eo.some(e=>{let[t]=e;return t===j.name})?(0,r.jsx)(a4,{name:j.name,editingName:U?.provider===j.name?U.name:j.name,fallbackLabel:el(j.name,{}),provider:e,onChange:e=>J(j.name,e),onEditingNameChange:e=>q(e===j.name?null:{provider:j.name,name:e}),onRename:e=>Y(j.name,e),onDelete:()=>X(j.name),onAddModels:e=>ee(j.name,e),enabledModels:d},j.name):null}let e=c.providers?.[j.providerName],t=e?.models?.[j.index];return t?(0,r.jsx)(ot,{providerName:j.providerName,provider:e,model:t,onChange:e=>et(j.providerName,j.index,e),onDelete:()=>es(j.providerName,j.index)},`${j.providerName}-${j.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(sQ,{embedded:n,title:a("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:a("i18n.close"),onClose:t,children:[(0,r.jsx)(aR,{controller:d}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsxs)(s3,{children:[ec.map(e=>{let t=j?.type==="oauth"&&j.providerId===e.id;return(0,r.jsxs)(ae,{active:t,onClick:()=>w({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(aF,{id:e.id,size:16}),(0,r.jsx)(at,{className:"is-grow",children:e.name}),ed(e.id)]},e.id)}),eu.map(e=>{let t=j?.type==="apikey"&&j.providerId===e.id;return(0,r.jsxs)(ae,{active:t,onClick:()=>w({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(aF,{id:e.id,size:16}),(0,r.jsx)(at,{className:"is-grow",children:e.displayName}),ed(e.id)]},e.id)}),(ec.length>0||eu.length>0)&&eo.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):eo.map(e=>{let[t,n]=e,i=j?.type==="provider"&&j.name===t,s=n.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(ae,{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)(at,{className:"is-grow",children:el(t,n)}),ed(t)]}),s.map((e,n)=>{var i;let s,o,l=j?.type==="model"&&j.providerName===t&&j.index===n,d=F.current.get(e);d||(d=`model-${++D.current}`,F.current.set(e,d));let c=_?.providerName===t&&_.index===n?_:null;return(0,r.jsxs)(ae,{active:l,className:"models-sidebar-indented-item",style:c?{boxShadow:`inset 0 ${c.after?"-2px":"2px"} 0 var(--accent)`}:void 0,"aria-keyshortcuts":"Alt+ArrowUp Alt+ArrowDown",onClick:()=>w({type:"model",providerName:t,index:n}),onKeyDown:e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let r="ArrowUp"===e.key?-1:"ArrowDown"===e.key?1:null;null!==r&&(e.preventDefault(),er(t,n,n+r))},...(i=e.id,s=e=>{var r;let i,s=B.current;if(s?.providerName!==t)return null;let a=e.currentTarget.getBoundingClientRect(),o=e.clientY>=a.top+a.height/2;return{from:s.index,to:(r=s.index,r<(i=o?n+1:n)?i-1:i),after:o}},{draggable:!m&&!b,onDragStart:e=>{B.current={providerName:t,index:n},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)},onDragOver:e=>{let r=s(e);if(!r)return;e.preventDefault(),e.dataTransfer.dropEffect="move";let i=r.to===r.from?null:{providerName:t,index:n,after:r.after};H(e=>e?.providerName===i?.providerName&&e?.index===i?.index&&e?.after===i?.after?e:i)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||H(e=>e?.providerName===t&&e.index===n?null:e)},onDrop:e=>{let n=s(e);n&&(e.preventDefault(),er(t,n.from,n.to),o())},onDragEnd:o=()=>{B.current=null,H(null)}}),children:[(0,r.jsx)(at,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:sY(e)||a("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"})]},d)}),(0,r.jsxs)("div",{className:"models-sidebar-model-footer",children:[(0,r.jsx)(ae,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),Q(t)},children:(0,r.jsxs)(at,{children:["+ ",a("i18n.model")]})}),(0,r.jsx)("button",{type:"button",className:"models-sidebar-sort-button","aria-label":a("models.sortByName"),title:a("models.sortByName"),disabled:m||null!==b||s.length<2,onClick:()=>ei(t),children:"A–Z"})]})]},t)})]}),(0,r.jsx)(aS,{onClick:e=>{e.preventDefault(),P(!0)},children:a("i18n.addProvider")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:p?null:ep??(0,r.jsx)(ab,{children:a("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(ay,{status:b||f?(0,r.jsx)("span",{style:{color:"#f87171"},children:b?a("models.configUnreadable",{error:b}):f}):a("models.applyHelp"),children:[!n&&(0,r.jsx)(aj,{onClick:t,children:a("i18n.cancel")}),(0,r.jsxs)(aj,{variant:"primary",onClick:ea,disabled:m||y||null!==b,className:y?"is-success":void 0,children:[y&&(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:y?a("i18n.saved"):m?a("i18n.saving"):a("i18n.save")})]})]})]}),L&&(0,r.jsx)(os,{oauthProviders:S,apiKeyProviders:N,onSelectOAuth:e=>{w({type:"oauth",providerId:e}),o()},onSelectApiKey:e=>{w({type:"apikey",providerId:e}),o()},onAddCustom:()=>{V(),o()},onClose:()=>P(!1)})]})}let oo=null;async function ol(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(oo)return oo;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 oo=null,!1}})();return oo=t,t.then(e=>{e||oo!==t||(oo=null)}),t}var od=n(9258);function oc(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function ou(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function op(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function oh(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function om(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function og(e,t){return e?e.slice(0,8):t}function of(e){let{skill:t,cwd:n,onToggle:s,toggling:a,saveError:o,updateStatus:l,checkingUpdate:d,updating:c,updateError:u,onCheckUpdate:p,onUpdate:h}=e,{t:m}=(0,eX.s)(),g=op(t),f=!t.disableModelInvocation,[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),k=t.filePath.split(/[\\/]/).pop(),[j,w]=(0,i.useState)([]),S=j.at(-1)??k,C=(0,i.useRef)(null),N=(0,i.useRef)(null),[I,$]=(0,i.useState)(0),E=(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+1):w(e=>[...e,t.document])},[S]);return(0,i.useLayoutEffect)(()=>{let e=N.current,t=C.current;null!==e&&(null!==x||v)&&t&&(N.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[x,v,I]),(0,i.useEffect)(()=>{let e=new AbortController;return b(null),y(null),(async()=>{try{var r;let i=new URLSearchParams({cwd:n,filePath:t.filePath});S!==k&&i.set("document",S);let s=await fetch(`/api/skills/content?${i}`,{signal:e.signal}),a=await s.json();if(!s.ok||a.error||"string"!=typeof a.content)throw Error(a.error??`HTTP ${s.status}`);b((r=a.content,(0,od.yv)(r).rest.trim()))}catch(t){if(e.signal.aborted)return;y(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,S,k]),(0,r.jsxs)(an,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(ar,{children:[(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:g,children:oh(g,m)}),(0,r.jsx)("span",{className:"config-detail-path",children:"project"===g?eh(t.filePath,n):ep(t.filePath)})]}),(0,r.jsx)(as,{children:(0,r.jsx)(aw,{checked:f,loading:a,label:m(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>s(t)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:m("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),t.install?.skillsShUrl&&(0,r.jsx)(al,{label:m("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)(al,{label:m("i18n.version"),children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:og(l?.currentVersion??t.install.versionHash,m("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,r.jsx)(aj,{size:"small",onClick:p,disabled:d||c,children:m("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:og(l.latestVersion,m("i18n.unknown"))}),(d||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${d?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:d?m("i18n.checking"):l?.state==="up-to-date"?m("i18n.upToDate"):l?.state==="unsupported"?m("i18n.automaticChecksUnavailable"):l?.message||m("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(aj,{variant:"primary",size:"small",onClick:h,disabled:c||d,children:m(c?"i18n.updating":"i18n.update")})]}),u&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:u})]}),(0,r.jsx)(al,{label:m("config.name"),children:(0,r.jsx)("span",{className:"skill-name-value",children:t.name})}),(0,r.jsx)(al,{label:m("i18n.description"),children:(0,r.jsx)("span",{className:"skill-description",children:t.description})}),(0,r.jsxs)(al,{label:m("skills.instructions"),ref:C,children:[j.length>0&&(0,r.jsx)(ar,{children:(0,r.jsxs)(ai,{children:[(0,r.jsx)(aj,{size:"small",onClick:()=>{N.current="",w(e=>e.slice(0,-1))},children:m("skills.documentBack")}),(0,r.jsx)("span",{className:"config-detail-path",title:S,children:S})]})}),v?(0,r.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:v}):null===x?(0,r.jsx)("span",{role:"status",className:"skill-instructions-status",children:m("i18n.loading")}):x?(0,r.jsx)(nF.m,{className:"skill-instructions",cwd:[t.baseDir,...S.split("/").slice(0,-1)].join("/"),onNavigateLink:E,children:x}):(0,r.jsx)("span",{className:"skill-instructions-status",children:m("skills.noInstructions")})]})]})}function ox(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:s,onInstalled:a}=e,{t:o}=(0,eX.s)(),[l,d]=(0,i.useState)(""),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(new Set),[j,w]=(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),g(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 g(n.error);u(n.results??[]),0===(n.results??[]).length&&g(o("i18n.noSkills"))}catch(e){g(String(e))}finally{h(!1)}}},[o]),N=(0,i.useCallback)(async e=>{x(e),v(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 v(r.error??`HTTP ${n.status}`);k(t=>new Set(t).add(`${j}:${e}`)),a()}catch(e){v(String(e))}finally{x(null)}},[a,j,t]),I="global"===j?"~/.pi/agent/skills/":`${ep(t)}/.pi/skills/`;return(0,r.jsxs)(an,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(am,{title:o("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,r.jsx)(ah,{value:j,label:o("config.saveTo"),options:[{value:"global",label:oh("global",o)},{value:"project",label:oh("project",o),disabled:!s}],path:I,disabledReason:o("trust.projectScopeUnavailable"),onChange:w})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Enter"!==e.key||p||C(l))},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)(aj,{variant:"primary",onClick:()=>C(l),disabled:p||!l.trim(),children:p?o("i18n.searching"):o("i18n.search")})]}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:m}),b&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:b})]}),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=f===e.package,s=e.package.indexOf("@"),a=s>-1?e.package.slice(0,s):e.package,l=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:l??a}),(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:a}),(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)(aj,{size:"small",onClick:()=>!t&&!i&&N(e.package),disabled:t||i||null!==f,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 ob(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a}=e,{t:o}=(0,eX.s)(),[l,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(()=>sC("skills",t)),[f,x]=(0,i.useState)(new Set),[b,v]=(0,i.useState)(null),[y,k]=(0,i.useState)(null),[j,w]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)({}),[$,E]=(0,i.useState)(new Set),[T,M]=(0,i.useState)(!1),[R,A]=(0,i.useState)(null),[L,P]=(0,i.useState)(null),[z,O]=(0,i.useState)(!0),W=(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),O(n.projectResourcesLoaded??!0),g(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)(()=>{I({}),P(null),W()},[t]);let F=ou(a),D=(0,i.useRef)(F);(0,i.useEffect)(()=>{D.current!==F&&(D.current=F,W())},[F,W]),(0,i.useEffect)(()=>{m&&sN("skills",m,t)},[t,m]);let B=(0,i.useCallback)(async e=>{let n=(e?[e]:l.filter(e=>!!e.install)).map(om).filter(e=>!!e);if(0!==n.length){P(null),E(e=>new Set([...e,...n])),e||M(!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}`);I(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{E(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||M(!1)}}},[t,l]),_=(0,i.useCallback)(async e=>{if(!e.install)return;let n=om(e);A(n),P(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 W();let s=i.skill?.install?.versionHash;I(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(null)}},[t,W]),H=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;x(t=>new Set(t).add(e.filePath)),v(null),w(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 v(r.error??`HTTP ${n.status}`);d(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){v(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=oc(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])),k(e),v(null),w(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 a=n.results;d(e=>{let t;return t=new Set(a.filter(e=>!e.error).map(e=>e.filePath)),e.map(e=>t.has(e.filePath)?{...e,disableModelInvocation:s}:e)});let l=a.filter(e=>e.error);if(l.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));w({group:e,error:[o("skills.bulkFailed",{count:l.length,total:a.length}),...l.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){w({group:e,error:t instanceof Error?t.message:String(t)})}finally{k(null),x(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[o]),q=l.find(e=>e.filePath===m)??null,K=c||f.size>0||null!==R;return(0,r.jsxs)(sQ,{embedded:s,title:o("common.skills"),subtitle:ep(t),closeLabel:o("i18n.close"),onClose:n,children:[!z&&(0,r.jsx)(ax,{message:o("trust.skillsNotLoaded")}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{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===l.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"===op(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===op(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===op(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===op(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===op(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!S&&m===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(ae,{active:i,onClick:()=>{g(e.filePath),C(!1)},children:[(0,r.jsx)(aC,{active:!s}),(0,r.jsx)(at,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=om(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,a=s===i.length;return(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(s5,{aside:(0,r.jsx)(s9,{enabled:s,total:i.length,disabled:K,loading:y===t,label:o(a?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void U(t,i,e)}),children:t}),j?.group===t&&(0,r.jsx)(s7,{error:j.error}),[...i.filter(e=>!e.disableModelInvocation),...i.filter(e=>e.disableModelInvocation)].map(n)]},t)})})()}),(0,r.jsx)(aS,{onClick:()=>C(!0),active:S,children:o("i18n.addSkill")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:S?(0,r.jsx)(ox,{cwd:t,projectResourcesLoaded:z,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{W()}}):c?null:q?(0,r.jsx)(of,{skill:q,cwd:t,onToggle:H,toggling:f.has(q.filePath),saveError:b,updateStatus:om(q)?N[om(q)]:void 0,checkingUpdate:!!om(q)&&$.has(om(q)),updating:R===om(q),updateError:L,onCheckUpdate:()=>void B(q),onUpdate:()=>void _(q)},q.filePath):(0,r.jsx)(ab,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(ay,{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)(aj,{onClick:n,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(aj,{variant:"secondary",onClick:()=>void B(),disabled:T||null!==R,children:T?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let ov={builtin:0,global:1,workspace:2,project:3},oy=["read","bash","edit","write","grep","find","ls"],ok=["","off","minimal","low","medium","high","xhigh","max"],oj={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},ow={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"},oS={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function oC(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 oN(e){return`${e.scope}:${e.name}`}function oI(e){return"global"===e||"project"===e}function o$(e){return oI(e)||"builtin"===e}function oE(e){let{label:t,children:n}=e;return(0,r.jsx)(al,{label:t,children:n})}function oT(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 oM(e){let{cwd:t,sessionId:n=null,onClose:s,onReloaded:a,embedded:o=!1,trust:l}=e,d=(0,eQ.a)(),{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)([]),[h,m]=(0,i.useState)([]),[g,f]=(0,i.useState)(!0),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(()=>sC("agents",t)),[k,j]=(0,i.useState)(oj),[w,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("global"),[I,$]=(0,i.useState)(!0),[E,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(!1),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(10),[B,_]=(0,i.useState)(!0),[H,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),Y=(0,i.useMemo)(()=>u.find(e=>oN(e)===v)??null,[u,v]),X=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),[h]),Q=(0,i.useCallback)(async e=>{$(!0),z(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??sC("agents",t),a=i.find(e=>oN(e)===s)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;y(a?oN(a):null),a&&(j(oC(a)),S(oI(a.scope)?"edit":"view"),oI(a.scope)&&N(a.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}},[t]);(0,i.useEffect)(()=>{Q()},[Q]),(0,i.useEffect)(()=>{let e=new AbortController;return _(!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}`);W(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||_(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{v&&sN("agents",v,t)},[t,v]);let ee=ou(l);(0,i.useEffect)(()=>{let e=new AbortController;return f(!0),b(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}`);m(r.modelList??[]),b(r.modelError??null)}catch(t){if(e.signal.aborted)return;b(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||f(!1)}})(),()=>e.abort()},[t,ee]);let et=async()=>{T(!0),z(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:k})}),n=await e.json();if(!e.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${e.status}`);await Q(oN(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}},en=async()=>{if(Y&&oI(Y.scope)&&window.confirm(c("agents.deleteConfirm",{name:Y.displayName}))){T(!0),z(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.name})}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);await Q()}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}}},er="view"!==w,ei="create"===w,es=!er||E||A,ea=ei?C:Y?.scope,eo=ei?"global"===C?`~/.pi/agent/agents/${k.name||"..."}.md`:`./.pi/agents/${k.name||"..."}.md`:Y?(Y.filePath?"project"===Y.scope||"workspace"===Y.scope?eh(Y.filePath,t):ep(Y.filePath):null)??c("agents.builtinPath"):"",el=ei?eo:Y?.filePath??eo,ed=e=>h.some(t=>`${t.provider}/${t.id}`===e),ec=k.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&ok.includes(r)?e.slice(0,n):e}(k.model,ed),eu=!ec||ed(ec),em=(()=>{if(!ec)return null;let e=ec.indexOf("/");return e<0?{provider:"",modelId:ec}:{provider:ec.slice(0,e),modelId:ec.slice(e+1)}})(),eg=es?{...ow,...oS}:ow,ef=ei?es:!Y||!o$(Y.scope)||E||A,ex=(e,t)=>{j(n=>({...n,[e]:t}))},eb=0===k.tools.length&&!k.loadSkills&&!k.loadExtensions,ev=async e=>{if(ei)return void ex("enabled",e);if(Y&&o$(Y.scope)){L(!0),z(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:Y.scope,name:Y.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=>oN(e)===oN(i)?i:e)),j(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}}},ey=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}`);W(r.enabled),V(!!n)}catch(e){K(e instanceof Error?e.message:String(e))}finally{U(!1)}},ek=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){G(!0),K(null);try{await ic(n,{type:"reload"}),V(!1),a?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{G(!1)}}};return(0,r.jsxs)(sQ,{embedded:o,title:c("common.agents"),subtitle:ep(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")}),Z&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:c("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[Z&&n&&(0,r.jsx)(aj,{size:"small",onClick:()=>void ej(),disabled:J||H,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||H,onChange:e=>D(Number(e.target.value)),onBlur:()=>void ek(F)})]}),(0,r.jsx)(aw,{checked:O,disabled:B||J,loading:H,label:c("agents.builtInTitle"),onChange:e=>void ey(e)})]})]}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:I?(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)(s5,{children:c(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=ov[e.scope],u.some(e=>e.name.toLowerCase()===t&&ov[e.scope]>n));return(0,r.jsxs)(ae,{active:v===oN(e)&&!ei,onClick:()=>{y(oN(e)),j(oC(e)),S(oI(e.scope)?"edit":"view"),oI(e.scope)&&N(e.scope),z(null)},children:[(0,r.jsx)(aC,{active:e.enabled}),(0,r.jsx)(at,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:c("agents.overridden")})]},oN(e))})]},e)})}),(0,r.jsx)(aS,{active:ei,onClick:()=>{let e="custom-agent",t=2;for(;u.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),j({...oj,name:e,displayName:e}),S("create"),N("global"),z(null)},children:c("agents.new")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:Y||ei?(0,r.jsxs)(an,{children:[(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:ei?(0,r.jsx)(ah,{value:C,label:c("config.saveTo"),options:["global","project"].map(e=>({value:e,label:c(`agents.scope.${e}`),disabled:E})),path:eo,onChange:N}):(0,r.jsxs)(r.Fragment,{children:[ea&&(0,r.jsx)(au,{scope:ea,children:c(`agents.scope.${ea}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:eo})]})}),(0,r.jsxs)(as,{children:[Y&&("view"===w||"edit"===w)&&(0,r.jsx)(aj,{size:"small",onClick:()=>{if(!Y)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}(Y.name,u);y(null),j({...oC(Y),name:e,displayName:c("agents.copyName",{name:Y.displayName})}),S("create"),N(oI(Y.scope)?Y.scope:"global"),z(null)},disabled:E||A,children:c("agents.duplicate")}),Y&&oI(Y.scope)&&"edit"===w&&(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:()=>void en(),disabled:E||A,children:c("agents.delete")}),(0,r.jsx)(aw,{checked:k.enabled,disabled:ef,label:k.enabled?c("agents.disable"):c("agents.enable"),onChange:e=>void ev(e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:d?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(oE,{label:c("agents.name"),children:ei?(0,r.jsx)("input",{"aria-label":c("agents.name"),value:k.name,disabled:es,onChange:e=>ex("name",e.target.value),style:ow}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:k.name})}),(0,r.jsx)(oE,{label:c("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":c("agents.displayName"),value:k.displayName,disabled:es,onChange:e=>ex("displayName",e.target.value),style:eg})})]}),(0,r.jsx)(oE,{label:c("agents.description"),children:(0,r.jsx)("input",{"aria-label":c("agents.description"),value:k.description,disabled:es,onChange:e=>ex("description",e.target.value),style:eg})}),(0,r.jsx)(oE,{label:c("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":c("agents.prompt"),value:k.systemPrompt,disabled:es,onChange:e=>ex("systemPrompt",e.target.value),style:{...eg,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:es?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(oE,{label:c("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:oy.map(e=>(0,r.jsx)(oT,{label:e,disabled:es,checked:k.tools.includes(e),onChange:t=>ex("tools",t?[...k.tools,e]:k.tools.filter(t=>t!==e))},e))})}),(0,r.jsxs)(oE,{label:c("agents.resources"),children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(oT,{label:c("agents.loadSkills"),disabled:es,checked:k.loadSkills,onChange:e=>ex("loadSkills",e)}),(0,r.jsx)(oT,{label:c("agents.loadExtensions"),disabled:es,checked:k.loadExtensions,onChange:e=>ex("loadExtensions",e)}),(0,r.jsx)(oT,{label:c("agents.mcp"),disabled:es||eb&&"on"!==k.mcp,checked:"on"===k.mcp,onChange:e=>ex("mcp",e?"on":"off")})]}),k.loadSkills&&void 0!==k.skills&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:k.skills.length>0?c("agents.skillsOnly",{skills:k.skills.join(", ")}):c("agents.skillsNone")}),k.loadExtensions&&void 0!==k.extensions&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:k.extensions.length>0?c("agents.extensionsOnly",{extensions:k.extensions.join(", ")}):c("agents.extensionsNone")}),!es&&eb?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpChatOnly")}):"on"===k.mcp&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:c("agents.mcpHint")})]}),(0,r.jsx)(oE,{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:k.codemode??"off",disabled:es,onChange:e=>ex("codemode",e.target.value),style:{...eg,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)(oE,{label:c("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(rc,{options:X,value:em,onChange:(e,t)=>ex("model",`${e}/${t}`),onClear:()=>ex("model",void 0),emptyLabel:g?c("agents.modelsLoading"):c("agents.inherit"),selectedLabel:k.model&&!eu?c("agents.modelUnavailable",{model:k.model}):k.model!==ec?k.model:void 0,disabled:es||g||0===h.length&&!k.model,ariaLabel:c("agents.model"),variant:"field",placement:"auto"}),x&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:x})]})}),(0,r.jsx)(oE,{label:c("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":c("agents.thinking"),value:k.thinking??"",disabled:es,onChange:e=>ex("thinking",e.target.value||void 0),style:eg,children:ok.map(e=>(0,r.jsx)("option",{value:e,children:e||c("agents.inherit")},e||"default"))})}),(0,r.jsx)(oE,{label:c("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":c("agents.maxTurns"),type:"number",min:1,value:k.maxTurns??"",disabled:es,onChange:e=>ex("maxTurns",e.target.value?Number(e.target.value):void 0),style:eg})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(oT,{label:c("agents.inheritContext"),disabled:es,checked:k.inheritContext,onChange:e=>ex("inheritContext",e)}),(0,r.jsx)(oT,{label:c("agents.background"),disabled:es,checked:k.runInBackground,onChange:e=>ex("runInBackground",e)})]})]}):(0,r.jsx)(ab,{children:c("agents.empty")})})})]}),(0,r.jsx)(ay,{status:(q||P)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||P}),children:er&&(0,r.jsxs)(aj,{variant:"primary",onClick:()=>void et(),disabled:E||M||A||!k.name.trim(),className:M?"is-success":void 0,children:[M&&(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:M?c("i18n.saved"):E?c("agents.saving"):c("agents.save")})]})})]})}let oR=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function oA(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function oL(e){return`${e.scope}\0${e.source}`}function oP(e){return`extension\0${e.path}`}function oz(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function oO(e,t){return t(`plugins.status.${e}`)}function oW(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function oF(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function oD(e){let{pkg:t}=e,{t:n}=(0,eX.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 oB(e){let{cwd:t,source:n,scope:i,projectResourcesLoaded:s,busy:a,actionError:o,onSourceChange:l,onScopeChange:d,onInstall:c}=e,{t:u}=(0,eX.s)();return(0,r.jsx)(ag,{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)(ah,{value:i,label:u("config.saveTo"),options:[{value:"global",label:oz("global",u)},{value:"project",label:oz("project",u),disabled:!s}],path:"project"===i?`${ep(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:!a&&!!n.trim(),normalizeValue:oA,onValueChange:l,onSubmit:c,examplesLabel:u("config.examples"),examples:oR,error:o,children:(0,r.jsx)(aj,{variant:"primary",onClick:c,disabled:a||!n.trim(),className:"is-pushed-right",children:u(a?"i18n.installing":"i18n.install")})})}function o_(e){let t,{pkg:n,cwd:s,busyKey:a,actionError:o,actionMessage:l,sessionId:d,updateStatus:c,checkingUpdate:u,updateError:p,onAction:h,onCheckUpdate:m,onReloadSession:g}=e,{t:f}=(0,eX.s)(),x=oL(n),b=(a?.endsWith(x)||a?.startsWith("bulk:"))??!1,v="reload"===a,y=!n.disabled,k=n.canCheckForUpdates,j=c?.state==="update-available",w=n.description?.trim(),S=(0,i.useId)();return(0,r.jsxs)(an,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ar,{className:"is-top-aligned",children:[(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:n.scope,children:oz(n.scope,f)}),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:f("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:f("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)(as,{children:[(0,r.jsx)(aj,{size:"small",variant:j?"primary":void 0,onClick:j||!k?()=>h("update",n):m,disabled:b||v||u,title:j?f("i18n.updateAvailable"):void 0,children:f(a===`update:${x}`?"i18n.updating":u?"i18n.checking":j||!k?"i18n.update":"i18n.check")}),(0,r.jsx)(aj,{size:"small",onClick:g,disabled:!d||v||b,"aria-describedby":d?void 0:S,children:f(v?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(aj,{variant:"danger",size:"small",onClick:()=>h("remove",n),disabled:b||v,children:f(a===`remove:${x}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(aw,{checked:y,loading:b||v,onChange:()=>h(n.disabled?"enable":"disable",n),label:f(n.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!d&&(0,r.jsx)("div",{id:S,className:"config-detail-heading-note",children:f("i18n.openSessionToReload")})]}),(0,r.jsxs)(ad,{children:[w&&(0,r.jsx)(ac,{label:f("i18n.description"),children:w}),(0,r.jsx)(ac,{label:f("i18n.status"),tone:"plain",style:{color:oF(n.status),textTransform:"capitalize"},children:oO(n.status,f)}),(0,r.jsxs)(ac,{label:f("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(f("i18n.installedVersion",{version:n.version})),n.configuredVersion&&t.push(f("i18n.configuredVersion",{version:n.configuredVersion})),t.length?t.join(" \xb7 "):f("i18n.unknown"))}),j&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:f("i18n.updateAvailable")}),k&&(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?f("i18n.checking"):c?.state==="up-to-date"?f("i18n.upToDate"):c?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):c?.message||f("i18n.checkFailed")})]}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,r.jsx)(ac,{label:f("i18n.package"),mono:!0,children:n.packageName??f("i18n.unknown")}),(0,r.jsx)(ac,{label:f("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,f)}),(0,r.jsx)(ac,{label:f("i18n.installedPath"),tone:n.installedPath?"muted":"error",mono:!0,children:n.installedPath?ep(n.installedPath):f("i18n.notFound")}),(0,r.jsx)(ac,{label:f("i18n.cwd"),tone:"dim",mono:!0,children:ep(s)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(ao,{children:f("i18n.resolvedResources")}),(0,r.jsx)(oD,{pkg:n})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:l}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function oH(e){let{extension:t}=e,{t:n}=(0,eX.s)(),i=t.enabled?"loaded":"disabled";return(0,r.jsxs)(an,{children:[(0,r.jsx)(ar,{children:(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:t.scope,children:oz(t.scope,n)}),(0,r.jsx)(aa,{children:t.name})]})}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:oO(i,n)}),(0,r.jsx)(ac,{label:n("i18n.installedPath"),mono:!0,children:ep(t.path)})]})]})}function oU(e){var t;let{cwd:n,sessionId:s,onClose:a,onReloaded:o,embedded:l=!1,trust:d}=e,{t:c}=(0,eX.s)(),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!0),[g,f]=(0,i.useState)(null),[x,b]=(0,i.useState)(()=>sC("plugins",n)),[v,y]=(0,i.useState)(!1),[k,j]=(0,i.useState)(""),[w,S]=(0,i.useState)("global"),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)(null),[E,T]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)({}),[P,z]=(0,i.useState)(new Set),[O,W]=(0,i.useState)(!1),[F,D]=(0,i.useState)(null),[B,_]=(0,i.useState)(!1),H=(0,i.useMemo)(()=>u?.packages??[],[u?.packages]),U=(0,i.useMemo)(()=>u?.standaloneExtensions??[],[u?.standaloneExtensions]),q=H.find(e=>oL(e)===x)??null,K=U.find(e=>oP(e)===x)??null,Z=u?.projectResourcesLoaded??!0,V=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:H.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[H]),J=(0,i.useCallback)(async()=>{m(!0),f(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),b(e=>e&&(t.packages.some(t=>oL(t)===e)||t.standaloneExtensions.some(t=>oP(t)===e))?e:t.packages[0]?oL(t.packages[0]):t.standaloneExtensions[0]?oP(t.standaloneExtensions[0]):null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{m(!1)}},[n]);(0,i.useEffect)(()=>{L({}),D(null),J()},[n]);let G=ou(d),Y=(0,i.useRef)(G);(0,i.useEffect)(()=>{Y.current!==G&&(Y.current=G,J())},[G,J]),(0,i.useEffect)(()=>{x&&sN("plugins",x,n)},[n,x]);let X=(0,i.useCallback)(async e=>{let t=(e?[e]:H.filter(e=>e.canCheckForUpdates)).map(oL);if(0!==t.length){D(null),z(e=>new Set([...e,...t])),e||W(!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[oL(e)]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{z(e=>{let n=new Set(e);for(let e of t)n.delete(e);return n}),e||W(!1)}}},[n,H]),Q=(0,i.useCallback)(async()=>{_(!0),$(null),T(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({}),T(c("i18n.packagesUpdated")),s&&T(`${c("i18n.packagesUpdated")} ${c("agents.reloadRequired")}`)}catch(e){$(e instanceof Error?e.message:String(e))}finally{_(!1)}},[n,s,c]),ee=(0,i.useCallback)(async(e,t)=>{let r=oL(t);N(`${e}:${r}`),$(null),T(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)b(s.packages[0]?oL(s.packages[0]):s.standaloneExtensions[0]?oP(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),T(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")};T(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,c]),et=(0,i.useCallback)(async(e,t,r)=>{let i=oc(t,r,e=>!e.disabled,e=>e.filtered),a=r?0:t.filter(e=>!e.disabled&&e.filtered).length,o=a>0?c("plugins.bulkKeptFiltered",{count:a}):void 0;if($(null),T(null),R(o?{scope:e,note:o}:null),0===i.length)return;let l=r?"enable":"disable";N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:l,cwd:n,packages:i.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),a=await t.json();if(!t.ok||a.error||!a.results)throw Error(a.error??`HTTP ${t.status}`);let{results:d,...u}=a;p(u);let h=d.filter(e=>e.error);if(h.length<d.length){let e=r?c("plugins.bulkEnabled"):c("plugins.bulkDisabled");T(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=oA(k).trim();if(!e)return;j(e);let t=`${w}\0${e}`;N(`install:${t}`),$(null),T(null),R(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:w,cwd:n})}),o=await a.json();if(!a.ok||o.error)throw Error(o.error??`HTTP ${a.status}`);p(o);let l=(r=o.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));b(l?oL(l):t),y(!1),j(""),T(c("i18n.packageInstalled"))}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,w,k,c]),er=(0,i.useCallback)(async()=>{if(s){N("reload"),$(null),T(null),R(null);try{await ic(s,{type:"reload"}),o?.(),await J(),T(c("i18n.sessionReloaded"))}catch(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,ea=H.some(e=>e.canCheckForUpdates),eo=h||null!==C||P.size>0||B;return(0,r.jsxs)(sQ,{embedded:l,title:c("common.plugins"),subtitle:ep(n),closeLabel:c("i18n.close"),onClose:a,children:[!Z&&(0,r.jsx)(ax,{message:c("trust.pluginsNotLoaded")}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:h?(0,r.jsx)("div",{className:"config-sidebar-message",children:c("i18n.loading")}):g?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:g}):0===H.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)(s5,{children:c("i18n.extensions")}),U.map(e=>{let t=oP(e);return(0,r.jsxs)(ae,{active:!v&&x===t,title:e.path,onClick:()=>{b(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aC,{active:e.enabled}),(0,r.jsx)(at,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),V.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)(s5,{aside:(0,r.jsx)(s9,{enabled:t,total:e.packages.length,disabled:eo,loading:C===`bulk:${e.scope}`,label:c(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:oz(e.scope,c)}),onChange:t=>void et(e.scope,e.packages,t)}),children:oz(e.scope,c)}),M?.scope===e.scope&&(0,r.jsx)(s7,{error:M.error,note:M.note}),e.packages.map(e=>{let t=oL(e),n=!v&&x===t;return(0,r.jsxs)(ae,{active:n,title:e.description??e.source,onClick:()=>{b(t),y(!1),$(null),T(null)},children:[(0,r.jsx)(aC,{active:!e.disabled,color:oF(e.status)}),(0,r.jsx)(at,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[oL(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:c("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,r.jsx)(aS,{active:v,onClick:()=>{y(!0),$(null),T(null)},children:c("i18n.addPlugin")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:v?(0,r.jsx)(oB,{cwd:n,source:k,scope:w,projectResourcesLoaded:Z,busy:ei,actionError:I,onSourceChange:j,onScopeChange:S,onInstall:en}):h?null:K?(0,r.jsx)(oH,{extension:K}):q?(0,r.jsx)(o_,{pkg:q,cwd:n,busyKey:C,actionError:I,actionMessage:E,sessionId:s,updateStatus:A[oL(q)],checkingUpdate:P.has(oL(q)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(q),onReloadSession:er},oL(q)):(0,r.jsx)(ab,{children:c("i18n.selectPackage")})})})]}),(0,r.jsxs)(ay,{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)(ak,{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(oW)}):(0,r.jsx)(ak,{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:[!l&&(0,r.jsx)(aj,{onClick:a,children:c("i18n.close")}),ea&&(0,r.jsx)(aj,{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"):O?c("i18n.checking"):es>0?`${c("i18n.updateAllPlugins")} (${es})`:c("i18n.checkUpdates")}),(0,r.jsx)(aj,{variant:"secondary",onClick:()=>void J(),disabled:eo,children:c("i18n.refresh")})]})]})}let oq="\\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",oK=RegExp(`[${oq}]`,"gu"),oZ=RegExp(`[${oq}]`,"u");function oV(e){return e.replace(oK,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let oJ=/[\s"'`$|&;<>()*?#~]/;function oG(e){let t=oZ.test(e),n=oV(e);return""===n||t||oJ.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function oY(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(oG).join(" ")}function oX(e){let t=void 0!==e.command?oY(e.command,e.args):void 0,n=void 0!==e.url?oV(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function oQ(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&oZ.test(e))}function o0(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:oV(e.name??"")}}}function o1(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function o2(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function o4(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function o8(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?oV(e.error):"link-outside"===e.reason?void 0===t?void 0:oV(t):void 0}let o6="codemode";function o3(e){return`${e.scope}\0${e.name}`}function o5(e){return e?.trust?.decision===!0}function o9(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function o7(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?o9(e.status):"on":"mcp-off":"not-trusted":"disabled"}let le={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"},lt={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function ln(e,t){return(t?.origin==="session"?lt[e]:void 0)??le[e]}let lr={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},li={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 ls(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 la(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function lo(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 ll={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"},ld={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"},lc={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},lu={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},lp=["codemode","deferred","direct","hidden"],lh={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function lm(e){return"auto-enable-codemode-invalid"!==e.reason}function lg(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 lf(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function lx(e,t){let n=e.flatMap(e=>e.servers.map(o3));return t===o6||null!==t&&n.includes(t)?t:n[0]??null}function lb(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function lv(e){return e.projectOverride?.preference??e.preference}let ly={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},lk={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},lj={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},lw={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function lS(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let lC=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function lN(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}:{},...lC(n.names)?{names:n.names}:{},...lC(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 lI(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},a=new AbortController,o=()=>a.abort();r?.aborted?a.abort():r?.addEventListener("abort",o,{once:!0});let l=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&a.abort()},n)});try{return await Promise.race([e(a.signal),l])}finally{clearTimeout(i),r?.removeEventListener("abort",o)}}function l$(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 lE(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&&l$(i)?{ok:!0,data:i}:{ok:!1,error:lN(i,r.status)}}let lT=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function lM(e,t,n){let r=await lE(e,t,n);if(r.ok||!e||!r.error.reason||!lT.has(r.error.reason))return r;let i=await lE(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function lR(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 lI(n=>lM(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function lA(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 a=i.ok&&null!==s&&"object"==typeof s?t(s):void 0;return void 0!==a?{ok:!0,stored:a}:{ok:!1,error:lN(s,i.status)}}async function lL(e,t,n){let r=await lA({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 lP(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 lI(n=>lL(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function lz(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 lI(async n=>{let r=await lA({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 lO(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 lI(async n=>{let r=await lA({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 lW(e){return!e.available&&"builtin-disabled"!==e.reason}function lF(e,t){if(lW(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!o5(t.project))return"project-untrusted"}}let lD={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function lB(e){return!0!==e.notAnObject}function l_(e){return lB(e)&&void 0===e.webPasswordField}async function lH(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&&l$(i)?{ok:!0,data:i}:{ok:!1,error:lN(i,r.status)}}async function lU(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 lI(e=>lH(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let lq={"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 lK(e,t){let n=lF(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let lZ={"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"},lV={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},lJ={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},lG={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function lY(e){return(Math.max(0,e)/1e3).toFixed(1)}async function lX(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:lN(i,r.status)}}async function lQ(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 lI(e=>lX(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let l0="•••",l1=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),l2=new Set([...l1,"auth","sig","code","pw"]),l4=["token","secret","password","passwd","apikey"],l8=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),l6=new Set(["-k"]);function l3(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 l5(e,t){let n=l3(e);return!(n.length>1&&l8.has(n[n.length-1]))&&n.some(e=>t.has(e)||l4.some(t=>e.length>t.length&&e.endsWith(t)))}function l9(e){return l5(e,l1)}let l7=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,})"),de=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,dt=/^[A-Za-z0-9_\-+/=.~]+$/;function dn(e){return!(/\s/.test(e)||dl(e))&&(!!(l7.test(e)||de.test(e))||!(e.length<24||!dt.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 dr=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,di=RegExp(dr.source,"g"),ds=/^(?:bearer|basic|token)\s+/i;function da(e,t,n){let r=e.replace(ds,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function dl(e){return da(e.replace(/\$[$!]/g,"_x"),dr,di)}let dd=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,dc=RegExp(dd.source,"g");function du(e){return da(e,dd,dc)}function dp(e,t){if(!e||""===t)return;e.push(t);let n=dg(t);n!==t&&e.push(n)}let dh=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function dm(e,t,n){let r=!1,i=e,s="",a=dh.exec(e);if(a){let[o,l,d]=a,c=d.lastIndexOf("@");if(c>=0&&!t(dg(d.slice(0,c)))){s=`${l}${l0}${d.slice(c)}`,r=!0;let e=d.slice(0,c);dp(n,e);let t=e.indexOf(":");t>=0&&dp(n,e.slice(t+1))}else s=o;i=e.slice(o.length)}let o=i.search(/[?#]/),l=o<0?i:i.slice(0,o),d=o<0?"":i.slice(o),c=l.split("/").map(e=>dn(dg(e))?(r=!0,dp(n,e),l0):e).join("/");return d=d.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let a=s.indexOf("=");if(a<0){let a=dg(s);return!dn(a)||t(a)?e:(r=!0,dp(n,s),`${i}${l0}`)}let o=s.slice(0,a),l=dg(s.slice(a+1));return""===l||t(l)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return l5(t,l2)}(o)&&!dn(l)?e:(r=!0,dp(n,s.slice(a+1)),`${i}${o}=${l0}`)}),{value:`${s}${c}${d}`,masked:r}}function dg(e){try{return decodeURIComponent(e)}catch{return e}}let df=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function dx(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&l9(r[1])){let[,i,s,a]=r;return t(a)?{value:e,masked:!1}:(dp(n,a.trim()),{value:`${i}:${s}${l0}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||df.test(e)))return;let i=!1;return{value:r.map(e=>{let r=df.exec(e);if(!r)return e;let[,s,a]=r;if(""===a.trim()||t(a))return e;if(l9(s.slice(0,-1).trim()))return i=!0,dp(n,a.trim()),`${s}${l0}`;let o=dx(a,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]&&l9(s[1]))return t(s[2])?{value:e,masked:!1}:(dp(n,s[2]),{value:`${s[1]}=${l0}`,masked:!0});if(/\s/.test(e)){var a,o,l;let r,i;return a=e,o=t,l=n,i=dy((r=a.split(/(\s+)/)).filter((e,t)=>t%2==0),o,!0,l),{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 dm(e,t,n);if(s&&""!==s[2]){let e=dx(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return dn(e)&&!t(e)?(dp(n,e),{value:l0,masked:!0}):{value:e,masked:!1}}function db(e){if(l6.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return l9(t)||"auth"===l3(t).at(-1)}let dv=/^(?:bearer|basic|token)$/i;function dy(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&dv.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,dp(r,e),l0)}let a=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(a){let[,e,n]=a;if(""!==n&&db(e)&&!t(n))return i=!0,dp(r,n),`${e}=${l0}`;let s=dx(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=db(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(dv.test(e)||t&&l9(t[1]))return s=!0,e}let o=dx(e,t,r);return i||=o.masked,o.value}),masked:i}}function dk(e){let{values:t,masked:n}=dy(e,du,!1);return{args:t,masked:n}}function dj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dw(e){return!e.startsWith("!")&&!dl(e)}function dS(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 dC={"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(dC);let dN={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},dI={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},d$={...dI,bareDollar:!0},dE={...dN,braceEnv:!0},dT=/^[A-Za-z_][A-Za-z0-9_]*$/,dM=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function dR(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function dA(e,t,n){let r=[],i=0;dM.lastIndex=0;for(let s=dM.exec(e);s;s=dM.exec(e)){let[a,o,l,d,c,u]=s,p=a;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(dT.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,a);else if(void 0!==l&&t.bareDollar)p={kind:"env",name:l,from:a};else if(void 0!==d&&t.percent&&n)p={kind:"env",name:d,from:a};else if(void 0!==c&&t.braceEnv)p="env"===c&&dT.test(u)?{kind:"env",name:u,from:a}:{kind:"unsupported",from:a};else if(void 0!==d||void 0!==c){dR(r,e.slice(i,s.index+1)),i=s.index+1,dM.lastIndex=s.index+1;continue}dR(r,e.slice(i,s.index)),"string"==typeof p?dR(r,p):r.push(p),i=s.index+a.length}return dR(r,e.slice(i)),r}function dL(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 dP(e){return e.startsWith("!")}function dz(e){if(dP(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);dT.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 dO=/<[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,dW=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,dF=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,dD=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function dB(e){return e.join("\0")}function d_(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function dH(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function dU(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let dq=new Set(["HOME","USERPROFILE"]);class dK{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 dZ(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let dV=/\$\{[^{}]*\}/g,dJ=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class dG{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(dZ),this.urlText=dZ(e.url??[])}encode(e,t){let n,r=dH(e),i=d_(e),s=dZ(t),a=[],o=!1,l=()=>a.every(e=>""===e),d=e=>{if(!r)return void a.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=dL(e,{atStart:l()});n!==e&&(o=!0),a.push(n)},c=e=>a.push(e),u=e=>a.push({field:e});if(!r&&dU(e)&&1===t.length&&"text"in t[0]&&dF.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(dF.test(n))return t&&c(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,a,void 0)}let p=0;return t.forEach((a,o)=>{let h=t[o+1],m=void 0===h||"text"in h&&/^[\\/]/.test(h.text),g=(t,r,i)=>{let a=0;for(let[d,c]of function(e){let t=e.trim();if(dW.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=dD.exec(t);if(n&&dW.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];dO.lastIndex=0;for(let t=dO.exec(e);t;t=dO.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,l;if(i.some(e=>{let[t,n]=e;return d<n&&c>t}))continue;d>a&&r(t.slice(a,d)),"url"===e[0]&&dY(s,p+d)&&(n="uri-component");let h=t.slice(d,c);u(this.field(e,"placeholder",(o=e,l=h,"env"===o[0]||"headers"===o[0]?o[1]:l.replace(/^[<{\s]+|[>}\s]+$/g,"")||d_(o)),h)),a=c}a<t.length&&r(t.slice(a))};switch(a.kind){case"text":g(a.text,d,[]);break;case"pi":{var f;let e=h?(f=a.text,(/\$+$/.exec(f)?.[0].length??0)%2==1?`${f}$`:f):a.text;if(r&&l()&&dP(e)){this.draft.note("shell-command-value",{field:i}),c(e);break}let t=[...e.matchAll(dV)].map(e=>[e.index,e.index+e[0].length]);g(e,c,t);break}case"env":r?(c(`$\{${a.name}}`),void 0!==a.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:a.name,fallback:a.fallback}),a.shell?this.draft.note("shell-variable",{field:i,name:a.name}):a.from!==`$\{${a.name}}`&&this.draft.note("variable-translated",{field:i,from:a.from,to:`$\{${a.name}}`})):dU(e)&&l()&&dq.has(a.name)&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):(u(this.field(e,"variable",a.name,a.from,void 0,a.fallback)),this.draft.note(a.shell?"shell-variable":"variable-unsupported-here",{field:i,name:a.name}));break;case"input":u(this.inputField(e,a));break;case"home":r?(c("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:a.from,to:"${HOME}"})):dU(e)&&l()&&m?(c("~"),this.draft.note("home-translated",{field:i,from:a.from})):u(this.field(e,"home","userHome",a.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",a.from,"text")):(c("."),this.draft.note("workspace-folder-relative",{field:i,from:a.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",a.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",a.from,a.from)),this.draft.note("unsupported-variable",{field:i,variable:a.from});break;case"prompt":"url"===e[0]&&dY(s,p)&&(n="uri-component"),u(this.promptField(e,a))}p+=("text"in a?a.text:a.from).length}),o&&this.draft.note("escaped-value",{field:i}),this.target(e,a,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=>dB(t.path)===dB(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 a=dJ.has(t)?`${t}.${n}`:d_(e);if(dJ.has(t)){if(this.fields.has(a))return a}else for(let t=2;this.fields.has(a);t++)a=`${d_(e)}#${t}`;let o=this.isSecretContext(e,r)||l9(n),l="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(a,{id:a,kind:i??(o?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&l?{optional:!0}:{},targets:[]}),a}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 l9(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(dk([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&dk([t,"x"]).args[1]===l0}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,dm(`https://host.invalid/?${n}=x`,du).masked)}default:return!1}}}function dY(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 dX(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 dQ=/^[A-Za-z0-9_-]+$/;function d0(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 d1=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function d2(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=d8(t);return s&&!d1.has(s.toLowerCase())?s:d8(r)||r||s||t}let d4=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function d8(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,d4)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let d6=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function d3(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=>!d6.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let d5=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 d9(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 d7(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(!d1.has(n.toLowerCase())&&"."!==n&&".."!==n)return d8(n.replace(/_/g,"-"))||n}return""}function ce(e,t){ct(e,t)&&cn(e,Math.ceil(t/1e3),t)}function ct(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function cn(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 cr=["codemode","deferred","direct","hidden"],ci={"codemode-deferred":"codemode"},cs=["localhost","127.0.0.1","[::1]"];function ca(e){return"string"==typeof e&&cr.includes(e)?e:"string"==typeof e&&Object.hasOwn(ci,e)?ci[e]:void 0}function co(e){try{return new URL(e)}catch{return}}function cl(e){let t=co(e);return void 0!==t&&"http:"===t.protocol&&cs.includes(t.hostname)&&""===t.search&&""===t.hash}function cd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cc(e){return cd(e)&&Object.values(e).every(e=>"string"==typeof e)}function cu(e,t){if(!dQ.test(e))return{problem:"name",name:e};if(!cd(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:a,description:o}=t;if(void 0!==r&&!ca(r))return{problem:"exposure",value:String(r)};if(void 0!==a){if(!cd(a))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(a))if(!ca(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=co(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!cc(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!cd(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||!cl(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&&"auto"!==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?co(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)?co(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&cs.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(!cd(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!cs.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||cc(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let cp=/[A-Za-z_]/,ch=/[A-Za-z0-9_]/,cm=/^[A-Za-z_][A-Za-z0-9_]*$/,cg=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),cf=new Set([..."|&;<>()"]),cx=/[0-9@*#?$!-]/,cb={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function cv(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 cy(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class ck{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 cj)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new cj(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=cy(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)&&cv(e,this.index)>0)this.index+=cv(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:"`"}):cf.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||!cg.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=cy(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 cb?(t+=cb[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&&cp.test(n)){let n=this.index+1;for(;n<t.length&&ch.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&&cx.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}),cm.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 cj extends Error{constructor(e){super(e.code),this.detail=e}}function cw(e){return new ck(e).run()}function cS(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function cC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let cN=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function cI(e){if(cN.some(t=>t in e))return!0;let t=e.oauth;return cC(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function c$(e){if(!cC(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]||cC(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function cE(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 cT(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 cM(e,t){let n=t?cT(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function cR(e){return e?{server:e}:{}}function cA(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function cL(e,t,n){let r;if(!cC(t))return{note:{code:"no-command-or-url",params:cR(e)}};let i=new Set,s=e=>(i.add(e),t[e]),a=n.rawPi,o=function(e,t){switch(e.flavor){case"zed":return dN;case"opencode":return dE;case"vscode":return dI;default:return cI(t)?d$:dI}}(n,t),l=s("name"),d=e??("string"==typeof l?l:void 0),c=new dK(n.source,a),u=(e,t)=>{if(a)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&c.note("looks-like-pi-config"),dA(e,o,t)};c.name=d,c.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(c.inputs=new Map([...n.inputs??[],...cO(p)]));let h=s("type"),m=s("command"),g=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:cR(d)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?cE(h):"unknown"))return{note:{code:"unsupported-transport",params:{...cR(d),type:String(h)}}};let f="string"==typeof m&&""!==m||Array.isArray(m)||cC(m),x=void 0!==g;if("sse"===r)return{note:cM(d,g)};if("ws"===r)return{note:{code:"websocket-transport",params:{...cR(d),...g?{url:g}:{}}}};if(void 0===r){if(f&&x)return{note:{code:"ambiguous-command-and-url",params:cR(d)}};if(x){if(void 0!==cT(g))return{note:cM(d,g)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&c.note("transport-guessed")}else{if(!f)return{note:{code:"no-command-or-url",params:cR(d)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...cR(d),type:String(h)}}};if("stdio"===r&&!f||"http"===r&&!x)return{note:{code:"no-command-or-url",params:cR(d)}};if(c.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let a,o=r("args"),l=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===l&&(l=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...cR(e.name),problem:"args"}};a=n[0],o=[...n.slice(1),...Array.isArray(o)?o:[]]}else if(cC(n))for(let t of(a="string"==typeof n.path?n.path:void 0,void 0===o&&(o=n.args),void 0===l&&(l=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(a=n);if(!a)return{code:"no-command-or-url",params:cR(e.name)};let d=Array.isArray(o)?[...o]:[];if(void 0!==o&&!Array.isArray(o))return{code:"invalid-config",params:{...cR(e.name),problem:"args"}};if(0===d.length&&/\s/.test(a.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(a.trim())){let t=cw(a.trim()),n=t.ok?t.words.map(cS):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:a}),a=n[0],d.push(...n.slice(1)))}for(let[t,n]of(e.command=i(a,!1),d.entries())){let r=cA(n);if(void 0===r)return{code:"invalid-config",params:{...cR(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==l){if(!cC(l))return{code:"invalid-config",params:{...cR(e.name),problem:"env"}};for(let[t,n]of Object.entries(l)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=cA(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&&l9(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,m,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),a=i(n,!1),o=cC(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===a.length&&"text"in a[0]?dX(e,n,o):e.url=a,cC(s))for(let[t,n]of Object.entries(s)){let r=cA(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):l9(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 l=r("oauth"),d=r("auth");if(!1===l?e.note("oauth-disable-unsupported"):cC(l)?cP(e,l,i):void 0!==l&&e.note("dropped-key",{key:"oauth"}),cC(d))for(let t of(cP(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,g,s,u);let b=s("timeout");if(void 0!==b)if(a)"number"==typeof b&&b>0?c.timeout=b:c.note("timeout-dropped",{value:String(b)});else if("opencode"===n.flavor)c.note("timeout-dropped",{value:String(b)});else if(cI(t))ce(c,b);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?ct(c,b)&&cn(c,Math.ceil(b),void 0):!function(e,t){if(!ct(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?cn(e,Math.ceil(t/1e3),t):cn(e,Math.ceil(t),void 0)}(c,b);let v=s("enabled"),y=s("disabled");!1===v||!0===y?(c.enabled=!1,c.note("imported-disabled")):(void 0!==v&&"boolean"!=typeof v||void 0!==y&&"boolean"!=typeof y)&&c.note("dropped-key",{key:void 0!==v?"enabled":"disabled"});let k=s("exposure");if(void 0!==k){let e=ca(k);e?c.exposure=e:c.note("invalid-exposure-dropped",{value:String(k)})}let j=s("toolExposure");if(void 0!==j){let e=cC(j)?Object.entries(j).map(e=>{let[t,n]=e;return[t,ca(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(a||void 0===k&&void 0===j||c.note("looks-like-pi-config"),a){let e=s("description");"string"==typeof e?c.description=e:void 0!==e&&c.note("dropped-key",{key:"description"})}for(let e of(cz(c,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||c.note("dropped-key",{key:e});return{draft:c}}function cP(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":"auto"===s||"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&&cl(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 cz(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 a={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))a[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)a[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=a}function cO(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)cC(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=>cC(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function cW(e,t,n,r){let i=[],s=0;for(let a of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){a.index>s&&i.push({kind:"text",text:e.slice(s,a.index)});let o=cC(t)&&cC(t[a[1]])?t[a[1]]:{};i.push(cF(`${n}${a[1]}`,a[1],a[0],o,r)),s=a.index+a[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function cF(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 cD(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...dA(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 cB(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 a=i.value.slice(s+t.length);return[n,[...a?[{...i,value:a}]:[],...e.slice(r+1)]]}}let c_=/^https?:\/\//i,cH=/^wss?:\/\//i,cU={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},cq=new Set(["pi","claude","codex","gemini"]),cK=new Set(["install","remove","uninstall","update","list","config"]);function cZ(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let cV={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","oauth-client-registration":"value",exposure:"value",description:"value"},cJ=new Map([["-l","--local"]]),cG=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name","oauth-client-registration"],cY=["env","cwd"];function cX(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 a=t[s],o=a.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(a);continue}let l=o.startsWith("--")?o.indexOf("="):-1,d=l>0?o.slice(0,l):o,c=n[d];if(!c){if(i.positional.length>=r.asArgAfter){i.positional.push(a),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=l>0?cQ(a,l+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 cQ(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 c0=/^[A-Za-z_][A-Za-z0-9_]*=/,c1=/^[^\s:]+:/;function c2(e,t,n,r){for(let i of t??[]){let t=cB(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],cD(t[1],n,!0)])}}function c4(e,t,n,r){for(let i of t??[]){let t=cB(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let a=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()&&a.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,cD(a,n,!0)])}}function c8(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function c6(e,t,n,r,i){let s,[a,o,...l]=r;if(!a||!o)return{code:"cli-usage",params:{cli:t}};e.name=a.text;let d=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===d){if("http"==(s=c_.test(o.text)?"http":cH.test(o.text)?"ws":"stdio")&&void 0!==cT(o.text))return cM(a.text,o.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===d?"http":d;return"sse"===s?cM(a.text,o.text):"ws"===s?{code:"websocket-transport",params:{server:a.text,url:o.text}}:"http"===s?(e.transport="http",e.url=cD(o.parts,i,!1),l.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:l.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:a.text,type:s}}:(e.transport="stdio",e.command=cD(o.parts,i,!1),e.args=l.map(e=>cD(e.parts,i,!1)),"stdio")}let c3={"-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 c5(e,t){return"env"===e?c0.test(t.text):c1.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function c9(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let c7={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function ue(e){let t,n=cS(e)??e.text;try{t=dS(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return cC(t)?{value:t}:{error:{code:"no-servers-found"}}}let ut={"--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"}},un={"-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 ur(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(ui(r),ui(i))}return t}function ui(e){try{return decodeURIComponent(e)}catch{return e}}function us(e){let t=e.trim();for(let e=0;e<4;e++)try{return dS(t)}catch{let e=ui(t);if(e===t)break;t=e.trim()}}function ua(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function uo(e){let t=e.get("config");if(!t)return ua("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:us(n);return cC(r)?{entries:[cL(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:ua("config")}function ul(e,t,n,r){return cC(e)?{entries:[cL(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:cO(r)})],notes:[]}:ua("config")}function ud(e){return{error:{code:"by-name-link",params:{name:e}}}}function uc(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function uu(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.replace(/&/g,"&");try{t=new URL(r)}catch{if(/^https?:\/\/\S+$/i.test(r)&&0===n)return{entries:[uh(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return ua("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return uo(ur(t.search));return ua("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 ud(ui(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return ud(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return ul(us(uc(r)),"vscode-install-link");return ua(i)}case"vsweb+mcp":return ul(us(uc(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return ul(us(uc(r)),"copilot-app-install-link");return ua(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 uo(ur(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=ur(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return uu(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?ul(us(e),"vscode-install-link",t.get("name")||void 0,us(t.get("inputs")??"[]")):ua("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return ul(us(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=ur(e.search).get("open");return t?uu(t,n+1):ua("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:[uh(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let up=new Set(["localhost","127.0.0.1","[::1]"]);function uh(e,t){let n=d3(t)||void 0;if(void 0!==cT(t))return{note:cM(n,t)};let r=new dK("url",!1);return r.transport="http",dX(r,t,!1),e?.protocol!=="http:"||up.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let um=/[\u200B-\u200D\u2060\uFEFF]/g,ug=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,uf={"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 ux(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>dB(e.path))))}function ub(e){var t;let n,r,i,s,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=(n=e.replace(um,"").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=dS(e)}catch(t){try{n=dS(`{${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 cL(n,r,t)});if(Array.isArray(e)){let r=e.filter(c$);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>cL(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!cC(e))return{error:{code:"no-servers-found"}};let i=cC(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?d2(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(cC):[],i=r.filter(e=>"string"==typeof e.type&&"http"===cE(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:cM(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:cR(n)}}]}return i.map(e=>{let r=new dK("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=cW(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(cC):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,cW(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[cF(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(cC(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(cC(e.servers)){let t=cO(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(cC(e.mcp)){let t=e.mcp;if(cC(t.servers)){let e=cO(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(cC(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return cC(r)&&("extension"===r.source||!c$(r))?{note:{code:"zed-extension-server",params:{server:n}}}:cL(n,cC(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(c$(e))return{entries:[cL(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(cC)&&s.some(c$)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(o,!0===a.rawPi);else if(ug.test(o)){if(!("error"in(s=uu(`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)?uu(o):(e=cw(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&&cU[i]&&e[t+1]?.text==="mcp"&&(n=t,r=cU[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 cZ(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=cJ.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 a=s.slice(2),o=cV[a];if(!o)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===o){r.set(a,!0);continue}let l=e[++t];if(void 0===l)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===o?i.set(a,[...i.get(a)??[],l]):r.set(a,l)}let[s,...a]=n,o=r.get("url");if(!s||""===s.text||void 0===o==(0===a.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let l=e=>{let t=r.get(e);return!0===t?void 0:t},d=(void 0===o?cG:cY).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 dK("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=cB(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=cD(o.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)c.headers.push([t,cD(n,"pi",!0)]);let t=l("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=l("oauth-client-id"),r=l("oauth-client-secret"),i=l("oauth-callback-port"),s=l("oauth-client-name"),a=l("oauth-client-registration");n&&(c.oauth.clientId=cD(n.parts,"pi",!1)),r&&(c.oauth.clientSecret=cD(r.parts,"pi",!0)),i&&(c.oauth.callbackPort=Number(i.text)),s&&(c.oauth.clientName=cD(s.parts,"pi",!1)),a&&(c.oauth.clientRegistration=a.text),p.url=o.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":o.text,(i||s||a)&&(p.oauth={...n?{clientId:n.text}:{},...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{},...a?{clientRegistration:a.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,cD(n,"pi",!0)]);let[t,...n]=a;c.command=cD(t.parts,"pi",!1),c.args=n.map(e=>cD(e.parts,"pi",!1));let r=l("cwd");r&&(c.cwd=cD(r.parts,"pi",!1)),p.command=t.text}let h=l("exposure");void 0!==h&&(p.exposure=h.text,c.exposure=ca(h.text)??h.text);let m=l("description");void 0!==m&&(p.description=m.text,c.description=m.text);let g=cu("server",p);return g?{note:{code:"invalid-config",params:{server:s.text,...g}}}:{draft:c}}(t,i.slice(1)));if("claude"===r&&"add"===e)return cZ(function(e){let t=cX("claude",e,c3,{asArgAfter:2,variadic:c5});if("error"in t)return{error:t.error};let n=new dK("claude-mcp-add",!1),r=c6(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],dI);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=c8(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=c4(n,t.lists.get("header"),dI,"claude");if(r)return{error:r};let a=t.values.get("client-id");a&&!0!==a&&(n.oauth.clientId=cD(a.parts,dI,!1)),t.values.has("client-secret")&&c9(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=c2(n,t.lists.get("env"),dI,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return cZ(function(e){let t=cX("claude",e,c7,{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=ue(r);if("error"in s)return s;let a=cL(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in a||(a.draft.scopeHint=c8(t.values.get("scope")),t.values.has("client-secret")&&"http"===a.draft.transport&&!a.draft.oauth.clientSecret&&c9(a.draft)),a}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return cZ(function(e){let t=cX("codex",e,ut,{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,a=n.length>0?n:s,o=t.values.get("url");if(!i||void 0===o==(0===a.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let l=new dK("codex-mcp-add",!1);for(let e of(l.name=i.text,["config","enable","disable"]))t.values.has(e)&&l.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&l.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!==cT(o.text))return{note:cM(i.text,o.text)};l.transport="http",l.url=cD(o.parts,dN,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&l.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&&(l.oauth.clientId=cD(n.parts,dN,!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"}}};l.transport="stdio";let e=c2(l,r,dN,"codex");if(e)return{error:e};l.command=cD(a[0].parts,dN,!1),l.args=a.slice(1).map(e=>cD(e.parts,dN,!1))}return{draft:l}}(t));if("gemini"===r&&"add"===e)return cZ(function(e){let t=cX("gemini",e,un,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new dK("gemini-mcp-add",!1),r=c6(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],d$);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=c8(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=c4(n,t.lists.get("header"),d$,"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=c2(n,t.lists.get("env"),d$,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&ce(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 cz(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(cq.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]&&cK.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=cQ(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=ue(r);if("error"in s)return s;t.push(cL(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):cZ(function(e){let t=new dK("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,cD(r.value,dN,!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=cD(i.parts,dN,!1),t.args=e.slice(n+1).map(e=>cD(e.parts,dN,!1));let s=e.slice(n+1).map(e=>e.text),a=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>c_.test(e)):void 0;return a&&t.note("mcp-remote-bridge",{url:a}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:uf[t],params:n}:{code:uf[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let l=[...s.notes],d=[],c=[...a.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){l.push(e.note);continue}let n=function(e){let t,n=new dG(e);if("stdio"===e.transport&&e.command&&""!==dZ(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||""===dZ(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:a,clientSecret:o,callbackPort:l,clientName:d,clientRegistration:c,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;a&&(s.clientId=n.encode(["oauth","clientId"],a)),o&&(s.clientSecret=n.encode(["oauth","clientSecret"],o)),void 0!==l&&(s.callbackPort=l),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){l.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return d3(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&&d3(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=d9(t,new Set(["-p","--package","-c","--call"]));return e?d2(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?d9(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?d2(n):""}case"uvx":case"pipx":{let e=d9("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?d2(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?d9(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?d7(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?d9(t.slice(e+1),d5):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return d8(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return d2(t[e+1].replace(/_/g,"-"));let n=d9(t,new Set(["-X","-W"]));return n?d7(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=d9("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?d7(e):""}default:return d8(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let a=(t=i,dQ.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";a!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:a}}));let o=d0(a,s?[...c,...u]:u);o!==a&&(r.notes.push({code:"name-deduplicated",params:{original:a,name:o}}),a=o),!s&&c.includes(a)&&r.notes.push({code:"name-taken",params:{name:a,suggestedName:d0(a,[...c,...u])}}),r.name=a;let p=cu(a,function(e){let t=ux(e),n=JSON.parse(JSON.stringify(e.config));t.has(dB(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(dB(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){l.push({code:"invalid-config",params:{server:a,...p}});continue}!function(e){let t=ux(e);for(let n of uN(e.config))t.has(dB(n))||e.notes.push({code:"literal-secret",params:{field:d_(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=dz(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=dz(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(a),d.push(r)}return 0===d.length?{ok:!1,notes:l.length>0?l:[{code:"no-servers-found"}]}:{ok:!0,servers:d,notes:l}}let uv=/^[A-Za-z_][A-Za-z0-9_]*$/;function uy(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 uk(e){let t=ux(e);return uN(e.config).filter(e=>dH(e)&&!t.has(dB(e)))}function uj(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let uw=/^(?:bearer|basic|token)\s+/i;function uS(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],a=new Map(uk(e).map(e=>[d_(e),e])),o=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=a.get(e);r?uv.test(n)?o.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:uj(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():"";uv.test(r)?"select"!==n.kind&&n.targets.every(e=>dH(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:uj(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 l=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&&l.add(d_(e.path));let s=dB(e.path);if(d.has(s))continue;if(d.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){uy(r,e.path,void 0);continue}let a="";for(let t of e.parts){var c,u,p,h;a+="string"==typeof t?t:(c=i.get(t.field),u=e.path,p=""===a,h=e.encoding,"reference"in c?`$\{${c.reference}}`:"uri-component"===h?encodeURIComponent(c.text):dH(u)?dL(c.text,{atStart:p}):c.text)}uy(r,e.path,a)}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(uw)?.[0]??"":"";uy(r,e,`${i}$\{${t}}`)}for(let e of uN(r))l.add(d_(e));return{ok:!0,config:r,secretPaths:[...l]}}let uC=["command","args","env","cwd","url","headers","oauth"];function uN(e){let t=[];for(let n of function(e){if(!dj(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(dj(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&dw(i)&&""!==i&&(l9(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||dx(i,dl).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=dj(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&dw(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&dm(e.url,du).masked&&t.push({kind:"url"}),"string"==typeof e.command&&dx(e.command,du).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&dk(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:""):[];dk(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>uC.indexOf(e[0])-uC.indexOf(t[0]))}let uI="PI_WEB_PASSWORD";function u$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uE(e){return u$(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function uT(e){if(!u$(e))return[];if(!("url"in e))return uE(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=uE(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=u$(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let uM={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function uR(e,t,n){let r=ub(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,a="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,a])}function uA(e,t){let n={...e,...t},r=uR(e.text,e.rawPi,e.server);if(void 0!==r&&r===uR(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function uL(e){return dC[e.code]??"warning"}function uP(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?oV(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=oV(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 a=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:a}):a}let uz={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"},uO={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"},uW=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),uF=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),uD=[{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 '${uF}'`},{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(uW)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(uF)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(uF)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(uF)}`}];function uB(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?oV(r):r.field===e.id?n:`‹${oV(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function u_(e){return"select"!==e.kind&&e.targets.every(e=>dH(e.path)&&void 0===e.encoding)}let uH=/^[A-Za-z_][A-Za-z0-9_]*$/;function uU(){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 uH.test(r)?r:void 0}let uq=/^(?:proxy-)?authorization$/i;function uK(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return uH.test(t)?t:uU(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return uU(t,...n)??uU(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(uq.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===uI?void 0:n}function uZ(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function uV(e,t){let n=e;for(let e of t)n=n.split(e).join(l0);return{text:n,masked:n!==e}}function uJ(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function uG(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(lm);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function uY(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function uX(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 uQ(e,t,n){switch(e.kind){case"trust-too-broad":return t(u1[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(u0[e.kind])}}let u0={"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"},u1={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 u2(e){return oV(ep(e))}function u4(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let u8=[{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"}],u6=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function u3(e){let{notes:t,fields:n=[]}=e,{t:i}=(0,eX.s)();if(0===t.length)return null;let s={error:0,warning:1,info:2},a=[...t].sort((e,t)=>s[uL(e)]-s[uL(t)]);return(0,r.jsx)("ul",{className:"mcp-add-notes",children:a.map((e,t)=>(0,r.jsx)("li",{className:`mcp-add-note is-${uL(e)}`,children:uP(e,i,n)},`${t}\0${e.code}`))})}let u5={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function u9(e){let{data:t,cwd:n,draft:s,busy:a,controlsBusy:o,failure:l,onDraftChange:d,onSubmit:c,onTrustProject:u}=e,{t:p}=(0,eX.s)(),h=(0,i.useId)(),m=(0,i.useId)(),g=(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:lb(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),a=e=>ub(t.text,{rawPi:t.rawPi,takenNames:uY(n,e)}),o=a(t.scope??"global"),l=o.ok?o.servers[Math.min(t.server,o.servers.length-1)]:void 0,d=t.scope??(l?.scopeHint==="project"&&"write"===s.kind?"project":"global");d!==(t.scope??"global")&&(l=(o=a(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=lW(n.mcp);if(!l)return{...c,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??l.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&u_(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(l,t),m=uk(l).map(d_),g=Object.fromEntries(m.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),f=uS(l,h,g),x={};if(!f.ok)for(let e of f.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let b=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]=uH.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=uS(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,uH.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(l,h,g),v=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,a={source:e.source,commandFields:uT(r).filter(e=>{let{value:t}=e;return dP(t)}).map(uJ),variableReferences:uT(r).map(e=>({...uJ(e),variables:dz(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=uV(r.url,i);return{...a,transport:"http",target:oV(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let o=uV(oY(r.command,r.args??[]),i);return{...a,transport:"stdio",target:o.text,...void 0!==r.cwd?{cwd:oV(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:o.masked}}(l,h,f),y=f.ok?cu(p,f.config):void 0,k="blocked"===s.kind?s.block:b.length>0?{kind:"secret",fields:b,fixed:!b.every(uZ)}:uG("project",n),j=uY(n,d),w=n.files.find(e=>e.scope===d);if(u)i={kind:"mcp-off"};else if(dQ.test(p))if(j.includes(p))i={kind:"name-taken",name:p,suggestedName:d0(p,j),...w?{path:w.path}:{}};else if(f.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:v.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of uT(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(uI):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===uI))return r}(f.config,{isCommandConfigValue:dP,getConfigValueEnvVarNames:dz}))i={kind:"web-password"};else if("project"===d&&k)i={kind:"scope",block:k};else{let e=uG(d,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return l.fields.find(e=>e.id===t)?.label??t},t=f.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(f.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===d&&k?e({...t,scope:"global"},n,r):{parsed:o,server:l,name:p,scope:d,projectMode:s,...k?{projectBlock:k}:{},values:h,pasteSecrets:m,secretReferences:g,fill:f,fieldProblems:x,secretPaths:b,preview:v,...i?{submitBlock:i}:{},trustFolder:"project"===d&&"trust-and-write"===s.kind}})(s,t,n),[s,t,n]),f=(0,i.useMemo)(()=>(function(e){let t=ub(e,{rawPi:!0});if(!t.ok)return!1;let n=ub(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(s.text),[s.text]),{parsed:x,server:b,preview:v,projectBlock:y,submitBlock:k}=g,j=b?[...b.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!g.pasteSecrets.includes(String(e.params?.field))):[],w=void 0!==s.name&&s.name!==b?.name?[]:j.filter(e=>u6.has(e.code)),S=j.filter(e=>!u6.has(e.code)),C=!a&&!o&&void 0===k,N=()=>{C&&c(uX(s,g))},I=e=>d({...s,...e}),$=t.files.find(e=>e.scope===g.scope)?.path??("project"===g.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),E=k&&(""!==s.text.trim()||"mcp-off"===k.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:oV(e.name),path:e.path?u2(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(oV).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(oV).join(", ")});case"config-invalid":return uP(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return uQ(e.block,t,u2)}}(k,p,b?.fields):void 0,T=y?.kind==="project-untrusted"&&y.trustable&&u,M=v?"http"===v.transport?v.headerNames:v.envNames:[];return(0,r.jsxs)(ag,{title:p("mcp.add.title"),catalogs:u8,target:(0,r.jsxs)(ah,{value:g.scope,label:p("config.saveTo"),options:[{value:"global",label:u4("global",p)},{value:"project",label:u4("project",p),disabled:void 0!==y&&"project"!==g.scope}],path:u2($),disabledReason:y?uQ(y,p,u2):null,onChange:e=>I({scope:e}),children:[T&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{size:"small",onClick:u,children:p("mcp.trust.trustButton")})}),g.trustFolder&&"trust-and-write"===g.projectMode.kind&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:u2(g.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:s.text,canSubmit:C,onValueChange:e=>d(uA(s,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===s.text.trim()?uD.map(e=>{let{source:t,text:n}=e;return{label:p(uO[t]),value:n}}):[],multiline:!0,children:[f&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:s.rawPi,onChange:e=>d(uA(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)(u3,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,r.jsxs)(al,{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(b??x.servers[0])),onChange:e=>I({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,r.jsx)("option",{value:t,children:oV(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})})]}),b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(al,{label:p("config.name"),children:(0,r.jsx)("input",{id:m,className:"mcp-add-input","aria-label":p("config.name"),value:g.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>I({name:e.target.value})})}),(0,r.jsx)(u3,{notes:w,fields:b.fields}),k?.kind==="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{size:"small",onClick:()=>I({name:k.suggestedName}),children:p("mcp.add.useName",{name:oV(k.suggestedName)})})})]}),b&&v&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ao,{children:p("mcp.add.preview")}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:p("mcp.add.readAs"),children:p(uO[v.source])}),(0,r.jsx)(ac,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${v.transport}`)}),(0,r.jsx)(ac,{label:"http"===v.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:v.target}),"stdio"===v.transport&&void 0!==v.cwd&&(0,r.jsx)(ac,{label:p("mcp.detail.cwd"),mono:!0,children:v.cwd}),M.length>0&&(0,r.jsx)(ac,{label:"http"===v.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,r.jsx)(u7,{names:M})}),v.commandFields.length>0&&(0,r.jsx)(ac,{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:v.commandFields.map(e=>{let t=o0(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),v.variableReferences.length>0&&(0,r.jsx)(ac,{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"===v.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,r.jsx)("span",{className:"mcp-config-chips",children:o4(v.variableReferences).map(e=>{let{variable:t,field:n}=e,i=o0(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:oV(t),field:p(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[v.unfilled&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),v.masked&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,r.jsx)(u3,{notes:S,fields:b.fields}),b.fields.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ao,{children:p("mcp.add.fields")}),b.fields.map(e=>{var t;let n;return(0,r.jsx)(pe,{field:e,fields:b.fields,draft:s,suggestedName:(t=g.name,(n=e.targets[0])?uK(d_(n.path),t):void 0),problem:g.fieldProblems[e.id],onDraftChange:d},e.id)})]}),g.pasteSecrets.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ao,{children:p("mcp.add.secrets")}),g.pasteSecrets.map(e=>{var t,n;let i;return(0,r.jsx)(pt,{label:e,draft:s,suggestedName:uK(e,g.name),stored:g.fill?.ok?(t=g.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(8)]:void 0:n.startsWith("env.")&&"command"in t?t.env?.[n.slice(4)]:void 0)&&dl(i)?i:void 0):void 0,problem:g.fieldProblems[e],onDraftChange:d},e)})]})]}),(0,r.jsx)(aj,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":a||void 0,"aria-describedby":E?h:void 0,onClick:N,children:a?p("mcp.add.adding"):g.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),E&&(0,r.jsx)("p",{id:h,className:`mcp-config-line ${k?.kind==="scope"?"is-warning":"is-dim"}`,children:E}),b&&!k&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),l&&(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(u1[e.breadth.kind],{path:u2(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(uZ)?"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:oV(e.name),path:e.path?u2(e.path):"mcp.json"});let n=e.reason?u5[e.reason]:void 0;return n?t(n,{error:oV(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):oV(e.error)}(l,p)]}),l.trustKept&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:u2(l.trust?.decisionPath??n??"")})}),l.notes&&l.notes.length>0&&(0,r.jsx)(u3,{notes:l.notes,fields:b?.fields}),"name-taken"===l.reason&&l.suggestedName&&k?.kind!=="name-taken"&&(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{size:"small",onClick:()=>I({name:l.suggestedName}),children:p("mcp.add.useName",{name:oV(l.suggestedName)})})}),"host-env-confirm"===l.reason&&l.names&&l.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:l.names.map(oV).join(", ")})}),(0,r.jsx)("span",{className:"mcp-config-line",children:(0,r.jsx)(aj,{variant:"danger",size:"small",disabled:a||o||void 0!==k,onClick:()=>c(uX(s,g,l.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function u7(e){let{names:t}=e,{t:n}=(0,eX.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:oV(e)},e))}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function pe(e){let t,{field:n,fields:s,draft:a,suggestedName:o,problem:l,onDraftChange:d}=e,{t:c}=(0,eX.s)(),u=(0,i.useId)(),p=l?{"aria-invalid":!0,"aria-describedby":u}:{},h=u_(n),m=h?a.references[n.id]:void 0,g=void 0!==m,f=oV(n.label),x=a.values[n.id]??n.defaultValue??"",b=uz[n.reason],v=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=g?m&&!l?uB(n,s,"${"+m+"}",!0):void 0:uB(n,s,`‹${c("mcp.add.field.slot")}›`),k=e=>d({...a,values:{...a.values,[n.id]:e}}),j=e=>{let t={...a.references};void 0===e?delete t[n.id]:t[n.id]=e,d({...a,references:t})};return(0,r.jsxs)("div",{className:"mcp-add-field",children:[(0,r.jsx)(al,{label:f,children:g?(0,r.jsx)("input",{className:"mcp-add-input","aria-label":c("mcp.add.field.variableName",{field:f}),value:m,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":f,value:x,...p,onChange:e=>k(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:oV(e)},e))]}):(0,r.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":f,value:x,autoComplete:"off",placeholder:n.placeholder?oV(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>k(e.target.value)})}),l&&(0,r.jsx)("span",{id:u,className:"mcp-config-line is-error",children:uP(l,c,[n])}),(0,r.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:oV(n.description)}),b&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:c(b)}),g?(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:v?c("mcp.add.field.optionalHeader",{name:oV(v)}):c("mcp.add.field.optional")})]})]}),h&&(0,r.jsxs)("label",{className:"mcp-add-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:g,onChange:e=>j(e.target.checked?o??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:c("mcp.add.field.useVariable")})]})]})}function pt(e){let{label:t,draft:n,suggestedName:s,stored:a,problem:o,onDraftChange:l}=e,{t:d}=(0,eX.s)(),c=(0,i.useId)(),u=n.secretReferences[t],p=void 0!==u,h=oV(t),m=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,l({...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=>m(e.target.checked?s??"":void 0)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.add.field.useVariable")})]}),p&&(0,r.jsx)(al,{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=>m(e.target.value)})}),o&&(0,r.jsx)("span",{id:c,className:"mcp-config-line is-error",children:uP(o,d)}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==a?d("mcp.add.secret.storedAs",{value:oV(a)}):d("mcp.add.field.variableHint"):d("mcp.add.secret.asPasted")})]})}let pn=new Set(["done","failed","cancelled","expired"]);function pr(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!pn.has(t))}let pi={"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"},ps={"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"},pa={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},po={"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 pl(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,pn.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function pd(e){return"sign-in-unknown"===e.reason}async function pc(e,t,n,r){var i;let s,a;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{a=await s.json()}catch{return{ok:!1,error:{error:`HTTP ${s.status}`}}}return s.ok&&null!==(i=a)&&"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:a}:{ok:!1,error:lN(a,s.status)}}function pu(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=t.method??"GET";return lI(r=>pc(e,t,n,r),()=>({ok:!1,error:{error:`${a} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function pp(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function ph(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?ps[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pm(e){let{server:t,run:n,block:s,signOutBlock:a,controlsBusy:o,signingOut:l,onSignIn:d,onSignOut:c,onPaste:u,onCancel:p}=e,{t:h}=(0,eX.s)(),m=(0,i.useId)(),g=(0,i.useId)(),f=(0,i.useId)(),x=(0,i.useRef)(null),b=(0,i.useRef)(null),v=pr(n),y=(0,i.useRef)(v);if((0,i.useEffect)(()=>{let e=y.current;y.current=v,!e&&v?e$(document,b.current):e&&!v&&e$(document,x.current)},[v]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,r.jsx)(ac,{label:h("mcp.detail.signIn"),children:void 0!==t.authProvider?h("mcp.signIn.provider",{provider:oV(t.authProvider)}):h("mcp.signIn.header")});let k=n?.flow,j=n?.starting===!0,w=void 0!==k&&(k.scope!==t.scope||k.name!==t.name),S=(t.oauthStateStored??t.signedIn)!==!1,C=j||l||void 0!==s,N=o||j||void 0!==a,I=k?.phase==="finishing";return(0,r.jsx)(ac,{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")}),k&&v&&w&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.shared",{name:oV(k.name)})}),k&&v&&("authorize"===k.phase?(0,r.jsx)(pg,{flow:k,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>u(t,k.flowId,e)},k.flowId):(0,r.jsx)("span",{role:"status",className:"mcp-config-line",children:h(pa[k.phase]??"mcp.signIn.phase.connecting")})),k&&v&&I&&(0,r.jsx)("span",{id:f,className:"mcp-config-line is-dim",children:h("mcp.signIn.phase.noCancel")}),k&&!v&&!n?.gone&&(0,r.jsx)(pf,{flow:k,shared:w}),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")," ",ph(n.error,h)]}),v&&n?.cancelError&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[h("mcp.signIn.cancelFailed")," ",ph(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")," ",ph(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:m,className:"mcp-config-line is-dim",children:h(pi[s])}),!s&&a&&S&&!v&&(0,r.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:h(pi[a])}),(0,r.jsxs)("div",{className:"mcp-sign-in-actions",children:[v&&k?(0,r.jsx)(aj,{ref:b,size:"small",disabled:n?.cancelling===!0||I,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":I?f:void 0,onClick:()=>p(t,k.flowId),children:h(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,r.jsx)(aj,{ref:x,size:"small",variant:"primary",disabled:C,"aria-busy":j||void 0,"aria-describedby":s?m:void 0,onClick:()=>d(t),children:h(j?"mcp.signIn.starting":"mcp.signIn.button")}),S&&!v&&(0,r.jsx)(aj,{size:"small",disabled:N,"aria-busy":l||void 0,"aria-describedby":a?s?m:g:void 0,onClick:()=>c(t),children:h(l?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!s&&!v&&S&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.replaces")}),S&&!a&&!v&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:h("mcp.signIn.signOutExplain")})]})})}function pg(e){let{flow:t,pasting:n,pasteError:s,onPaste:a}=e,{t:o}=(0,eX.s)(),[l,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&&e$(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)(aO,{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:oV(p)})]}):(0,r.jsxs)(r.Fragment,{children:[o("mcp.signIn.authorize.notALink")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oV(t.authorizationUrl??"")})]}),value:l,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:()=>a(l)}),s&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.signIn.paste.refused")," ",ph(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:oV(s.error)})]})]}),t.redirectUrl&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.redirect",{url:oV(t.redirectUrl)})}),(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.signIn.authorize.wait")})]})}function pf(e){let{flow:t,shared:n}=e,{t:i}=(0,eX.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 po[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!s)return null;let a=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"===a?"mcp-config-line is-error":"warning"===a?"mcp-config-line is-warning":"mcp-config-line",children:i(s,{name:oV(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:oV(t.error)})]})]})}function px(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function pb(e){return oV(ep(e))}function pv(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:pb(r.path)}):t(n)}function py(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function pk(e,t){return e.timedOut?t("mcp.actionTimedOut"):py(e,t)}function pj(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function pw(e){let{cwd:t,onClose:n,embedded:s=!1,trust:a,onTrustProject:o,onProjectTrustChanged:l}=e,[d,c]=(0,i.useState)({state:"loading"}),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(()=>sC("mcp",t)),[g,f]=(0,i.useState)({saving:!1,error:null}),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[I,$]=(0,i.useState)({}),E=(0,i.useRef)(0),T=(0,i.useRef)(null),M=(0,i.useRef)(null),R=(0,i.useRef)(null),A=(0,i.useRef)(new Map),[L,P]=(0,i.useState)({}),z=(0,i.useRef)(L);z.current=L;let[O,W]=(0,i.useState)(0),[F,D]=(0,i.useState)(!1),[B,_]=(0,i.useState)(uM),H=(0,i.useRef)(B);H.current=B;let[U,q]=(0,i.useState)(null),[K,Z]=(0,i.useState)(null),V=(0,i.useRef)(!0),J=(0,i.useRef)(d);J.current=d;let G=(0,i.useCallback)(async()=>{let e=++E.current;T.current?.abort();let n=new AbortController;T.current=n,p(!0);let r=await lR(t,void 0,n.signal);if(e===E.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}:{}}),m(e=>lx(lg(r.data,!!t),e))}},[t]),Y=ou(a);(0,i.useEffect)(()=>(G(),()=>{E.current+=1,T.current?.abort()}),[G,Y]);let X=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"preference"});let n=await lP(e,void 0,t.signal);M.current===t&&(M.current=null,f({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}),G())},[G]),Q=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"mode"});let n=await lz(e,void 0,t.signal);M.current===t&&(M.current=null,f({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),G())},[G]),ee=(0,i.useCallback)(async e=>{let t=new AbortController;M.current=t,f({saving:!0,error:null,target:"inlineBudget"});let n=await lO(e,void 0,t.signal);M.current===t&&(M.current=null,f({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),G())},[G]);(0,i.useEffect)(()=>{let e=A.current;return V.current=!0,()=>{V.current=!1,M.current?.abort(),M.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,i.useCallback)(async e=>{let n=o3(e);if(A.current.has(n))return;let r={};A.current.set(n,r),$(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,a=await lQ({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),$(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],a,e.configKey)}));let o=J.current,l="loaded"===o.state?o.data.servers.find(e=>o3(e)===n):void 0;(a.ok?l?.configKey===a.data.configKey:void 0===a.error.reason||a.error.timedOut)||G()},[t,G]),en=(0,i.useCallback)((e,n)=>{E.current+=1,T.current?.abort(),p(!1),c(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),m(r=>lx(lg(e,!!t),n??r))},[t]),er=(0,i.useCallback)(async e=>{let n=o3(e),r=z.current[n];if(r?.starting||pr(r))return;P(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,a=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 pu("/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);V.current&&(P(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?pl({},e.data,t):{error:e.error}}(a)})),a.ok||void 0===a.error.reason||a.error.timedOut||G())},[t,G]),ei=(0,i.useCallback)(async(e,t,n)=>{let r=o3(e);P(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 pu(pp(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);V.current&&P(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?{...pl(i,n.data,r),pasteError:void 0}:pd(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=o3(e);P(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 pu(pp(e),{method:"DELETE"},t,n,r)}(t);V.current&&P(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?pl(i,n.data,r):pd(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),ea=Object.entries(L).flatMap(e=>{let[t,n]=e;return pr(n)&&n.flow?[`${t}\x01${n.flow.flowId}`]:[]}).join("\x02");(0,i.useEffect)(()=>{if(!ea)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of ea.split("\x02")){let[n,r]=t.split("\x01"),i=z.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 pu(pp(e),{},t,n,r)}(r,void 0,e.signal);if(e.signal.aborted)return;P(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?pl(e,n.data,r):pd(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}})}W(e=>e+1)},1e3);return()=>{clearTimeout(t),e.abort()}},[ea,O]);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],pr(n)&&!pr(r)})&&G()},[L,G]);let el=(0,i.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,b(n);let s=J.current,a="loaded"===s.state&&s.data.project?t:null,o=await lU(e,a,void 0,i.signal);if(R.current===i)return R.current=null,b(null),o.ok?en(o.data,r?.(o.data)):G(),o},[en,t,G]),ed=(0,i.useCallback)(async(e,t)=>{let n=o3(e),r=pj();y(null),j(null);let i=await el({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),ec=(0,i.useCallback)(async(e,t)=>{let n=o3(e),r=pj();y(null),j(null);let i=await el({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[el]),eu=(0,i.useCallback)(async(e,t)=>{let n=o3(e),r=pj();y(null),j(null);let i=await el({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}))},[el]),ep=(0,i.useCallback)(async e=>{let t=o3(e),n=pj();y(null),j(null);let r=await el({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})},[el]),eh=(0,i.useCallback)(async()=>{if(!w)return;let e=pj();y(null),j(null),S({...w,undoing:!0,error:void 0});let t=await el({action:"undo",token:w.token},"undo",e=>e.restored?o3(e.restored):void 0);t&&(S(e=>e?.token!==w.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[el,w]),em=(0,i.useCallback)(async e=>{let t=o3(e),n=pj();y(null),j(null),P(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await el({action:"sign-out",scope:e.scope,name:e.name},`sign-out:${t}`);if(r){if(P(e=>({...e,[t]:r.ok?{signedOut:{removed:r.data.signedOut?.removed===!0}}:{...e[t],signOutError:r.error}})),r.ok){let e=Date.now();$(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})}},[el]),eg=(0,i.useCallback)(async e=>{let n=pj(),r=H.current;y(null),j(null),q(null);let i=await el(e,"add",e=>e.added?o3(e.added):void 0);if(!i)return;let s=H.current!==r;if(!i.ok){s||q(i.error),i.error.trust&&t&&l?.(t,i.error.trust),N({control:n});return}let{added:a,trust:o,trustedFolder:d}=i.data;if(D(!1),s||_(uM),N({control:null,toSelectedRow:!0}),!a)return;Z({...a,key:o3(a),...d&&t?{trustedFolder:t}:{}}),o&&t&&l?.(t,o);let c=i.data.servers.find(e=>o3(e)===o3(a));c&&!lK(c,i.data)&&et(c)},[t,l,el,et]),ef=w?.token,ex=w?.expiresInMs;(0,i.useEffect)(()=>{if(void 0===ef||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===ef?null:e),ex);return()=>clearTimeout(e)},[ef,ex]);let eb=(0,i.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:oc(t,n,e=>e.enabled).filter(n?l_:lB),keptOff:n?t.filter(e=>!e.enabled&&lB(e)&&!l_(e)).length:0},s=pj();if(y(null),j(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let a=await el({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!a)return;if(N({control:s}),!a.ok)return void j({scope:e,keptOff:i,failures:[],total:r.length,error:a.error});let o=a.data.results??[],l=o.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));j(l.length>0||i>0?{scope:e,keptOff:i,failures:l,total:o.length}:null)},[el]);return(0,i.useEffect)(()=>{h&&sN("mcp",h,t)},[t,h]),(0,r.jsx)(pS,{cwd:t,load:d,selected:h,refreshing:u,embedded:s,codemodeSave:g,busy:x,actionError:v,groupStatus:k,undo:w,focusBack:C,tests:I,signIns:L,adding:F,addDraft:B,addFailure:U,added:K,onAddOpen:()=>{D(!0),Z(null),y(null)},onAddDraftChange:e=>{H.current=e,_(e),q(null)},onAddSubmit:e=>void eg(e),onTest:e=>void et(e),onSignIn:e=>void er(e),onSignOut:e=>void em(e),onSignInPaste:(e,t,n)=>void ei(e,t,n),onSignInCancel:(e,t)=>void es(e,t),onSelect:e=>{m(e),y(null),D(!1),Z(t=>t?.key===e?t:null)},onRefresh:()=>void G(),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 eb(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:o,onClose:n})}function pS(e){var t,n,s,a;let o,l,d,{cwd:c,load:u,selected:p,refreshing:h,embedded:m,codemodeSave:g={saving:!1,error:null},busy:f=null,actionError:x=null,groupStatus:b=null,undo:v=null,focusBack:y=null,tests:k={},signIns:j={},adding:w=!1,addDraft:S=uM,addFailure:C=null,added:N=null,onAddOpen:I=()=>{},onAddDraftChange:$=()=>{},onAddSubmit:E=()=>{},onSelect:T,onRefresh:M,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:P=()=>{},onServerSwitchInProject:z=()=>{},onExposureChange:O=()=>{},onGroupSwitch:W=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:B=()=>{},onSignIn:_=()=>{},onSignOut:H=()=>{},onSignInPaste:U=()=>{},onSignInCancel:q=()=>{},onTrustProject:K,onClose:Z}=e,{t:V}=(0,eX.s)(),J=(0,i.useId)(),G=(0,i.useId)(),Y="loaded"===u.state?(t=u.data,o=!1,l=t.servers.map(e=>{var t;let n=k[o3(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:l}:t):void 0,X=Y?lg(Y,!!c):[],Q=Y?{mcpAvailable:Y.mcp.available,projectServersLoad:o5(Y.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>o3(e)===p),en=N?ee.find(e=>o3(e)===N.key):void 0,er=Y?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"}}(Y.mcp):void 0,ei=er?void 0:Y?.hostInactive,es=Y?.files.find(e=>"project"===e.scope),ea=Y?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"}}(Y.project,es):void 0,eo=K&&lb(Y?.project)?K:void 0,el=ea?.kind==="untrusted"&&void 0!==eo,ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(el);(0,i.useEffect)(()=>{let e=eu.current;eu.current=el,e&&!el&&e$(document,ed.current??ec.current)},[el]);let eh=(0,i.useRef)(null),em=v?.token,eg=(0,i.useRef)(em);(0,i.useEffect)(()=>{let e=eg.current;eg.current=em,void 0!==em&&em!==e?e$(document,eh.current):void 0!==e&&void 0===em&&e$(document,ed.current??ec.current)},[em]);let ef=Y?[...Y.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],ex=lf(ee),eb=Y?.files.find(e=>"global"===e.scope),ev=Y?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&o5(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}}(Y):void 0,ey=Y?(n=ee.length,s=Y.files,n>0?"mcp.selectItem":s.some(e=>e.problems.some(lm))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ek=null!==f||h||g.saving,ej=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y&&!ek&&ej.current!==y)if(ej.current=y,y.toSelectedRow)e$(document,ed.current??ec.current);else{var e,t,n;e=document,t=y.control,n=ed.current??ec.current,t&&e$(e,t.isConnected&&!t.disabled?t:n)}},[y,ek]);let ew=e=>Y?lF(e,Y):void 0,eS=!!Y&&lW(Y.mcp),eC=X.find(e=>"project"===e.scope)?.servers??[],eN=ew("project"),eI=ea?.kind==="untrusted"?[pv(ea,V),eN&&"mcp-off"!==eN&&eC.length>0?V(lD[eN]):null].filter(Boolean).join(" "):"";return(0,r.jsxs)(sQ,{embedded:m,title:V("settings.mcp"),subtitle:c?ep(c):void 0,closeLabel:V("i18n.close"),onClose:Z,children:[(0,r.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,r.jsxs)(af,{id:J,children:[pv(er,V),eS&&(0,r.jsxs)(r.Fragment,{children:[" ",V(lD["mcp-off"])]}),Y&&!Y.mcp.available&&Y.mcp.detail&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oV(Y.mcp.detail)})]})]}),ei&&(0,r.jsx)(af,{children:V("mcp.hostInactive",{path:pb(ei.cwd),owner:pb(ei.owner)})}),"loaded"===u.state&&u.projectError&&(0,r.jsx)(af,{children:V("mcp.projectNotListed",{reason:py(u.projectError,V)})}),ea?.kind==="untrusted"&&(0,r.jsx)(ax,{id:G,message:eI,trustLabel:V("mcp.trust.trustButton"),onTrust:eo}),ea?.kind==="inherited"&&(0,r.jsx)(af,{children:pv(ea,V)}),v&&(0,r.jsxs)(af,{action:v.error?.reason==="undo-unavailable"?void 0:(0,r.jsx)(aj,{ref:eh,size:"small",onClick:D,disabled:v.undoing||ek,children:v.undoing?V("mcp.undoing"):V("mcp.undo")}),children:[V("mcp.removed",{name:oV(v.name),path:pb(v.path)}),v.error&&(0,r.jsxs)(r.Fragment,{children:[" ",V("mcp.undoFailed")," ",pk(v.error,V)]})]}),N&&Y&&en&&(0,r.jsx)(pC,{added:N,cwd:c,server:en,testing:k[N.key]?.running===!0,signIn:j[N.key],signingOut:f===`sign-out:${N.key}`,signInBlock:en?lK(en,Y):void 0,onSignIn:_})]}),(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:"loading"===u.state?(0,r.jsx)("div",{className:"config-sidebar-message",children:V("i18n.loading")}):"failed"===u.state?(0,r.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[V("mcp.loadFailed")," ",py(u.error,V)]}):Y&&Q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"config-sidebar-group",children:(0,r.jsx)(pN,{codemode:Y.codemode,active:!w&&p===o6,rowRef:ed,onSelect:T})}),X.map(e=>{let t=ew(e.scope);return(0,r.jsx)(pI,{group:e,context:Q,selected:w?null:p,selectedRowRef:ed,block:t,blockNoticeId:"mcp-off"===t?er?J:void 0:t&&ea?.kind==="untrusted"?G:void 0,busy:f,controlsBusy:ek,status:b?.scope===e.scope?b:null,onSelect:T,onGroupSwitch:W},e.scope)})]}):null}),Y&&(0,r.jsx)(aS,{ref:ec,active:w,onClick:I,children:V("mcp.add.action")})]}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:Y&&Q&&ev&&ey?w?(0,r.jsx)(u9,{data:Y,cwd:c,draft:S,busy:"add"===f,controlsBusy:ek,failure:C,onDraftChange:$,onSubmit:E,onTrustProject:eo}):p===o6?(0,r.jsx)(pF,{codemode:Y.codemode,autoEnable:ev,save:g,serverBusy:null!==f,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,r.jsx)(pT,{server:et,context:Q,codemode:Y.codemode,toolSearchDisabled:Y.toolSearchDisabled,autoEnable:ev,block:ew(et.scope),inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!o5(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:o3(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,Y),inProjectBlock:ew("project"),savedWhileOff:!Y.mcp.available&&!eS,busy:f,controlsBusy:ek,actionError:x?.key===o3(et)?x.failure:null,test:(a=k[o3(et)],a&&void 0!==a.configKey&&a.configKey!==et.configKey?{running:a.running,...a.response?{response:a.response}:{}}:a),testBlock:lK(et,Y),signIn:j[o3(et)],signInBlock:lK(et,Y),signOutBlock:(d=lF(et.scope,Y))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:P,onSwitchInProject:z,onShowServer:e=>{T(e),requestAnimationFrame(()=>e$(document,ed.current??ec.current))},onExposureChange:O,onRemove:F,onTest:B,onSignIn:_,onSignOut:H,onSignInPaste:U,onSignInCancel:q},o3(et)):(0,r.jsx)(ab,{children:"mcp.empty"===ey?V(ey,{globalPath:pb(eb?.path??"~/.pi/agent/mcp.json")}):V(ey)}):null})})]}),(0,r.jsxs)(ay,{status:ef.length>0?(0,r.jsx)(ak,{tone:ef.some(e=>{let{problem:t}=e;return lm(t)})?"error":"warning",summary:1===ef.length?V("mcp.footer.fileProblem"):V("mcp.footer.fileProblems",{count:ef.length}),details:ef.map(e=>{let{file:t,problem:n}=e,i=o8(n,t.realPath);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("code",{className:"mcp-config-chip",children:pb(t.path)})," ",V(`mcp.fileProblem.${n.reason}`),i&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("code",{className:"mcp-config-chip",children:i})]})]})})}):(0,r.jsx)(ak,{summary:ex.total>0?V("mcp.serverCount",{enabled:ex.enabled,total:ex.total}):""}),children:[!m&&(0,r.jsx)(aj,{onClick:Z,children:V("i18n.close")}),(0,r.jsx)(aj,{variant:"secondary",onClick:M,disabled:ek,children:V("i18n.refresh")})]})]})}function pC(e){let{added:t,cwd:n,server:i,testing:s,signIn:a,signingOut:o,signInBlock:l,onSignIn:d}=e,{t:c}=(0,eX.s)(),u=oV(t.name),p="project"===t.scope&&n?oV(eh(t.path,n)):pb(t.path),h=i.status,m=!s&&h?.origin==="test"&&"needs-auth"===h.state&&i.usesOAuth,g=a?.starting===!0||pr(a);return(0,r.jsxs)(af,{action:!m||g||o||l?void 0:(0,r.jsx)(aj,{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:pb(t.trustedFolder)}),s&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.testing")]}),m&&(0,r.jsxs)(r.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function pN(e){let{codemode:t,active:n,rowRef:i,onSelect:s}=e,{t:a}=(0,eX.s)(),o=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",l=a(lw[o]);return(0,r.jsxs)(ae,{ref:n?i:void 0,active:n,"aria-label":a("mcp.codemode.rowLabel",{state:l}),onClick:()=>s(o6),children:[(0,r.jsx)(aC,{...la(lS(o))}),(0,r.jsx)(at,{className:"is-grow",children:a("mcp.codemode.title")}),(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${lS(o)}`,children:l})]})}function pI(e){var t;let n,i,{group:s,context:a,selected:o,selectedRowRef:l,block:d,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:m,onGroupSwitch:g}=e,{t:f}=(0,eX.s)(),{enabled:x,total:b}=lf(s.servers),v=(t=s.servers).some(e=>e.enabled&&lB(e))&&t.every(e=>e.enabled||!l_(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(lm)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(s),k=h?(n=h.keptOff>0?f("mcp.groupKeptOff",{count:h.keptOff}):void 0,i=h.error?`${f("mcp.actionFailed")} ${pk(h.error,f)}`:h.failures.length>0?[f("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${oV(t)}: ${pk(n,f)}`})].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)(s5,{aside:b>0?(0,r.jsx)(s9,{enabled:x,total:b,checked:v,disabled:p||void 0!==d,loading:u===`group:${s.scope}`,describedBy:d?c:void 0,label:f(v?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:px(s.scope,f)}),onChange:e=>g(s.scope,s.servers,e)}):void 0,children:px(s.scope,f)}),k&&(0,r.jsx)(s7,{note:k.note,error:k.error}),y&&(0,r.jsx)("div",{className:"mcp-sidebar-group-empty",children:f(y)}),s.servers.map(e=>{let t=o3(e),n=o7(e,a),i=ls(n),s=li[n],d=oV(e.name);return(0,r.jsxs)(ae,{ref:o===t?l:void 0,active:o===t,"aria-label":f("mcp.rowLabel",{name:d,state:f(ln(n,e.status))}),onClick:()=>m(t),children:[(0,r.jsx)(aC,{...la(i)}),(0,r.jsx)(at,{className:`is-grow${"on"===i?"":" is-muted"}`,children:d}),s&&(0,r.jsx)("span",{className:`mcp-sidebar-badge is-${i}`,children:f(s)})]},t)})]})}function p$(e){let{fields:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=o0(e);return(0,r.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function pE(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:oV(e)},e))})}function pT(e){let{server:t,context:n,codemode:s,toolSearchDisabled:a,autoEnable:o,block:l,inProject:d,inProjectBlock:c,savedWhileOff:u,busy:p,controlsBusy:h,actionError:m,test:g,testBlock:f,signIn:x,signInBlock:b,signOutBlock:v,onSwitch:y,onSwitchInProject:k,onShowServer:j,onExposureChange:w,onRemove:S,onTest:C,onSignIn:N,onSignOut:I,onSignInPaste:$,onSignInCancel:E}=e,{t:T}=(0,eX.s)(),M=(0,i.useId)(),R=(0,i.useId)(),A=o7(t,n),L=oX(t),P=t.status,z=P?.origin==="test"&&"connected"===P.state&&P.toolCount>0?P:void 0,O=void 0===t.invalidError,W="http"===t.transport||void 0===t.transport&&void 0!==t.url,F=!W&&("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"===lv(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:a},o):void 0,B=(0,i.useId)(),_=(0,i.useId)(),H=o3(t),U=oV(t.name),q=!t.enabled&&void 0!==t.webPasswordField,K=!0===t.notAnObject,Z=l?T(`mcp.reason.${l}`):K?T("mcp.reason.entry-not-object"):q?T("mcp.reason.web-password"):u?T("mcp.write.savedWhileOff"):void 0;return(0,r.jsxs)(an,{children:[(0,r.jsxs)("div",{className:"config-detail-heading",children:[(0,r.jsxs)(ar,{children:[(0,r.jsxs)(ai,{children:[(0,r.jsx)(au,{scope:t.scope,children:px(t.scope,T)}),(0,r.jsx)(aa,{children:U})]}),(0,r.jsxs)(as,{children:[(0,r.jsx)(pO,{server:t,test:g,testBlock:f,describedBy:R,onTest:C}),(0,r.jsx)(aj,{variant:"danger",size:"small",disabled:h||void 0!==l,"aria-describedby":l?M:void 0,onClick:()=>S(t),children:p===`remove:${H}`?T("i18n.removing"):T("i18n.remove")}),(0,r.jsx)(aw,{checked:t.enabled,disabled:h||void 0!==l||K||q,loading:p===`switch:${H}`,describedBy:Z?M:void 0,label:T(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:U}),onChange:e=>y(t,e)})]})]}),Z&&(0,r.jsx)("div",{id:M,className:"config-detail-heading-note",children:Z})]}),m&&(0,r.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[T("mcp.actionFailed")," ",pk(m,T)]}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(pW,{server:t,state:A,test:g,testBlock:f,testBlockId:R}),void 0!==t.description&&(0,r.jsx)(ac,{label:T("mcp.detail.description"),tone:"plain",children:oV(t.description)}),void 0!==L?(0,r.jsx)(ac,{label:W?T("mcp.detail.url"):T("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:L}):t.transport&&(0,r.jsx)(ac,{label:T("mcp.detail.transport"),children:T(`mcp.transport.${t.transport}`)}),F&&void 0!==t.cwd&&(0,r.jsx)(ac,{label:T("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:oV(t.cwd)}),F&&t.envNames.length>0&&(0,r.jsx)(ac,{label:T("mcp.detail.env"),children:(0,r.jsx)(pE,{names:t.envNames})}),W&&t.headerNames.length>0&&(0,r.jsx)(ac,{label:T("mcp.detail.headers"),children:(0,r.jsx)(pE,{names:t.headerNames})}),O&&t.commandFields.length>0&&(0,r.jsx)(ac,{label:T("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:T("mcp.server.commandFields")}),(0,r.jsx)(p$,{fields:t.commandFields})]})}),O&&t.variableReferences.length>0&&(0,r.jsx)(ac,{label:T("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:T(o1(t))}),(0,r.jsx)("span",{className:"mcp-config-chips",children:o4(t.variableReferences).map(e=>{let{variable:t,field:n}=e,i=o0(n);return(0,r.jsx)("code",{className:"mcp-config-chip",children:T("mcp.server.variableIn",{variable:t,field:T(i.key,i.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),W&&O&&(0,r.jsx)(pm,{server:t,run:x,block:b,signOutBlock:v,controlsBusy:h,signingOut:p===`sign-out:${H}`,onSignIn:N,onSignOut:I,onPaste:$,onCancel:E}),(t.exposure||z)&&(0,r.jsx)(ac,{label:T("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":T("mcp.exposure.label",{name:U}),"aria-describedby":[B,l?M:null].filter(Boolean).join(" "),value:t.exposure,disabled:h||void 0!==l,onChange:e=>{let n=e.target.value;n!==t.exposure&&w(t,n)},children:lp.map(e=>(0,r.jsx)("option",{value:e,children:"codemode"===e?T("mcp.exposure.optionDefault",{label:T(lh[e])}):T(lh[e])},e))}),p===`exposure:${H}`&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:T("i18n.saving")})]}),(0,r.jsx)("span",{id:B,className:"mcp-config-line",children:T(lu[t.exposure])}),void 0!==t.toolExposureCount&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:T("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),D&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(D,T)})]}),z&&(0,r.jsx)(pz,{status:z,serverExposure:t.exposure})]})}),d&&(0,r.jsx)(ac,{label:T("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?T("mcp.inProject.overridden",{keys:d.keys.join(", ")}):T("mcp.inProject.refused")}),(0,r.jsx)("span",{children:(0,r.jsx)(aj,{size:"small",onClick:()=>j(d.key),children:T("mcp.inProject.show")})})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:(0,r.jsx)(aj,{size:"small",disabled:h||void 0!==c||q,"aria-describedby":[_,c||q?M:null].filter(Boolean).join(" "),onClick:()=>k(t,!t.enabled),children:p===`in-project:${H}`?T("i18n.saving"):T(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,r.jsx)("span",{id:_,className:"mcp-config-line is-dim",children:T("mcp.inProject.saved")})]})})}),(0,r.jsx)(ac,{label:T("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:pb(t.sourcePath)})]}),(0,r.jsxs)("div",{className:"mcp-config-lines",children:[oQ(t)&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.hiddenCharacters")}),!t.validated&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.unchecked")}),t.replacesGlobal&&(0,r.jsx)("p",{className:"mcp-config-line is-warning",children:T("mcp.server.replacesGlobal")}),t.override&&(0,r.jsx)("p",{className:"mcp-config-line",children:pv(o2(t.override.keys),T)}),t.shadowedByProject&&"replaced"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==A&&(0,r.jsx)("p",{className:"mcp-config-line",children:T("mcp.server.overriddenByProject")}),t.masked&&(0,r.jsx)("p",{className:"mcp-config-line is-dim",children:T("mcp.server.masked")})]})]})}function pM(e){let{error:t,stderr:n}=e,{t:i}=(0,eX.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:oV(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(oV).join("\n")})]})]})}function pR(e){let{status:t,showState:n,entryCwd:i}=e;return"session"===t.origin?(0,r.jsx)(pP,{status:t,showState:n}):(0,r.jsx)(pL,{status:t,showState:n,entryCwd:i})}function pA(e){let{view:t}=e,{t:n}=(0,eX.s)();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function pL(e){let{status:t,showState:n,entryCwd:i}=e,{t:s,locale:a}=(0,eX.s)(),o=lo(t.testedAt,a),l=t.serverInfo;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(pA,{view:t.timedOut?{key:lV.timedOut,tone:"error"}:{key:lV[t.state],tone:ls(t.state)}}),s((t.afterSignIn?lG:lJ)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:lY(t.durationMs),time:o})]}),(0,r.jsx)(pM,{error:t.error,stderr:t.stderr}),l&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.test.serverInfo",{name:oV(l.title??l.name),version:oV(l.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:pb(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:lY(t.queuedMs)})})]})}function pP(e){let{status:t,showState:n}=e,{t:i,locale:s}=(0,eX.s)(),a=lo(t.updatedAt,s),o=void 0===t.closedAt?void 0:lo(t.closedAt,s);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,r.jsx)(pA,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:ll[t.state],tone:lc[t.state]}}),i(void 0!==t.closedAt?"mcp.session.summary.closed":ld[t.state],{path:pb(t.cwd),time:a,...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:pb(t.conflict)})]}),(0,r.jsx)(pM,{error:t.error,stderr:t.stderr})]})}function pz(e){let{status:t,serverExposure:n}=e,{t:i}=(0,eX.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:oV(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(lh[e.exposure])})]}),e.description&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:oV(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 pO(e){let{server:t,test:n,testBlock:s,describedBy:a,onTest:o}=e,{t:l}=(0,eX.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&&e$(document,d.current)},[c]),(0,r.jsx)(aj,{ref:d,size:"small",disabled:c||void 0!==s,"aria-busy":c||void 0,"aria-describedby":s?a:void 0,onClick:()=>o(t),children:l(c?"mcp.test.testing":"mcp.test.button")})}function pW(e){let{server:t,state:n,test:i,testBlock:s,testBlockId:a}=e,{t:o}=(0,eX.s)(),l=t.status,d=lr[n],c="invalid"===s&&"invalid"===n?"state":"web-password"===s&&void 0!==t.webPasswordField?"password":void 0;return(0,r.jsx)(ac,{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-${ls(n)}`,children:o(ln(n,l))}),"invalid"===n&&(0,r.jsxs)("span",{id:"state"===c?a:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.invalid")," ",(0,r.jsx)("code",{className:"mcp-config-chip",children:oV(t.invalidError??"")})]}),t.webPasswordField&&(0,r.jsxs)("span",{id:"password"===c?a:void 0,className:"mcp-config-line is-warning",children:[o("mcp.server.webPassword")," ",(0,r.jsx)(p$,{fields:[t.webPasswordField]})]}),l?(0,r.jsx)(pR,{status:l,showState:o9(l)!==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?lZ[e.reason]:void 0;return n?t(n):py(e,t)}(i.error,o)]}),s&&!c&&(0,r.jsx)("span",{id:a,className:"mcp-config-line is-dim",children:o(lq[s])}),!s&&t.commandFields.length>0&&(0,r.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.test.serial")})]})})}function pF(e){let{codemode:t,autoEnable:n,save:i,serverBusy:s,onChange:a,onModeChange:o,onInlineBudgetSave:l}=e,{t:d}=(0,eX.s)(),c=t.sandbox,u=t.preference,p=i.saving||s,h=void 0===i.target||"preference"===i.target?i:{saving:!1,error:null},m=function(e,t){if("automatic"===lv(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),g="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,f=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:ly[t.preference],params:{path:t.settingsPath}}}(t);return(0,r.jsxs)(an,{children:[(0,r.jsx)(ar,{children:(0,r.jsx)(ai,{children:(0,r.jsx)(aa,{children:d("mcp.codemode.title")})})}),(0,r.jsx)("p",{className:"mcp-config-line",children:d("mcp.codemode.intro")}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{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)(ap,{value:u,label:d("mcp.codemode.title"),options:[{value:"automatic",label:d(lw.automatic),disabled:p},{value:"always",label:d(lw.always),disabled:p||void 0!==g}],disabledReason:g?pv(g,d):null,onChange:e=>{e!==u&&a(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:oV(t.preferenceError??"")})]}),h.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.saveFailed")," ",(0,r.jsx)(pD,{error:h.error})]}),x&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(x,d)}),m&&(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(m,d)})]})}),t.mode?(0,r.jsx)(pB,{mode:t.mode,codemode:t,save:i,waiting:p,onChange:o}):void 0!==t.modeError&&(0,r.jsx)(ac,{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:oV(t.modeError)})]})}),t.inlineBudget?(0,r.jsx)(p_,{budget:t.inlineBudget,save:i,waiting:p,onSave:l}):void 0!==t.inlineBudgetError&&(0,r.jsx)(ac,{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:oV(t.inlineBudgetError)})]})}),(0,r.jsx)(ac,{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:oV(c.error)})]}):(0,r.jsx)("span",{className:"mcp-config-line",children:d("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),f&&(0,r.jsx)(ac,{label:d("mcp.codemode.builtin"),tone:"error",children:pv(f,d)})]})]})}function pD(e){let{error:t}=e,{t:n}=(0,eX.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:oV(t.error)})}function pB(e){let{mode:t,codemode:n,save:i,waiting:s,onChange:a}=e,{t:o}=(0,eX.s)(),l="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:lj[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===lv(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,r.jsx)(ac,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,r.jsxs)("div",{className:"mcp-config-lines",children:[(0,r.jsx)(ap,{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)&&a(e)},children:l&&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(lk[t.value])}),d.map(e=>(0,r.jsx)("span",{className:"mcp-config-line is-warning",children:pv(e,o)},e.key)),l&&i.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.toolMode.saveFailed")," ",(0,r.jsx)(pD,{error:i.error})]})]})})}function p_(e){let t,n,{budget:s,save:a,waiting:o,onSave:l}=e,{t:d}=(0,eX.s)(),c=(0,i.useRef)(null),u=(0,i.useId)(),p=void 0===s.value?"":String(s.value),[h,m]=(0,i.useState)(p);(0,i.useEffect)(()=>{m(p)},[p]);let g=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),f=!!g.ok&&(null===g.value?void 0!==s.value||void 0!==s.invalid:g.value!==s.value),x="inlineBudget"===a.target,b=x&&a.saving,v=(0,i.useRef)(b);(0,i.useEffect)(()=>{let e=v.current;v.current=b,e&&!b&&e$(document,c.current)},[b]);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)(ac,{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(),g.ok&&f&&!o&&l(g.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":!g.ok||void 0,value:h,placeholder:String(s.default),readOnly:o,autoComplete:"off",spellCheck:!1,onChange:e=>m(e.target.value)}),(0,r.jsx)("span",{className:"mcp-config-line",children:d("mcp.codemode.inlineBudget.unit")}),(0,r.jsx)(aj,{type:"submit",size:"small",disabled:!f||o,children:d("mcp.codemode.inlineBudget.save")}),b&&(0,r.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:d("i18n.saving")})]}),!g.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:pv(e,d)},e.key)),x&&a.error&&(0,r.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[d("mcp.codemode.inlineBudget.saveFailed")," ",(0,r.jsx)(pD,{error:a.error})]})]})})}async function pH(e){let t=await fetch("/api/channels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));return{ok:t.ok,error:n.error}}function pU(e){var t;let n,{embedded:s=!0,onClose:a}=e,{t:o}=(0,eX.s)(),[l,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(""),[m,g]=(0,i.useState)(""),[f,x]=(0,i.useState)(null),[b,v]=(0,i.useState)(null),y=(0,i.useRef)(!1),k=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/channels",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return void u(t.error??`HTTP ${e.status}`);d(t),u(null),y.current||g(t.config.defaultCwd??"")}catch(e){u(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{k();let e=setInterval(()=>void k(),5e3);return()=>clearInterval(e)},[k]);let j=(0,i.useCallback)(async(e,t,n)=>{x(e),v(null);let r=await pH(t);if(x(null),!r.ok)return void v({kind:"error",message:r.error??o("telegram.actionFailed")});let i=n();i&&v(i),await k()},[k,o]),{config:w}=l??{};return(0,r.jsxs)(sQ,{embedded:s,title:o("settings.channels"),closeLabel:o("i18n.close"),onClose:()=>a?.(),children:[(0,r.jsxs)(s8,{children:[(0,r.jsx)(s6,{children:(0,r.jsx)(s3,{children:c&&!l?(0,r.jsx)("div",{role:"alert",className:"config-sidebar-message is-error",children:o("channels.loadFailed",{error:c})}):l?(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(s5,{children:o("channels.group")}),(n=l.config.tokenSet?l.config.enabled?l.lastError?{tone:"error",badge:"channels.badge.error"}:{tone:"on",badge:"channels.badge.on"}:{tone:"off",badge:"channels.badge.off"}:{tone:"off",badge:"channels.badge.unconfigured"},(0,r.jsxs)(ae,{active:!0,"aria-label":`Telegram — ${o(n.badge)}`,children:[(0,r.jsx)(aC,{..."on"===(t=n.tone)?{active:!0}:"off"===t?{active:!1}:{color:"#ef4444"}}),(0,r.jsx)(at,{className:"is-grow",children:"Telegram"}),(0,r.jsx)("span",{className:`mcp-sidebar-badge${"error"===n.tone?" is-error":""}`,children:o(n.badge)})]}))]}):(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")})})}),(0,r.jsx)(av,{children:(0,r.jsx)(an,{className:"is-fill",children:l&&w?(0,r.jsxs)(r.Fragment,{children:[b&&(0,r.jsx)(af,{children:b.message}),l.lastError&&(0,r.jsx)(af,{children:o("telegram.loopError",{error:l.lastError})}),(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(aa,{children:"Telegram"})}),(0,r.jsx)(as,{children:(0,r.jsx)(aw,{checked:w.enabled,disabled:!w.tokenSet||null!==f,label:o("telegram.enabledLabel"),onChange:e=>void j("enabled",{action:"set-enabled",enabled:e},()=>null)})})]}),!w.tokenSet&&(0,r.jsx)(af,{children:o("telegram.setupHint")}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:o("telegram.botStatus"),children:l.running?o("telegram.connected",{bot:l.botUsername??""}):o("telegram.notConnected")}),(0,r.jsx)(ac,{label:o("telegram.tokenLabel"),children:(0,r.jsx)("input",{type:"password",autoComplete:"off",spellCheck:!1,className:"mcp-add-input",placeholder:w.tokenSet?o("telegram.tokenPlaceholder",{hint:w.tokenHint??""}):"1234567890:AA…","aria-label":o("telegram.tokenLabel"),value:p,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)(as,{children:[(0,r.jsx)(aj,{size:"small",disabled:""===p.trim()||null!==f,onClick:()=>void j("token",{action:"set-token",token:p.trim()},()=>(h(""),{kind:"ok",message:o("telegram.tokenSaved")})),children:o("telegram.tokenSave")}),w.tokenSet&&(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j("remove-token",{action:"remove-token"},()=>({kind:"info",message:o("telegram.tokenRemoved")})),children:o("telegram.tokenRemove")})]}),(0,r.jsx)(ao,{children:o("telegram.chatsHeading")}),(0,r.jsx)(ai,{children:o("telegram.chatsDescription")}),l.lastUnknownChat&&(0,r.jsx)(af,{action:(0,r.jsx)(aj,{size:"small",disabled:null!==f||w.allowedChats.some(e=>e.id===l.lastUnknownChat?.id),onClick:()=>void j("allow",{action:"allow-chat",chatId:l.lastUnknownChat?.id,title:l.lastUnknownChat?.title},()=>({kind:"ok",message:o("telegram.chatAllowed")})),children:o("telegram.allowChat")}),children:o("telegram.unknownChatPrompt",{title:l.lastUnknownChat.title??o("telegram.unnamedChat"),id:String(l.lastUnknownChat.id)})}),0===w.allowedChats.length?(0,r.jsx)(ab,{children:o("telegram.noChats")}):(0,r.jsx)(r.Fragment,{children:w.allowedChats.map(e=>(0,r.jsx)("div",{className:"channels-chat",children:(0,r.jsxs)(ad,{children:[(0,r.jsxs)(ac,{label:e.title??o("telegram.unnamedChat"),mono:!0,children:[e.id,(0,r.jsxs)(as,{children:[(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j(`test-${e.id}`,{action:"test-send",chatId:e.id},()=>({kind:"ok",message:o("telegram.testSent")})),children:o("telegram.testSend")}),(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==f,onClick:()=>void j(`remove-${e.id}`,{action:"remove-chat",chatId:e.id},()=>({kind:"info",message:o("telegram.chatRemoved")})),children:o("telegram.chatRemove")})]})]}),(0,r.jsx)(ac,{label:o("telegram.chatCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:o("telegram.defaultCwdPlaceholder"),"aria-label":o("telegram.chatCwdLabel"),defaultValue:e.cwd??"",onBlur:t=>{let n=t.target.value.trim();n!==(e.cwd??"")&&j(`cwd-${e.id}`,{action:"set-chat-cwd",chatId:e.id,cwd:n},()=>({kind:"ok",message:o("telegram.chatCwdSaved")}))}},`${e.id}:${e.cwd??""}`)})]})},e.id))}),(0,r.jsx)(ao,{children:o("telegram.defaultCwdLabel")}),(0,r.jsx)(ad,{children:(0,r.jsx)(ac,{label:o("telegram.defaultCwdLabel"),children:(0,r.jsx)("input",{type:"text",spellCheck:!1,className:"mcp-add-input",placeholder:o("telegram.defaultCwdPlaceholder"),"aria-label":o("telegram.defaultCwdLabel"),value:m,onChange:e=>{y.current=!0,g(e.target.value)}})})}),(0,r.jsx)(as,{children:(0,r.jsx)(aj,{size:"small",disabled:null!==f,onClick:()=>void j("cwd",{action:"set-default-cwd",cwd:m.trim()},()=>({kind:"ok",message:o("telegram.defaultCwdSaved")})),children:o("telegram.defaultCwdSave")})})]}):null})})]}),(0,r.jsx)(ay,{status:l?(0,r.jsx)(ak,{tone:l.lastError?"warning":void 0,summary:l.running?o("telegram.connected",{bot:l.botUsername??""}):o("telegram.notConnected")}):void 0,children:!s&&a&&(0,r.jsx)(aj,{onClick:a,children:o("i18n.close")})})]})}let pq={minutes:6e4,hours:36e5,days:864e5};function pK(e){return String(e).padStart(2,"0")}function pZ(e){let t=new Date(e);return`${t.getFullYear()}-${pK(t.getMonth()+1)}-${pK(t.getDate())}T${pK(t.getHours())}:${pK(t.getMinutes())}`}function pV(e){if("cron"===e.kind)return{kind:"cron",expr:e.cronExpr.trim(),...""!==e.cronTz.trim()?{tz:e.cronTz.trim()}:{}};if("at"===e.kind){let t=Date.parse(e.atLocal);return Number.isFinite(t)?{kind:"at",atMs:t}:null}let t=Math.round(e.everyValue)*pq[e.everyUnit];return Number.isFinite(t)&&e.everyValue>0?{kind:"every",everyMs:t}:null}function pJ(e){if(!e)return{name:"",kind:"every",cronExpr:"0 9 * * *",cronTz:Intl.DateTimeFormat().resolvedOptions().timeZone,atLocal:pZ(Date.now()+36e5),everyValue:1,everyUnit:"hours",cwd:"",prompt:"",notify:!0,notifyChannels:[],silentWhen:""};let t=e.schedule;return{name:e.name,kind:t.kind,cronExpr:"cron"===t.kind?t.expr:"0 9 * * *",cronTz:"cron"===t.kind?t.tz??"":"",atLocal:"at"===t.kind?pZ(t.atMs):pZ(Date.now()+36e5),everyValue:"every"===t.kind?t.everyMs/pq.hours>=1&&t.everyMs%pq.hours==0?t.everyMs/pq.hours:Math.max(1,Math.round(t.everyMs/pq.minutes)):1,everyUnit:"every"===t.kind&&(t.everyMs%pq.hours!=0||t.everyMs<pq.hours)?"minutes":"hours",cwd:e.cwd,prompt:e.prompt,notify:e.notify,notifyChannels:e.notifyChannels.flatMap(e=>"telegram"===e.type&&Number.isInteger(e.chatId)?[{type:"telegram",chatId:e.chatId}]:[]),silentWhen:e.silentWhen}}function pG(e,t){if(null===e)return t("automations.neverAgain");let n=new Date(e),r=new Date().toDateString()===n.toDateString(),i=`${pK(n.getHours())}:${pK(n.getMinutes())}`;return r?i:`${pK(n.getMonth()+1)}-${pK(n.getDate())} ${i}`}async function pY(e){let t=await fetch("/api/automations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));return{ok:t.ok,error:"string"==typeof n.error?n.error:void 0,payload:n}}function pX(e){let{embedded:t=!0,onClose:n}=e,{t:s}=(0,eX.s)(),[a,o]=(0,i.useState)(null),[l,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(()=>pJ(null)),[x,b]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),w=(0,i.useRef)("ok"),S=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/automations",{cache:"no-store"}),t=await e.json();if(!e.ok||t.error)return;o(t.automations??[]),d(t.runs??[]),t.telegram&&u(t.telegram)}catch{}},[]);(0,i.useEffect)(()=>{S();let e=setInterval(()=>void S(),5e3);return()=>clearInterval(e)},[S]);let C=(0,i.useMemo)(()=>a?.find(e=>e.id===h)??null,[a,h]),N=(0,i.useCallback)(e=>{m(e),b(null),j(null),f(pJ(a?.find(t=>t.id===e)??null))},[a]),I=(0,i.useCallback)(()=>{m("new"),b(null),j(null),f(pJ(null))},[]);(0,i.useEffect)(()=>{let e=pV(g);if(!e)return;let t=setTimeout(()=>{pY({action:"preview",schedule:e}).then(e=>{e.ok?b({dueAt:"number"==typeof e.payload?.dueAt?e.payload.dueAt:null,problem:"string"==typeof e.payload?.problem?e.payload.problem:null}):b({dueAt:null,problem:e.error??s("automations.actionFailed")})})},400);return()=>clearTimeout(t)},[g,s]);let $=(0,i.useCallback)(async(e,t,n)=>{y(e),j(null);let r=await pY(t);return(y(null),r.ok)?(null!==n&&(w.current="ok",j(n)),await S(),!0):(w.current="error",j(r.error??s("automations.actionFailed")),!1)},[S,s]),E=()=>n?.(),T=null!==C,M=pV(g),R=""!==g.name.trim()&&""!==g.cwd.trim()&&""!==g.prompt.trim()&&null!==M&&x?.problem==null;return(0,r.jsxs)(sQ,{embedded:t,title:s("settings.automations"),closeLabel:s("i18n.close"),onClose:E,children:[(0,r.jsxs)(s8,{children:[(0,r.jsxs)(s6,{children:[(0,r.jsx)(s3,{children:null===a?(0,r.jsx)("div",{className:"config-sidebar-message",children:s("i18n.loading")}):0===a.length&&null===h?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:s("automations.noneYet")}):(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(s5,{children:s("automations.group")}),a.map(e=>(0,r.jsxs)(ae,{active:h===e.id,onClick:()=>N(e.id),children:[(0,r.jsx)(aC,{active:e.enabled&&null!==e.nextDueAt}),(0,r.jsx)(at,{className:"is-grow",children:e.name}),(0,r.jsx)("span",{className:"mcp-sidebar-badge",children:e.enabled?null!==e.nextDueAt?pG(e.nextDueAt,s):"…":s("channels.badge.off")})]},e.id))]})}),(0,r.jsx)(aS,{active:"new"===h,onClick:I,children:s("automations.newAction")})]}),(0,r.jsx)(av,{children:(0,r.jsxs)(an,{className:"is-fill",children:[(null===h||"new"===h||T)&&(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)(af,{children:k}),null!==h&&"new"!==h&&T&&(0,r.jsxs)(ar,{children:[(0,r.jsx)(ai,{children:(0,r.jsx)(aa,{children:C.name})}),(0,r.jsxs)(as,{children:[(0,r.jsx)(aw,{checked:C.enabled,disabled:null!==v,label:s("automations.enabledLabel"),onChange:e=>void $(`enabled-${C.id}`,{action:"set-enabled",id:C.id,enabled:e},null)}),(0,r.jsx)(aj,{size:"small",variant:"secondary",disabled:null!==v,onClick:()=>void $(`run-${C.id}`,{action:"run-now",id:C.id},s("automations.runStarted")),children:s("automations.runNow")}),(0,r.jsx)(aj,{size:"small",variant:"danger",disabled:null!==v,onClick:()=>{$(`delete-${C.id}`,{action:"delete",id:C.id},s("automations.deleted")).then(e=>{e&&N(null)})},children:s("automations.delete")})]})]}),(0,r.jsxs)(ad,{children:[(0,r.jsx)(ac,{label:s("automations.nameLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,"aria-label":s("automations.nameLabel"),value:g.name,onChange:e=>f(t=>({...t,name:e.target.value}))})}),(0,r.jsx)(ac,{label:s("automations.scheduleLabel"),children:(0,r.jsxs)("div",{className:"automations-schedule",children:[(0,r.jsxs)("select",{"aria-label":s("automations.scheduleLabel"),value:g.kind,onChange:e=>f(t=>({...t,kind:e.target.value})),children:[(0,r.jsx)("option",{value:"cron",children:s("automations.kind.cron")}),(0,r.jsx)("option",{value:"every",children:s("automations.kind.every")}),(0,r.jsx)("option",{value:"at",children:s("automations.kind.at")})]}),"cron"===g.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"0 9 * * 1-5","aria-label":s("automations.cronExpr"),value:g.cronExpr,onChange:e=>f(t=>({...t,cronExpr:e.target.value}))}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"Asia/Shanghai","aria-label":s("automations.cronTz"),value:g.cronTz,onChange:e=>f(t=>({...t,cronTz:e.target.value}))})]}),"every"===g.kind&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"automations-number-input",type:"number",min:1,"aria-label":s("automations.everyValue"),value:g.everyValue,onChange:e=>f(t=>({...t,everyValue:Number(e.target.value)}))}),(0,r.jsxs)("select",{"aria-label":s("automations.everyUnit"),value:g.everyUnit,onChange:e=>f(t=>({...t,everyUnit:e.target.value})),children:[(0,r.jsx)("option",{value:"minutes",children:s("automations.unit.minutes")}),(0,r.jsx)("option",{value:"hours",children:s("automations.unit.hours")}),(0,r.jsx)("option",{value:"days",children:s("automations.unit.days")})]})]}),"at"===g.kind&&(0,r.jsx)("input",{className:"automations-datetime-input",type:"datetime-local","aria-label":s("automations.atTime"),value:g.atLocal,onChange:e=>f(t=>({...t,atLocal:e.target.value}))})]})}),(0,r.jsx)(ac,{label:s("automations.nextRun"),children:null===x?"…":null!==x.problem?`⚠️ ${x.problem}`:`${pG(x.dueAt,s)}`}),(0,r.jsx)(ac,{label:s("automations.cwdLabel"),children:(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"/Volumes/…","aria-label":s("automations.cwdLabel"),value:g.cwd,onChange:e=>f(t=>({...t,cwd:e.target.value}))})}),(0,r.jsx)(ac,{label:s("automations.notifyLabel"),children:(0,r.jsxs)("div",{className:"automations-notify",children:[(0,r.jsxs)("div",{className:"automations-notify-row",children:[(0,r.jsx)(aw,{checked:g.notify,label:s("automations.notifyBrowser"),onChange:e=>f(t=>({...t,notify:e}))}),(0,r.jsx)("span",{children:s("automations.notifyBrowser")})]}),null!==c&&c.chats.map(e=>{let t=g.notifyChannels.some(t=>t.chatId===e.id);return(0,r.jsxs)("label",{className:"automations-notify-row",children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:t=>f(n=>({...n,notifyChannels:t.target.checked?[...n.notifyChannels,{type:"telegram",chatId:e.id}]:n.notifyChannels.filter(t=>t.chatId!==e.id)}))}),(0,r.jsx)("span",{children:null!==e.title&&""!==e.title.trim()?e.title:`Telegram \xb7 ${e.id}`})]},e.id)}),null!==c&&0===c.chats.length&&(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifyTelegramHint")}),(0,r.jsxs)("div",{className:"automations-notify-row is-wide",children:[(0,r.jsx)("span",{className:"automations-notify-silent-label",children:s("automations.notifySilentLabel")}),(0,r.jsx)("input",{className:"mcp-add-input",type:"text",spellCheck:!1,placeholder:"NO_REPLY","aria-label":s("automations.notifySilentLabel"),value:g.silentWhen,onChange:e=>f(t=>({...t,silentWhen:e.target.value}))})]}),(0,r.jsx)("div",{className:"automations-notify-hint",children:s("automations.notifySilentHint")})]})})]}),(0,r.jsx)(al,{label:s("automations.promptLabel"),children:(0,r.jsx)("textarea",{className:"automations-prompt",rows:5,spellCheck:!1,"aria-label":s("automations.promptLabel"),value:g.prompt,onChange:e=>f(t=>({...t,prompt:e.target.value}))})}),"new"===h&&(0,r.jsx)(af,{children:s("automations.disclosure")}),(0,r.jsx)(as,{children:(0,r.jsx)(aj,{disabled:!R||null!==v,onClick:()=>{$("save",{action:T?"update":"create",...T?{id:C.id}:{},name:g.name.trim(),schedule:pV(g),cwd:g.cwd.trim(),prompt:g.prompt,notify:g.notify,notifyChannels:g.notifyChannels,silentWhen:g.silentWhen.trim()},T?s("automations.saved"):s("automations.created")).then(e=>{e&&(T||m(null))})},children:T?s("automations.save"):s("automations.create")})})]}),(0,r.jsx)(ao,{children:s("automations.historyTitle")}),0===l.length?(0,r.jsx)(ab,{children:s("automations.noRuns")}):(0,r.jsx)(ad,{children:l.slice(0,12).map(e=>{let t=a?.find(t=>t.id===e.automationId),n=null!==e.finishedAt?Math.max(1,Math.round((e.finishedAt-e.startedAt)/1e3)):null;return(0,r.jsxs)(ac,{label:t?.name??s("automations.deletedAutomation"),mono:!0,children:[(0,r.jsx)(aC,{..."failed"===e.status?{color:"#ef4444"}:{active:"done"===e.status}}),s(`automations.run.${e.status}`)," \xb7 ",new Date(e.startedAt).toLocaleString(),null!==n?` \xb7 ${n}s`:"",null!==e.sessionId&&(0,r.jsx)(aj,{size:"small",variant:"secondary",onClick:()=>window.open(p(e.sessionId),"_blank"),children:s("automations.openSession")})]},e.id)})})]})})]}),(0,r.jsx)(ay,{status:null!==a?(0,r.jsx)(ak,{summary:s("automations.footerCount",{count:a.length})}):void 0,children:!t&&E&&(0,r.jsx)(aj,{onClick:E,children:s("i18n.close")})})]})}var pQ=n(75702);let p0=[{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 p1(){let{t:e}=(0,eX.s)(),t=(0,ro.VE)();return(0,r.jsx)("div",{className:"settings-font-rows",children:p0.map(n=>{let{kind:i,label:s,placeholder:a,reset:o,weightLabel:l}=n,d=t[`${i}Weight`],c=pQ.qI.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(a),maxLength:pQ.zx,"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(l)}: ${d}`,children:e(pQ.qI[c].label)}),(0,r.jsx)(aj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(o),"aria-label":e(o),disabled:!t[i]&&d===pQ.Fj,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:pQ.qI[0].value,max:pQ.qI[pQ.qI.length-1].value,step:100,value:d,"aria-label":e(l),"aria-valuetext":`${d} ${e(pQ.qI[c].label)}`,onChange:e=>t.setFontWeight(i,Number(e.target.value))})]},i)})})}function p2(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"})]}):"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"})]}):"channels"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("path",{d:"m21.5 4.5-2.9 13.2a1.6 1.6 0 0 1-2.5.9L12 15.6l-2.3 2.3a1 1 0 0 1-1.7-.5L7 13.6 3.4 12.2a.8.8 0 0 1-.1-1.5L20.2 3.2a.9.9 0 0 1 1.3 1.3Z"}),(0,r.jsx)("path",{d:"m7 13.6 11.7-8.4L9.4 14.8"})]}):"automations"===t?(0,r.jsxs)("svg",{...s,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3.5 2"})]}):(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 p4(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:s,onQuoteSelectionChange:a}=e,{locale:o,setLocale:l,supportedLocales:d,t:c}=(0,eX.s)(),{preference:u,setThemePreference:p}=(0,sg.D)(),{width:h,setWidth:m,fontSize:g,setFontSize:f}=(0,ra.Uh)(),x=rs(),b=eY(),[v,y]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(!1),[I,$]=(0,i.useState)(null),[E,T]=(0,i.useState)(!1),[M,R]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[P,z]=(0,i.useState)(null),[O,W]=(0,i.useState)(null),[F,D]=(0,i.useState)(!1),[B,_]=(0,i.useState)(null),[H,U]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[Z,V]=(0,i.useState)(!1),[J,G]=(0,i.useState)(!1),[Y,X]=(0,i.useState)("");(0,i.useEffect)(()=>{T((0,sI.ql)()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>V(e?.enabled===!0)).catch(()=>{})},[]);let Q=async()=>{G(!0),X("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{X(c("auth.logoutFailed"))}finally{G(!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||R(!0===n.enabled)}).catch(t=>{e||z(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/auto-title").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||W(!0===n.enabled)}).catch(t=>{e||_(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let ee=async e=>{L(!0),z(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}`);R(!0===i.enabled),t&&n()}catch(e){z(e instanceof Error?e.message:String(e))}finally{L(!1)}},et=async e=>{D(!0),_(null);try{let t=await fetch("/api/auto-title",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);W(!0===n.enabled)}catch(e){_(e instanceof Error?e.message:String(e))}finally{D(!1)}},en=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 ic(t,{type:"reload"}),n())}catch(e){S(e instanceof Error?e.message:String(e))}finally{j(!1)}},er=async(e,t)=>{if(v){N(!0),$(null);try{let n=t?[...v.builtinTools,e]:v.builtinTools.filter(t=>t!==e),r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({builtinTools:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);y(i)}catch(e){$(e instanceof Error?e.message:String(e))}finally{N(!1)}}},ei=async()=>{if(!H){U(!0),K(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 ol(o))throw Error("unsupported or not permitted");K({kind:"ok",message:c("settings.pushRegistered")})}catch(e){K({kind:"error",message:`${c("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{U(!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:sf.F$.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)(p1,{}),(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:[g,"px"]}),(0,r.jsx)(aj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentFontSize"),"aria-label":c("settings.resetChatContentFontSize"),disabled:g===ra.NN,onClick:()=>f(ra.NN),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:ra.WH,max:ra.Oi,step:1,value:g,onChange:e=>f(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)(aj,{variant:"ghost",size:"small",className:"settings-chat-reset",title:c("settings.resetChatContentWidth"),"aria-label":c("settings.resetChatContentWidth"),disabled:h===ra.mi,onClick:()=>m(ra.mi),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:ra.lg,max:ra.fI,step:10,value:h,onChange:e=>m(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)(aw,{checked:E,label:c("settings.thinkingExpandedDefault"),onChange:e=>{(0,sI.kF)(e),T(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)(aw,{checked:s,label:c("settings.quoteSelection"),onChange:a})]}),(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:()=>ri("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:()=>ri("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)(aw,{checked:!0===M,loading:null===M&&!P||A,label:c("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void ee(e)})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:c("settings.autoTitle")}),(0,r.jsx)(aw,{checked:!1!==O,loading:null===O&&!B||F,label:c("settings.autoTitle"),describedBy:"settings-auto-title-description",onChange:e=>void et(e)})]})]}),(0,r.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:c("settings.cacheMissNoticesDescription")}),P&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:P}),(0,r.jsx)("p",{id:"settings-auto-title-description",className:"settings-general-description",children:c("settings.autoTitleDescription")}),B&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:B})]}),(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"===b,onChange:()=>eG("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"===b,onChange:()=>eG("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")})]}),v&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:c("settings.builtinTools")}),(0,r.jsx)("p",{id:"settings-builtin-tools-description",className:"settings-general-description",children:c("settings.builtinToolsDescription")}),(0,r.jsx)("div",{className:"settings-send-mode-options settings-builtin-tools",role:"group","aria-label":c("settings.builtinTools"),"aria-describedby":"settings-builtin-tools-description",children:ik.kt.map(e=>(0,r.jsxs)("label",{className:"settings-send-mode-option",children:[(0,r.jsx)("input",{type:"checkbox",checked:v.builtinTools.includes(e),disabled:C,onChange:t=>void er(e,t.target.checked),className:"sr-only"}),(0,r.jsx)("span",{className:"settings-send-mode-label",children:"bash"===e&&v.powerShellEnabled?"powershell":e})]},e))}),I&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:I})]}),v?.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)(aw,{checked:v.powerShellEnabled,loading:k,label:c("settings.usePowerShell"),onChange:e=>void en(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}),(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:H,onClick:()=>void ei(),children:H?c("settings.pushRegisterLoading"):c("settings.pushRegister")})]}),q&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===q.kind?{color:"var(--accent)"}:void 0,children:q.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:()=>l(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)})})]}),Z&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(aj,{variant:"secondary",disabled:J,onClick:()=>void Q(),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"})}),J?c("auth.loggingOut"):c("auth.logOut")]}),Y&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:Y})]})]})}let p8={home:"home",section:"home",detail:"section"},p6={home:0,section:1,detail:2},p3="cubic-bezier(0.2, 0.8, 0.2, 1)";function p5(e){let t,{cwd:n,sessionId:s,initialSection:a,openAtHome:o=!1,onClose:l,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u,projectTrust:p,onOpenTrustDialog:h,onProjectTrustChanged:m}=e,{t:g}=(0,eX.s)(),[f,x]=(0,i.useState)(a),[b,v]=(0,i.useState)(()=>new Set([f])),y=[{id:"general",label:g("settings.general")},{id:"models",label:g("common.models")},{id:"skills",label:g("common.skills")},{id:"agents",label:g("common.agents")},{id:"plugins",label:g("common.plugins")},{id:"mcp",label:g("settings.mcp")},{id:"channels",label:g("settings.channels")},{id:"automations",label:g("settings.automations")}].map(e=>({...e,requiresProject:sy(e.id)})),k=sy(f),j=(0,eQ.a)(),w=function(e,t){let[n,r]=(0,i.useState)(t?"home":"section");e||"section"===n||r("section");let s=(0,i.useRef)(n);s.current=n;let a=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;let t=()=>{0!==a.current&&(a.current-=1,r(e=>p8[e]))};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]);let o=(0,i.useCallback)(t=>{e&&(window.history.pushState(window.history.state,""),a.current+=1,r(t))},[e]);return{level:n,levelRef:s,enter:o,goUp:(0,i.useCallback)(()=>{a.current>0?window.history.back():r(e=>p8[e])},[]),dropHistory:(0,i.useCallback)(()=>{let e=a.current;a.current=0,e>0&&window.history.go(-e)},[])}}(j,o),{dropHistory:S,enter:C,goUp:N,levelRef:I}=w,$=(0,i.useRef)(null),E=(0,i.useRef)(null),T=(0,i.useRef)(w.level);(0,i.useLayoutEffect)(()=>{let e=T.current;T.current=w.level,j&&e!==w.level&&function(e,t,n,r){if(!e||"function"!=typeof e.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let i=p6[r]>p6[n];e.animate(i?[{transform:"translateX(100%)",boxShadow:"-12px 0 24px rgba(0, 0, 0, 0.12)"},{transform:"translateX(0)",boxShadow:"-12px 0 24px rgba(0, 0, 0, 0)"}]:[{transform:"translateX(-30%)",opacity:.4},{transform:"translateX(0)",opacity:1}],{duration:280,easing:p3}),t?.querySelectorAll(".settings-phone-back, .settings-dialog-title").forEach(e=>{e.animate([{opacity:0,transform:`translateX(${i?16:-16}px)`},{opacity:1,transform:"translateX(0)"}],{duration:220,easing:p3})})}(E.current,$.current,e,w.level)},[j,w.level]);let M=(0,i.useCallback)(()=>{S(),l()},[l,S]),R=y.find(e=>e.id===f)?.label??g("settings.title"),[A,L]=(0,i.useState)(null),P=(0,i.useMemo)(()=>({detailOpen:"detail"===w.level,openDetail:()=>{"section"===I.current&&(L(null),C("detail"))},closeDetail:()=>{"detail"===I.current&&N()},reportDetailTitle:L}),[C,N,w.level,I]);(0,i.useEffect)(()=>sS(a),[a]),(0,i.useEffect)(()=>{var e;let t;return e=document,t=e=>{"Escape"!==e.key||e.defaultPrevented||eI(e)||(e.preventDefault(),M())},e.addEventListener("keydown",t,!1),()=>e.removeEventListener("keydown",t,!1)},[M]);let z=(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,z.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,i.useEffect)(()=>{!n&&k&&(x("general"),v(e=>new Set(e).add("general")),sS("general"))},[n,k]);let O=e=>{v(t=>new Set(t).add(e)),x(e),sS(e)},W=(e,t)=>b.has(e)?(0,r.jsx)("div",{hidden:f!==e||"home"===w.level,"data-phone-level":j?w.level:void 0,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{ref:z,role:"dialog","aria-modal":"true","aria-label":g("settings.title"),tabIndex:-1,onClick:e=>{e.target===e.currentTarget&&M()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{ref:$,className:"settings-dialog-header",children:[j&&"home"!==w.level&&(t="detail"===w.level?R:g("settings.title"),(0,r.jsxs)("button",{type:"button",className:"settings-phone-back",onClick:N,"aria-label":g("settings.backTo",{name:t}),children:[(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)("span",{children:t})]})),(0,r.jsx)("strong",{className:"settings-dialog-title",children:j&&"home"!==w.level?"section"===w.level?R:A:g("settings.title")}),(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-section-tabs",children:y.map(e=>{let t=f===e.id,i=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?g("settings.projectRequired"):e.label,"aria-current":t?"page":void 0,onClick:()=>O(e.id),children:[(0,r.jsx)(p2,{section:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id)})}),(0,r.jsx)("button",{type:"button",onClick:M,title:g("i18n.close"),"aria-label":g("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{ref:E,className:"settings-dialog-main",children:[j&&"home"===w.level&&(0,r.jsx)("nav",{"aria-label":g("settings.title"),className:"settings-phone-home",children:y.map(e=>{let t=e.requiresProject&&!n;return(0,r.jsxs)("button",{type:"button",className:"settings-phone-home-item",disabled:t,"aria-describedby":t?`settings-phone-home-${e.id}-note`:void 0,onClick:()=>{O(e.id),C("section")},children:[(0,r.jsx)(p2,{section:e.id,size:20}),(0,r.jsxs)("span",{className:"settings-phone-home-label",children:[(0,r.jsx)("span",{children:e.label}),t&&(0,r.jsx)("span",{id:`settings-phone-home-${e.id}-note`,className:"settings-phone-home-note",children:g("settings.projectRequired")})]}),(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",className:"settings-phone-home-chevron",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]},e.id)})}),(0,r.jsxs)(s0.Provider,{value:P,children:[W("general",(0,r.jsx)(p4,{sessionId:s,onSessionReloaded:d,quoteSelectionEnabled:c,onQuoteSelectionChange:u})),W("models",(0,r.jsx)(oa,{embedded:!0,cwd:n,onClose:M})),n&&W("skills",(0,r.jsx)(ob,{embedded:!0,cwd:n,trust:p,onClose:M},n)),n&&W("agents",(0,r.jsx)(oM,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:M,onReloaded:d},n)),n&&W("plugins",(0,r.jsx)(oU,{embedded:!0,cwd:n,sessionId:s,trust:p,onClose:M,onReloaded:d},n)),W("mcp",(0,r.jsx)(pw,{embedded:!0,cwd:n,trust:p,onTrustProject:h,onProjectTrustChanged:m,onClose:M},n??"")),W("channels",(0,r.jsx)(pU,{})),W("automations",(0,r.jsx)(pX,{}))]})]})]})})}let p9="project-trust-mcp-status";function p7(e){let{cwd:t,busy:n,error:s,onCancel:a,onConfirm:o,onStatus:l}=e,[d,c]=(0,i.useState)({state:"loading"}),u=(0,i.useRef)(l);return(0,i.useEffect)(()=>{u.current=l},[l]),(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)(he,{cwd:t,busy:n,error:s,listing:d,onCancel:a,onConfirm:o})}function he(e){let{cwd:t,busy:n,error:s,listing:a,onCancel:o,onConfirm:l}=e,{t:d}=(0,eX.s)(),c="loading"===a.state,u="loaded"===a.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(a.status):void 0,p=(0,i.useRef)(null),h=(0,i.useRef)(n),m=(0,i.useRef)(o);return(0,i.useEffect)(()=>{h.current=n,m.current=o},[n,o]),(0,i.useEffect)(()=>{var e,t,n;let r,i,s;return e=document,t=p.current,n=()=>{h.current||m.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=e=>{"Escape"!==e.key||(e.stopPropagation(),eI(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:oV(t)}),u&&(0,r.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:d(u)}),"loaded"===a.state&&void 0!==a.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:oV(a.statusError)})]}),(0,r.jsx)(hn,{listing:a})]})]}),s&&(0,r.jsx)(ht,{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:l,disabled:n||c,"aria-busy":n||void 0,"aria-describedby":c?p9:void 0,children:d(n?"trust.trusting":"trust.trustProject")})]})]})})}function ht(e){let{error:t}=e,{t:n}=(0,eX.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:oV(t.error)})]})}function hn(e){let{listing:t}=e,{t:n}=(0,eX.s)();if("loading"===t.state)return(0,r.jsx)("p",{id:p9,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:oV(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)(hr,{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)(ha,{server:e},e.name))})]}):null}function hr(e){let{file:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:t.problems.map(e=>{let i=o8(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 hi(e){let{fields:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:t.map(e=>{let t=o0(e);return(0,r.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function hs(e){let{server:t}=e,{t:n}=(0,eX.s)();return(0,r.jsx)(r.Fragment,{children:o4(t.variableReferences).map(e=>{let{variable:t,field:i}=e,s=o0(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 ha(e){let t,{server:n}=e,{t:i}=(0,eX.s)(),s=oX(n),a=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:oV(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:oV(n.cwd)})}),oQ(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:oV(n.invalidError)})]}),n.webPasswordField&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.webPassword")," ",(0,r.jsx)(hi,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,r.jsx)("p",{className:"project-trust-mcp-line",children:i("mcp.server.disabled")}),a&&n.commandFields.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i("mcp.server.commandFields")," ",(0,r.jsx)(hi,{fields:n.commandFields})]}),a&&n.variableReferences.length>0&&(0,r.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[i(o1(n))," ",(0,r.jsx)(hs,{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=o2(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 ho(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function hl(e){let t=e,n=t.branchPreview,r=ho(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&ho(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function hd(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 hc(e){let{node:t,activePathIds:n,depth:i,isLast:s,parentLines:a,onSelect:o}=e,{node:l,skipped:d,branchPreview:c,labelEntry:u}=hl(t),p=n.has(l.entry.id),h=n.has(t.entry.id)||n.has(l.entry.id),m=c?.text??function(e){if("message"===e.type&&ho(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),g=c?c.role??null:ho(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(l.entry.id):void 0,children:[a.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"}}),g&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===g?"var(--accent)":"var(--text-dim)",background:"user"===g?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===g?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===g?"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:m})]}),l.children.map((e,t)=>(0,r.jsx)(hc,{node:e,activePathIds:n,depth:i+1,isLast:t===l.children.length-1,parentLines:[...a,!s],onSelect:o},e.entry.id))]})}function hu(e){let{tree:t,activeLeafId:n,onLeafChange:s,inline:a,containerRef:o,open:l,onToggle:d,hasSession:c,compact:u,hideInlineButton:p,locked:h=!1}=e,{t:m}=(0,eX.s)(),[g,f]=(0,i.useState)(!1),x=void 0!==l?l:g,b=(0,i.useRef)(null),[v,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!a)return;let e=o?.current??b.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,a,o]);let k=(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]),w=h?void 0:j,S=h&&(0,r.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:m("i18n.branchesLockedWhileRunning")}),C=c?hd(t)?null:m("i18n.noBranches"):m("i18n.noActiveSession"),N=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=hl(e[0]).node;return t.children.length>1?t.children:[]}(t),I=!C&&N.length>0,$=(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:I?"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"})]}),E=(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 a?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:b,onClick:()=>d?d():f(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:m("i18n.branches"),"aria-label":m("i18n.branches"),"aria-pressed":x,children:[$,!u&&(0,r.jsx)("span",{children:m("i18n.branches")})]}),x&&v&&(0,r.jsx)("div",{style:{position:"fixed",top:v.top,left:v.left,width:v.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hc,{node:e,activePathIds:k,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},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:()=>f(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:[$,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:m("i18n.branches")}),E]}),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:I?(0,r.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[S,N.map((e,t)=>(0,r.jsx)(hc,{node:e,activePathIds:k,depth:0,isLast:t===N.length-1,parentLines:[],onSelect:w},e.entry.id))]}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:C??m("i18n.noBranches")})})]})}function hp(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:`
|
|
8
8
|
.system-prompt-panel {
|
|
9
9
|
display: flex;
|
|
10
10
|
height: min(600px, 75dvh);
|