pi-yun 0.3.7 → 0.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +13 -13
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +7 -7
- 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.js +13 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +13 -1
- package/.next/server/app/_not-found.rsc +6 -6
- package/.next/server/app/_not-found.segments/_full.segment.rsc +6 -6
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +6 -6
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +5 -5
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/api/cwd/browse/route.js.nft.json +2 -2
- package/.next/server/app/api/cwd/validate/route.js.nft.json +2 -2
- package/.next/server/app/api/models/default/route.js.nft.json +2 -2
- package/.next/server/app/api/models/enabled/route.js.nft.json +2 -2
- package/.next/server/app/index.html +13 -1
- package/.next/server/app/index.rsc +8 -8
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +19 -14
- package/.next/server/app/index.segments/_full.segment.rsc +8 -8
- package/.next/server/app/index.segments/_tree.segment.rsc +5 -5
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +13 -1
- package/.next/server/app/login.rsc +7 -7
- package/.next/server/app/login.segments/_full.segment.rsc +7 -7
- package/.next/server/app/login.segments/_tree.segment.rsc +5 -5
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +18 -13
- package/.next/server/app/page.js +11 -11
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/pet-preview/page_client-reference-manifest.js +1 -1
- package/.next/server/app/pet-preview.html +13 -1
- package/.next/server/app/pet-preview.rsc +7 -7
- package/.next/server/app/pet-preview.segments/_full.segment.rsc +7 -7
- package/.next/server/app/pet-preview.segments/_tree.segment.rsc +5 -5
- package/.next/server/app/pet-preview.segments/pet-preview/__PAGE__.segment.rsc +18 -13
- package/.next/server/app-paths-manifest.json +13 -13
- package/.next/server/chunks/2243.js +1 -1
- package/.next/server/chunks/5247.js +13 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +13 -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/1278-47be9d5535ac0d9a.js +1 -0
- package/.next/static/chunks/app/{layout-1cb83cd48b1ac329.js → layout-12c3afe80c1642e6.js} +1 -1
- package/.next/static/chunks/app/page-87e2ec7fc048f45b.js +1095 -0
- package/.next/static/chunks/{webpack-67f30ea39607f470.js → webpack-6538aa971611c09d.js} +1 -1
- package/.next/static/css/6e6de01dcc979ed8.css +1 -0
- package/.next/static/css/9dc67645f3b96ddd.css +1 -0
- package/.next/static/css/{687611655a4712bf.css → 9e397cae4b87bcb0.css} +1 -1
- package/.next/static/css/de7d296b6053e446.css +1 -0
- package/.next/trace +35 -35
- package/.next/trace-build +1 -1
- package/package.json +1 -1
- package/public/icons/sunbeam-avatars.png +0 -0
- package/.next/static/chunks/1278-8dcfbbde20475ac7.js +0 -1
- package/.next/static/chunks/app/page-4b482c6a57ee105f.js +0 -1095
- package/.next/static/css/039ba82c8bc47e49.css +0 -1
- package/.next/static/css/8a42a0b2143324a2.css +0 -1
- package/.next/static/css/b1f0128457d479a0.css +0 -1
- /package/.next/static/{fvuKFDvsSB3IdEbZoMsGT → 5ysvNCYII0Dq7UH_qNE3P}/_buildManifest.js +0 -0
- /package/.next/static/{fvuKFDvsSB3IdEbZoMsGT → 5ysvNCYII0Dq7UH_qNE3P}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,1095 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{5284:e=>{e.exports={lock:"LockToggle_lock__hI4qs"}},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>h,getPresetFromTools:()=>p,kU:()=>l,kt:()=>c,sn:()=>u,xG:()=>m});let r="configured",i=["configured","none","read-only","default","full"],s=[],l=["read","grep","find","ls"],a=["read","bash","edit","write"],o=["bash","read","edit","write","grep","find","ls"],c=["read","grep","find","ls","edit","write","bash"],d=new Set([...o,"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=>d.has(e)).sort().join(",");return t===[...l].sort().join(",")?"read-only":t===[...a].sort().join(",")?"default":t===[...o].sort().join(",")?"full":"default"}function m(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...l]:"full"===e?[...o]:[...a]}},16397:(e,t,n)=>{"use strict";let r,i,s,l,a,o,c;n.d(t,{AppShell:()=>kS});var d=n(95155),u=n(12115),p=n(73321);let h=null;function m(e,t){let{desktopOnly:n=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=(0,u.useRef)(t),i=(0,u.useRef)(null);(0,u.useLayoutEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=()=>{i.current?.cancel(),i.current=null},n=()=>{e.matches&&t()},r=()=>{document.hidden&&t()};return e.addEventListener("change",n),document.addEventListener("visibilitychange",r),()=>{e.removeEventListener("change",n),document.removeEventListener("visibilitychange",r),t()}},[]),(0,u.useLayoutEffect)(()=>{if(r.current===t)return;r.current=t;let s=e.current,l=i.current,a=l?.playState==="running"&&s?getComputedStyle(s).opacity:.84;if(l?.cancel(),i.current=null,null===t||!s||"function"!=typeof s.animate||document.hidden||s.closest('[hidden], [inert], [aria-hidden="true"]')||window.matchMedia("(prefers-reduced-motion: reduce)").matches||n&&window.matchMedia("(max-width: 640px)").matches)return;let o=s.animate([{opacity:a},{opacity:1}],{duration:160,easing:"cubic-bezier(.2, .8, .2, 1)"});i.current=o,o.onfinish=()=>{i.current===o&&(i.current=null)}},[n,e,t])}function f(){let[e,t]=(0,u.useState)(null),n=(0,u.useRef)(null),r=(0,u.useCallback)(()=>{null!==n.current&&(clearTimeout(n.current),n.current=null)},[]),i=(0,u.useCallback)(()=>{r(),t(null)},[r]),s=(0,u.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,u.useEffect)(()=>r,[r]),{phase:e,start:s,end:i}}var g=n(47650);function x(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 v(e){return e?.kind==="subagent"||e?.kind==="side"}function b(e){let t=e.relation?.kind==="subagent"?e.relation:null;return e.name||t?.description||e.firstMessage||e.id.slice(0,12)}function y(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,l=null;for(;;){if(n.has(s)){l=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(!v(r.relation)){l=r.id;break}s=r.relation.parentSessionId}for(let t of e)n.set(t,l)}return n}(e),n=new Map;for(let t of e)v(t.relation)||n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(!v(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 w(e,t){return t?y(e).find(e=>e.root.id===t||e.subagents.some(e=>e.id===t))??null:null}function j(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 k=new Map,S="parked-new:";function C(e){return`${S}${e}`}let N="pi-web:draft:",E=new Set,M=new Set,$=new Map,I=null,T=!1;function R(){try{return window.localStorage??null}catch{return null}}function A(e){return!e.startsWith("new:")&&!e.startsWith(S)}function L(e){let t=[];for(let n=0;n<e.length;n++){let r=e.key(n);r?.startsWith(N)&&t.push(r)}return t}function P(){null!==I&&clearTimeout(I),I=null;let e=[...M];M.clear();let t=R();if(t)for(let n of e)!function(e,t){let n=N+t,r=k.get(t)?.value??"";try{let t;if(!r||r.length>2e4)return void e.removeItem(n);let i=null===e.getItem(n);e.setItem(n,JSON.stringify({text:r,at:Date.now()})),i&&((t=L(e)).length<=50||t.map(t=>({key:t,at:function(e,t){try{let n=JSON.parse(e.getItem(t)??"")?.at;return"number"==typeof n&&Number.isFinite(n)?n:0}catch{return 0}}(e,t)})).sort((e,t)=>t.at-e.at).slice(50).forEach(t=>{let{key:n}=t;return e.removeItem(n)}))}catch{try{e.removeItem(n)}catch{}}}(t,n)}function z(){"hidden"===document.visibilityState&&P()}function O(e){!(!A(e)||$.has(e))&&R()&&(M.add(e),!T&&(T=!0,window.addEventListener("pagehide",P),"u">typeof document&&document.addEventListener("visibilitychange",z)),null===I&&(I=setTimeout(P,300)))}function W(e){if(M.delete(e),!A(e))return;let t=R();if(t)try{t.removeItem(N+e)}catch{}}function F(e){$.set(e,($.get(e)??0)+1),W(e);let t=!1;return()=>{if(t)return;t=!0;let n=($.get(e)??1)-1;n>0?$.set(e,n):($.delete(e),k.get(e)?.value&&O(e))}}function D(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function _(e){return!e.value&&0===e.images.length}function B(e){let t=k.get(e)??function(e){if(E.has(e)||!A(e))return null;E.add(e);let t=R();if(!t)return null;try{let n=t.getItem(N+e);if(!n)return null;let r=JSON.parse(n),i=r&&"object"==typeof r?r.text:null;if("string"!=typeof i||!i||i.length>2e4)return null;let s={value:i,images:[]};return k.set(e,s),s}catch{return null}}(e);return t?D(t):null}function H(e,t){if(_(t))return void U(e);E.add(e);let n=k.get(e);k.set(e,D(t)),t.value?n?.value!==t.value&&O(e):W(e)}function U(e){E.add(e),k.delete(e),W(e)}function K(e,t){return e.trim()?t.trim()?`${e}
|
|
2
|
+
|
|
3
|
+
${t}`:e:t}function q(e,t,n,r){let i=[...t??[],...r].filter(j).slice(0,10).map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});return{value:K(e,n),images:i}}function V(e,t,n){let r=B(e)??{value:"",images:[]},i=q(t,n,r.value,r.images);return H(e,i),i}function Z(e,t,n){if(e===t)return n?D(n):B(t);let r=B(e),i=n&&!_(n)?D(n):r??(n?D(n):null),s=B(t);if(U(e),!i)return s;let l=s?q(s.value,s.images,i.value,i.images):i;return H(t,l),D(l)}function J(e){return`?session=${encodeURIComponent(e)}`}function Y(e){return!e.defaultPrevented&&0===e.button&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&!e.altKey}let G="pi-web:last-open-by-workspace";function X(){try{return window.localStorage}catch{return null}}function Q(e){let t=e.getItem(G);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function ee(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:X();if(t)try{let n=Q(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(G):t.setItem(G,JSON.stringify(n))}catch{}}function et(e){return e.projectKey??e.projectRoot??e.cwd}function en(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=et(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 er=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,ei=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function es(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function el(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function ea(e){return"string"==typeof e&&er.test(e)}function eo(e){return"string"==typeof e&&e.length>0&&e.length<=4096&&"__proto__"!==e}let ec=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function ed(e){if(null===e)return null;if("string"!=typeof e)return;let t=e.trim();return t?ec.test(t)||[...t].length>80?void 0:t:null}function eu(e,t){let n=e.projectNames;return n&&ei(n,t)?n[t]:void 0}function ep(e,t){return!!e.removedProjects&&ei(e.removedProjects,t)}let eh=new TextEncoder;function em(e){return eh.encode(JSON.stringify(e)).length+1}function ef(e){let t=1;for(let n of e)t+=em(n);return t}function eg(e,t){return e<=1e3&&t<=262144}function ex(e){let t=[],n=1;for(let r of e){if(t.length>=1e3)break;let e=em(r);n+e>262144||(t.push(r),n+=e)}return t}function ev(e,t){return eh.encode(JSON.stringify(e)).length+eh.encode(JSON.stringify(t)).length+2}function eb(e,t){return e<=1e3&&t<=262144}function ey(){return{version:1,revision:0,sessions:{},projects:{}}}function ew(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 ej(e,t,n){let r=ei(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 ek(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 eS(e,t,n){let r={...e.projectNames};if((ei(r,t)?r[t]:void 0)===(n??void 0))return!1;if(null===n)delete r[t];else if(r[t]=n,!eb(Object.keys(r).length,function(e){let t=1;for(let[n,r]of Object.entries(e))t+=ev(n,r);return t}(r)))return!1;return 0===Object.keys(r).length?delete e.projectNames:e.projectNames=r,!0}function eC(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 eN(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 eE={desktop:{section:38,recent:30,subagent:30,"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:{section:44,recent:44,subagent:44,"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}},eM="pinned";function e$(e,t){return Object.hasOwn(e.sessions,t)?e.sessions[t]:void 0}function eI(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function eT(e){let t=Date.parse(e);return Number.isNaN(t)?-1/0:t}function eR(e,t){return e===t?0:e>t?-1:1}function eA(e){return[e.root.id,...e.subagents.map(e=>e.id)]}function eL(e,t){return 0!==t.size&&(t.has(e.root.id)||e.subagents.some(e=>t.has(e.id)))}function eP(e,t){return!!t&&(e.root.id===t||e.subagents.some(e=>e.id===t))}function ez(e,t,n){let r=eI(e$(t,e.root.id)?.archivedAt);if(null===r||eL(e,n))return!1;if(e.root.detailsPending)return!0;let i=Date.parse(e.root.modified);return Number.isNaN(i)||r>=i}function eO(e,t,n){return null!==eI(e$(t,e.root.id)?.pinnedAt)&&!ez(e,t,n)}function eW(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 eF(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 eD(e,t){return{running:eL(e,t.runningIds),awaiting:!!t.awaitingIds&&eL(e,t.awaitingIds),unread:eL(e,t.unreadIds),selected:eP(e,t.selectedSessionId),transient:!0===e.root.transient}}function e_(e,t){let n=0,r=0,i=0;for(let s of e)t.awaitingIds&&eL(s,t.awaitingIds)?r++:eL(s,t.runningIds)&&n++,eL(s,t.unreadIds)&&i++;return{running:n,awaiting:r,unread:i}}function eB(e){return et(e.root)}function eH(e){return e.relation?.kind==="subagent"&&!e.transient}function eU(e,t){let n=new Map,r=new Map;return{noteFamily(e){let t=eB(e);n.has(t)||n.set(t,e.root.projectRoot??e.root.cwd)},get(i){let s=r.get(i);if(s)return s;let l=Object.hasOwn(e.projects,i)?e.projects[i]:void 0,a=null!==t&&t.key===i,o=n.get(i)??(a?t.root:void 0)??l?.root??i,c=eu(e,i)??null,d={key:i,root:o,name:c??eW(o),customName:c,pinned:void 0!==l,current:a};return r.set(i,d),d}}}function eK(e,t,n,r){return{kind:"session",key:`session:${t}:${e.root.id}`,family:e,context:t,project:n,status:eD(e,r)}}function eq(e,t,n,r){let i=e.map((e,n)=>{if(n<t)return!1;let i=eD(e,r);return i.running||i.unread||i.selected}),s=t+n,l=0,a=e.filter((e,n)=>n<t||!!i[n]||n<s&&(l++,!0)),o=Math.max(t,Math.min(s,e.length));for(let t=0;o<e.length&&t<20;o++)!i[o]&&t++;return{visible:a,revealed:l,nextShown:o-t}}function eV(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 eZ(e,t){if(!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function eJ(e,t,n){let r=e-t,i=n>0;return r>0||i?{hidden:r,canShowLess:i}:null}function eY(e,t,n,r){let i=r-n,s=[];for(let n of y(e.sessions)){if(eB(n)!==t||ez(n,e.uiState,e.runningIds)||eO(n,e.uiState,e.runningIds))continue;let r=eD(n,e);if(r.running||r.unread||r.selected||r.transient)continue;let l=Date.parse(n.latestModified);Number.isNaN(l)||l>=i||s.push(n.root.id)}return s}function eG(e,t){let n=[],r=0;for(let i of y(e.sessions))if(eB(i)===t&&!i.root.transient){if(eL(i,e.runningIds)||e.awaitingIds&&eL(i,e.awaitingIds)){r++;continue}n.push(i.root.id)}return{ids:n,running:r}}function eX(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),l=i["up"===n?s-1:s+1];return l?{anchorKey:l.key,position:"up"===n?"before":"after"}:null}function eQ(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1)return null;let s=e[t],l=e[t+1];return"start"===i?s===n?null:s:s>=n&&l<=n+r?null:"nearest"===i&&l>n&&s<n+r?s<n||l-s>r?s:l-r:Math.max(0,s-Math.max(0,(r-(l-s))/2))}function e0(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e1(e){let t=e0(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function e2(e){let t=e0(e).replace(/\/+$/,"");return t.split("/").pop()??t}function e4(e){let t=e0(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function e3(e,t){if(!t)return e;let n=e0(e),r=e0(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function e8(e,t){return`${e0(e).replace(/\/$/,"")}/${t}`}let e6=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function e5(e){let t=e.match(e6);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let e9=/ · [0-9a-f]{4}$/;function e7(e){return e.name||(e5(e.firstMessage)??e.firstMessage)||e.id.slice(0,12)}function te(e){let t=e9.exec(e);return t&&0!==t.index?{base:e.slice(0,t.index),suffix:t[0]}:null}function tt(){try{return window.localStorage}catch{return null}}function tn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tt();if(!t)return!1;try{return"true"===t.getItem(e)}catch{return!1}}function tr(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:tt();if(n)try{n.setItem(e,String(t))}catch{}}let ti="pi-web:sidebar-tab",ts="pi-web:sidebar-groups-v2",tl="pi-web:sidebar-groups",ta="pi-web:sidebar-archive-collapsed",to="pi-web:sidebar-pins-collapsed",tc="pi-web:sidebar-recents-collapsed",td="pi-web:sidebar-subagents-collapsed",tu="pi-web:sidebar-files-show-ignored",tp="pi-web:sidebar-files-collapsed",th="pi-web:sidebar-changes-view-mode",tm="pi-web:sidebar-non-git-cwds",tf=["pi-web:file-explorer:open","pi-web:sidebar-session-pane-height",tl];function tg(){try{return window.localStorage}catch{return null}}function tx(e){let t={};if(null===e||"object"!=typeof e||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))"__proto__"!==n&&"boolean"==typeof r&&(t[n]=r);return t}function tv(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{let n=Object.entries(tx(e)),r=n.length>300?n.slice(n.length-300):n;t.setItem(ts,JSON.stringify(Object.fromEntries(r)))}catch{}}function tb(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(ta,JSON.stringify([...new Set(e)].slice(-300)))}catch{}}function ty(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(to,String(e))}catch{}}function tw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return[];try{let t=e.getItem(tm),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];return n.filter(e=>"string"==typeof e&&""!==e).slice(-50)}catch{return[]}}function tj(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}}}}async function tk(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 tS(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function tC(e,t){let n=t.replace(/[/\\]+$/,"");return n&&(e===n||e.startsWith(`${n}/`)||e.startsWith(`${n}\\`))?`./${e.slice(n.length).replace(/^[/\\]/,"")}`:tS(e)}function tN(e,t){return{cwd:e.current&&t?t:e.root,projectKey:e.key,projectRoot:e.root}}function tE(e){let t=e.project;return!t||e.projects.some(e=>e.key===t.key)?[...e.projects]:[t,...e.projects]}function tM(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 t$(e){let t=e.map(e=>({choice:e,name:e.alias??eW(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?eW(t.slice(0,r)):null}})}let tI={awaiting:"#d97706",unread:"#0891b2"};function tT(e){return Number.isFinite(e)?Math.max(0,Math.floor(e)):0}let tR=null,tA=null,tL=new Map;function tP(){return[...document.querySelectorAll('link[rel="icon"]')]}async function tz(e,t){let n=await (!tA&&(tA=new Promise(e=>{let t=new Image;t.onload=()=>e(t),t.onerror=()=>e(null),t.src="/icons/icon-192.png"})),tA);if(!n||tR!==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,l=s?56:42,a=192-l-10,o=l+10;if(i.beginPath(),i.arc(a,o,l,0,2*Math.PI),i.fillStyle=tI[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),a,o+4)),tR!==t)return;let c=r.toDataURL("image/png");for(let e of tP())e.href=c}function tO(e){return e.isComposing||229===e.keyCode}function tW(e,t){let n=e=>{"Escape"!==e.key||(e.stopPropagation(),tO(e)||(e.preventDefault(),t()))};return e.addEventListener("keydown",n,!0),()=>e.removeEventListener("keydown",n,!0)}function tF(e,t){let n=e=>{"Escape"!==e.key||e.defaultPrevented||tO(e)||(e.preventDefault(),t())};return e.addEventListener("keydown",n,!1),()=>e.removeEventListener("keydown",n,!1)}function tD(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})}}function t_(e,t){let n=e.activeElement;return!!t&&(!n||n===e.body)&&(t.focus({preventScroll:!0}),!0)}let tB=Symbol.for("pi-web:page-id");function tH(){let e=globalThis,t=e[tB];if("string"==typeof t)return t;let n=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return e[tB]=n,n}let tU=new Set,tK=1;function tq(e){let t=e.source.deref();return t&&2!==t.readyState?t:void 0}function tV(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(let e of tU)tq(e)||tU.delete(e);let r={id:tK++,kind:e,label:n,source:new WeakRef(t),createdAt:Date.now(),opens:0,errors:0,lastOpenAt:null,lastErrorAt:null};return tU.add(r),"function"==typeof t.addEventListener&&(t.addEventListener("open",()=>{r.opens+=1,r.lastOpenAt=Date.now()}),t.addEventListener("error",()=>{r.errors+=1,r.lastErrorAt=Date.now()})),t}function tZ(){let e=[];for(let t of tU){let n=tq(t);if(!n){tU.delete(t);continue}e.push({id:t.id,kind:t.kind,label:t.label,state:1===n.readyState?"open":"connecting",createdAt:t.createdAt,opens:t.opens,errors:t.errors,lastOpenAt:t.lastOpenAt,lastErrorAt:t.lastErrorAt})}return e}let tJ={trackingSince:null,lastHiddenAt:null,lastVisibleAt:null,hiddenCount:0};function tY(){"u">typeof document&&("hidden"===document.visibilityState?(tJ.lastHiddenAt=Date.now(),tJ.hiddenCount+=1):tJ.lastVisibleAt=Date.now())}function tG(){return{state:"u">typeof document&&"hidden"===document.visibilityState?"hidden":"visible",trackingSince:tJ.trackingSince,lastHiddenAt:tJ.lastHiddenAt,lastVisibleAt:tJ.lastVisibleAt,hiddenCount:tJ.hiddenCount}}let tX={count:0,failures:0,last:null};function tQ(){return{...tX,last:tX.last?{...tX.last}:null}}function t0(){if("u"<typeof performance||"function"!=typeof performance.getEntriesByType)return null;let e=performance.getEntriesByType("navigation")[0],t=e?.nextHopProtocol;return t||("u">typeof location&&"http:"===location.protocol?"http/1.1":null)}let t1="pi-web:unread-session-ids";function t2(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}function t4(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))t2(r)&&n.set(e,r);return n}function t3(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 t8=["pointerdown","keydown","wheel","touchstart"],t6=null,t5=0,t9=null;function t7(){return"u">typeof document&&"visible"===document.visibilityState&&document.hasFocus()}function ne(){return t6??=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:12e4,r=null,i=!1,s=new Set,l=e=>null!==r&&e-r<n,a=t=>{let n=e()&&l(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();l(e)||(i=!1),r=e,a(e)},notePageChange(){let e=t();l(e)||(i=!1),a(e)},isAttended:()=>e()&&l(t()),onAttended:e=>(s.add(e),()=>s.delete(e))}}(t7,()=>performance.now())}function nt(){return 0!==t5&&ne().isAttended()}function nn(e,t,n){let r=null,i=new Set;function s(){try{return t(window.localStorage.getItem(e))}catch{return n}}function l(){return null===r&&(r=s()),r}function a(){i.forEach(e=>e())}function o(t){if(null!==t.key&&t.key!==e)return;let n=s();n!==r&&(r=n,a())}function c(e){return 0===i.size&&(window.addEventListener("storage",o),r=s()),i.add(e),()=>{i.delete(e),0===i.size&&window.removeEventListener("storage",o)}}return{use:function(){return(0,u.useSyncExternalStore)(c,l,()=>n)},set:function(t){if(t!==l()){r=t;try{window.localStorage.setItem(e,t)}catch{}a()}}}}let nr="below",ni=nn("pi-web:sidebar-files-placement",function(e){return"tab"===e?"tab":nr},nr);var ns=n(21278);let nl="(max-width: 640px)",na="(max-width: 480px)";function no(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function nc(e){return!!window.matchMedia&&window.matchMedia(e).matches}let nd=e=>no(nl,e),nu=()=>nc(nl),np=e=>no(na,e),nh=()=>nc(na);function nm(){return!1}function nf(){return(0,u.useSyncExternalStore)(nd,nu,nm)}let ng="(min-width: 1200px)",nx=e=>no(ng,e),nv=()=>nc(ng);function nb(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function ny(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function nw(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:i,getDefaultWidth:s,getMaxWidth:l,growthDirection:a,maxWidth:o,minWidth:c,collapseAt:d,onCollapse:p,persistClamp:h=!0,storageKey:m,widthRef:f}=e,g=(0,u.useRef)(null),x=(0,u.useRef)(null),v=(0,u.useRef)(!1),b=(0,u.useRef)(i),[y,w]=(0,u.useState)(i),[j,k]=(0,u.useState)(!1),[S,C]=(0,u.useState)(!1);(0,u.useEffect)(()=>{C(!0)},[]);let N=(0,u.useCallback)(()=>Math.min(o,Math.max(c,l())),[l,o,c]),E=(0,u.useCallback)(e=>nb(e,c,N()),[N,c]),M=(0,u.useCallback)(e=>{f.current=e,g.current?.style.setProperty(r,`${e}px`)},[r,f]),$=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{forcePersist:n=!1,persist:r=!0}=t,i=E(e),s=i!==f.current;return M(i),w(i),h?r&&(s||n)&&ny(m,i):n&&(b.current=nb(e,c,o),ny(m,b.current)),i},[M,E,o,c,h,m,f]),I=(0,u.useCallback)(()=>{$(h||x.current?f.current:b.current)},[$,h,f]),T=(0,u.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),R=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=x.current;if(n&&n.pointerId===e){x.current=null,T(n),k(!1),!t&&p&&void 0!==d&&n.requestedWidth<d?($(h?n.startWidth:b.current,{forcePersist:!0}),p()):$(f.current,{forcePersist:h||f.current!==n.startWidth});try{n.target.hasPointerCapture(e)&&n.target.releasePointerCapture(e)}catch{}}},[d,$,p,h,T,f]),A=(0,u.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=x.current;t&&R(t.pointerId,!0);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),x.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:f.current,requestedWidth:f.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",k(!0)},[n,R,f]),L=(0,u.useCallback)(e=>{let t=x.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void R(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX;t.requestedWidth=t.startWidth+(i-t.startPosition)*r;let s=E(t.requestedWidth);M(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",`${s} px`)},[M,n,E,R,a]),P=(0,u.useCallback)(e=>{R(e.pointerId)},[R]),z=(0,u.useCallback)(e=>{R(e.pointerId,!0)},[R]),O=(0,u.useCallback)(e=>{R(e.pointerId,!0)},[R]),W=(0,u.useCallback)(()=>{$(s?.()??i,{forcePersist:!0})},[$,i,s]),F=(0,u.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",s="vertical"===n?"ArrowUp":"ArrowLeft",l=h?f.current:Math.max(f.current,b.current);e.key===(r?i:s)?(e.preventDefault(),$(l+t,{forcePersist:!0})):e.key===(r?s:i)?(e.preventDefault(),$(f.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),$(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),$(Math.max(l,N()),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),W())},[n,$,N,a,c,h,W,f]);return(0,u.useEffect)(()=>{if(v.current)return;v.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(m),t=e??s?.()??i;if(!h){b.current=nb(t,c,o),$(b.current,{persist:!1});return}let n=$(t,{persist:!1});null!==e&&e!==n&&ny(m,n)},[$,i,s,o,c,h,m]),(0,u.useEffect)(()=>{if(!v.current)return;I();let e=()=>{I()};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[I]),(0,u.useEffect)(()=>{if(!j)return;let e=()=>{let e=x.current;e&&R(e.pointerId,!0)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[R,j]),(0,u.useEffect)(()=>()=>{let e=x.current;e&&(x.current=null,T(e))},[T]),{isResizing:j,panelRef:g,reclampWidth:I,resetWidth:W,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":S?N():o,"aria-valuemin":c,"aria-valuenow":y,"aria-valuetext":`${y} px`,onDoubleClick:W,onKeyDown:F,onLostPointerCapture:O,onPointerCancel:z,onPointerDown:A,onPointerMove:L,onPointerUp:P,role:"separator",tabIndex:0},width:y}}function nj(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];(0,u.useEffect)(()=>{if(!t)return;let n=null,r=null,i=!1,s=null,l=()=>{null!==s&&(clearTimeout(s),s=null)},a=()=>{n&&(l(),n.classList.add("scrollbar-visible"))},o=()=>{n&&(l(),s=setTimeout(()=>{s=null,n?.classList.remove("scrollbar-visible")},500))},c=()=>{a(),o()},d=()=>{if(!i){if(!(n=e.current)){r=requestAnimationFrame(d);return}n.addEventListener("pointerenter",a),n.addEventListener("pointerleave",o),n.addEventListener("scroll",c)}};return d(),()=>{i=!0,null!==r&&cancelAnimationFrame(r),n?.removeEventListener("pointerenter",a),n?.removeEventListener("pointerleave",o),n?.removeEventListener("scroll",c),l(),n?.classList.remove("scrollbar-visible")}},[t,e])}let nk="/api/sessions/ui-state";async function nS(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 nC(e){return e instanceof Error?e.message:String(e)}async function nN(e){if(!e.ok)throw Error(await nS(e));let t=await e.json(),n=t&&"object"==typeof t?function(e){if(!es(e)||void 0!==e.version&&1!==e.version||void 0!==e.sessions&&!es(e.sessions)||void 0!==e.projects&&!es(e.projects))return null;let t=ey(),n=e.revision;for(let[r,i]of("number"==typeof n&&Number.isSafeInteger(n)&&n>=0&&(t.revision=n),Object.entries(e.sessions??{}))){if(!ea(r))continue;let e=function(e){if(!es(e))return null;let t={};return el(e.pinnedAt)&&(t.pinnedAt=e.pinnedAt),el(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(!eo(n))continue;let e=es(r)&&el(r.pinnedAt)&&eo(r.root)?{pinnedAt:r.pinnedAt,root:r.root}:null;e&&(t.projects[n]=e)}if(es(e.removedProjects)){let n={};for(let[t,r]of Object.entries(e.removedProjects))eo(t)&&el(r)&&(n[t]=r);Object.keys(n).length&&(t.removedProjects=n)}if(Array.isArray(e.projectOrder)){let n=new Set,r=ex(e.projectOrder.filter(e=>!(!eo(e)||n.has(e))&&(n.add(e),!0)));r.length>0&&(t.projectOrder=r)}if(es(e.projectNames)){let n={},r=0,i=1;for(let[t,s]of Object.entries(e.projectNames)){let e=ed(s);if(!eo(t)||"string"!=typeof e)continue;let l=ev(t,e);eb(r+1,i+l)&&(n[t]=e,r++,i+=l)}r>0&&(t.projectNames=n)}if(es(e.readAt)){let n={};for(let[t,r]of Object.entries(e.readAt))ea(t)&&el(r)&&(n[t]=r);let r=ew(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}async function nE(e){let t;try{t=await e.json()}catch(t){if(!(t instanceof SyntaxError))throw t;throw Error(`HTTP ${e.status}`)}let n=null!==t&&"object"==typeof t?t.error:void 0;if("string"==typeof n&&n)throw Error(n);if(!e.ok)throw Error(`HTTP ${e.status}`);return t}let nM={overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},n$={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},nI={padding:"6px 16px",borderRadius:6,fontSize:13},nT={...nI,border:0,background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600},nR={...nI,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)"};async function nA(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`);return await nE(n)}async function nL(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 nE(n);if(!r.path)throw Error(`HTTP ${n.status}`);return r.path}function nP(){return(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function nz(){return(0,d.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,d.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,d.jsx)("path",{d:"M2 9h12"}),(0,d.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function nO(e){let{onCancel:t,onSelect:n,initialPath:r,busy:i=!1,error:s}=e,{t:l}=(0,ns.s)(),[a,o]=(0,u.useState)(null),[c,p]=(0,u.useState)(""),[h,m]=(0,u.useState)(null),[f,x]=(0,u.useState)(r??""),[v,b]=(0,u.useState)([]),[y,w]=(0,u.useState)(null),[j,k]=(0,u.useState)(null),[S,C]=(0,u.useState)(!0),[N,E]=(0,u.useState)(!1),[M,$]=(0,u.useState)(""),[I,T]=(0,u.useState)(null),[R,A]=(0,u.useState)(!1),L=(0,u.useRef)(!1),P=(0,u.useRef)(!1),z=(0,u.useRef)(null),O=(0,u.useRef)(!1),W=(0,u.useCallback)(async e=>{C(!0),k(null);try{let t=await nA(e),n=t.path??e??"/";return p(n),m(t.parentPath??null),x(n),b(t.directories??[]),w(t.drives??null),n}catch(e){return k(e instanceof Error?e.message:String(e)),null}finally{C(!1)}},[]);(0,u.useEffect)(()=>{o(document.body),W(r||void 0)},[r,W]),(0,u.useEffect)(()=>(O.current=!0,()=>{O.current=!1}),[]),(0,u.useEffect)(()=>{(j||s)&&z.current?.focus()},[j,s]);let F=()=>{R||(E(!1),$(""),T(null))},D=async()=>{let e=M.trim();if(c&&e&&!R){A(!0),T(null);try{let t=await nL(c,e);E(!1),$(""),await W(t)}catch(e){T(e instanceof Error?e.message:String(e))}finally{A(!1)}}},_=f.trim(),B=_!==c,H=!!_&&!i&&!S,U=!!c&&!B&&!i&&!S,K=!!h||/^[a-zA-Z]:[\\/]?$/.test(c),q=async()=>{let e=B?await W(_):c;e&&O.current&&n(e)};return a?(0,g.createPortal)((0,d.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onPointerDown:e=>{L.current=e.target===e.currentTarget},onClick:e=>{let n=L.current;L.current=!1,n&&e.target===e.currentTarget&&!i&&t()},onPointerCancel:()=>{L.current=!1},onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),!e.nativeEvent.isComposing&&229!==e.keyCode&&(e.preventDefault(),i||t()))},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,d.jsxs)("div",{className:"directory-picker-panel",style:{...nM,position:"relative",width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{minWidth:0,flex:1},children:(0,d.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:l("directoryPicker.selectDirectory")})}),(0,d.jsx)("button",{type:"button",onClick:t,disabled:i,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:i?"default":"pointer",opacity:i?.5:1},children:"\xd7"})]}),(0,d.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&W(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void W(h??void 0),disabled:S||!K,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:K?"pointer":"default",opacity:K?1:.45},children:(0,d.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,d.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,d.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,d.jsx)("input",{ref:z,className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:l("directoryPicker.pathPlaceholder"),autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{x(e.target.value),k(null)},style:{...n$,minWidth:0,flex:1}}),(0,d.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:S||!f.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:S||!f.trim()?"default":"pointer",opacity:S||!f.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,d.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[S?(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==y?(0,d.jsx)(d.Fragment,{children:y.length>0?y.map(e=>(0,d.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void W(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,d.jsx)(nz,{}),(0,d.jsx)("span",{children:e.name})]},e.path)):(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):v.length>0?v.map(e=>(0,d.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void W(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,d.jsx)(nP,{}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,d.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noSubdirectories")}),(j||s)&&(0,d.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:j??s})]}),(0,d.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,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>{E(!0),T(null)},disabled:!U,style:{...nR,marginRight:"auto",opacity:U?1:.6,cursor:U?"pointer":"default"},children:l("directoryPicker.newDirectory")}),(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:t,disabled:i,style:{...nR,cursor:i?"default":"pointer"},children:l("i18n.cancel")}),(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>void q(),disabled:!H,title:B&&_?l("directoryPicker.selectTypedPath",{path:_}):l("directoryPicker.selectCurrentDirectory"),style:{...nT,opacity:H?1:.6,cursor:H?"pointer":"default"},children:l(i?"i18n.checking":"directoryPicker.selectThisFolder")})]}),N&&(0,d.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=>{P.current=e.target===e.currentTarget},onClick:e=>{let t=P.current;P.current=!1,t&&e.target===e.currentTarget&&F()},onPointerCancel:()=>{P.current=!1},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||"Escape"===e.key&&F()},children:(0,d.jsxs)("form",{role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.createDirectory"),onSubmit:e=>{e.preventDefault(),D()},style:{...nM,width:400,maxWidth:"100%"},children:[(0,d.jsx)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",color:"var(--text)",fontSize:15,fontWeight:700},children:l("directoryPicker.createDirectory")}),(0,d.jsxs)("div",{style:{padding:"12px 18px"},children:[(0,d.jsx)("label",{htmlFor:"new-directory-name",style:{display:"block",marginBottom:6,color:"var(--text-muted)",fontSize:11},children:l("directoryPicker.directoryName")}),(0,d.jsx)("input",{id:"new-directory-name",value:M,autoFocus:!0,autoComplete:"off",spellCheck:!1,placeholder:l("directoryPicker.directoryNamePlaceholder"),onChange:e=>{$(e.target.value),T(null)},disabled:R,className:"directory-picker-path",style:{...n$,width:"100%",boxSizing:"border-box"}}),I&&(0,d.jsx)("div",{style:{marginTop:7,color:"#dc2626",fontSize:11,lineHeight:1.35},children:I}),(0,d.jsxs)("div",{style:{display:"flex",gap:6,marginTop:10},children:[(0,d.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:R||!M.trim(),style:{...nT,flex:1,opacity:R?.65:1,cursor:R||!M.trim()?"default":"pointer"},children:l(R?"directoryPicker.creating":"directoryPicker.create")}),(0,d.jsx)("button",{className:"directory-picker-action",type:"button",onClick:F,disabled:R,style:{...nR,flex:1,cursor:R?"default":"pointer"},children:l("i18n.cancel")})]})]})]})})]})}),a):null}function nW(e){let{strokeWidth:t=1.7,...n}=e;return(0,d.jsxs)(nD,{...n,strokeWidth:t,children:[(0,d.jsx)("circle",{cx:"9",cy:"8",r:"3"}),(0,d.jsx)("path",{d:"M3 20v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2M16 5.2a3 3 0 0 1 0 5.6M18 14.2a4 4 0 0 1 3 3.8v2"})]})}function nF(e){let{strokeWidth:t=1.7,...n}=e;return(0,d.jsxs)(nD,{...n,strokeWidth:t,children:[(0,d.jsx)("path",{d:"M4 8a8.5 8.5 0 1 1-1 4"}),(0,d.jsx)("path",{d:"M4 3.5V8h4.5M12 7.5v5l3.5 2"})]})}function nD(e){let{size:t=13,className:n,label:r,strokeWidth:i=2,children:s}=e;return(0,d.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:n,...r?{role:"img","aria-label":r}:{"aria-hidden":!0},children:s})}function n_(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("path",{d:"M12 5v14M5 12h14"})})}function nB(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("circle",{cx:"5",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"}),(0,d.jsx)("circle",{cx:"19",cy:"12",r:"1.4",fill:"currentColor",stroke:"none"})]})}function nH(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"5",rx:"1"}),(0,d.jsx)("path",{d:"M5 9v9a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9"}),(0,d.jsx)("path",{d:"M10 13h4"})]})}function nU(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]})}function nK(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M12 17v5"}),(0,d.jsx)("path",{d:"M9 10.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.8a2 2 0 0 0-1.1-1.8l-1.8-.9a2 2 0 0 1-1.1-1.8V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"})]})}function nq(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M12 17v5"}),(0,d.jsx)("path",{d:"M15 9.3V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8.5"}),(0,d.jsx)("path",{d:"m2 2 20 20"}),(0,d.jsx)("path",{d:"M9 9v1.8a2 2 0 0 1-1.1 1.8l-1.8.9A2 2 0 0 0 5 15.2V16a1 1 0 0 0 1 1h11"})]})}function nV(e){let{strokeWidth:t,...n}=e;return(0,d.jsx)(nD,{...n,strokeWidth:t,children:(0,d.jsx)("path",{d:"m9 6 6 6-6 6"})})}function nZ(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function nJ(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("circle",{cx:"6",cy:"5",r:"2.5"}),(0,d.jsx)("circle",{cx:"18",cy:"5",r:"2.5"}),(0,d.jsx)("circle",{cx:"12",cy:"19",r:"2.5"}),(0,d.jsx)("path",{d:"M6 7.5v1.5a3 3 0 0 0 3 3h6a3 3 0 0 0 3-3V7.5"}),(0,d.jsx)("path",{d:"M12 12v4.5"})]})}function nY(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M14 4h6v6"}),(0,d.jsx)("path",{d:"M20 4 11 13"}),(0,d.jsx)("path",{d:"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"})]})}function nG(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M3 6h18"}),(0,d.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,d.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,d.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}function nX(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}function nQ(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("circle",{cx:"12",cy:"12",r:"4.5",fill:"currentColor",stroke:"none"})})}function n0(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("circle",{cx:"12",cy:"12",r:"4.5"})})}function n1(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("path",{d:"M20 6 9 17l-5-5"})})}function n2(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}function n4(e){let{open:t,...n}=e;return(0,d.jsxs)(nD,{...n,strokeWidth:1.7,children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"3"}),(0,d.jsx)("path",{d:"M9 4v16"}),(0,d.jsx)("path",{d:t?"m16 9-3 3 3 3":"m13 9 3 3-3 3"})]})}function n3(e){let{open:t=!1,...n}=e;return(0,d.jsx)(nD,{...n,children:(0,d.jsx)("path",{d:t?"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.5 6a2 2 0 0 1-1.94 1.5H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v2":"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})})}function n8(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M12 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-6"}),(0,d.jsx)("path",{d:"m16 3 5 5M10 14l1-4L18 3a2.12 2.12 0 0 1 3 3l-7 7Z"})]})}function n6(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M3 8a2 2 0 0 1 2-2h3.4l1.9 1.9H19a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}),(0,d.jsx)("path",{d:"M12 11v5M9.5 13.5h5"})]})}function n5(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,d.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function n9(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,d.jsx)("path",{d:"m20 20-4-4"})]})}function n7(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,d.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,d.jsx)("path",{d:"M12 3v12"})]})}function re(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]})}function rt(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,d.jsx)("path",{d:"M3 12h6M15 12h6"})]})}function rn(e){return(0,d.jsxs)(nD,{...e,children:[(0,d.jsx)("path",{d:"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function rr(e){return(0,d.jsx)(nD,{...e,children:(0,d.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ri(e){let{className:t,...n}=e;return(0,d.jsx)(nD,{...n,strokeWidth:2.8,className:t?`sidebar-spin ${t}`:"sidebar-spin",children:(0,d.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4"})})}var rs=n(77476),rl=n.n(rs);function ra(e){let{projects:t,initialPath:n,onCancel:r,onCreate:i}=e,{t:s}=(0,ns.s)(),l=(0,u.useId)(),a=(0,u.useId)(),o=(0,u.useId)(),c=(0,u.useRef)(null),p=(0,u.useRef)(null),h=(0,u.useRef)(null),[m,f]=(0,u.useState)(null),[x,v]=(0,u.useState)(""),[b,y]=(0,u.useState)(""),[w,j]=(0,u.useState)(!1),[k,S]=(0,u.useState)(!1),[C,N]=(0,u.useState)(null),E=(0,u.useRef)(!1),M=(0,u.useRef)(!1),$=(0,u.useRef)({browsing:w,onCancel:r});function I(e){if(y(e),!E.current){let n=t.find(t=>t.root===e);v(n?.alias??eW(e))}N(null),j(!1),requestAnimationFrame(()=>h.current?.focus({preventScroll:!0}))}async function T(){if(!M.current){M.current=!0,S(!0),N(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();if(!e.ok||t.error||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);I(t.cwd)}catch(e){N(e instanceof Error?e.message:String(e))}finally{M.current=!1,S(!1)}}}async function R(){let e=ed(x);if(!M.current&&e&&b){M.current=!0,S(!0),N(null);try{let t=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:b})}),n=await t.json();if(!t.ok||n.error||!n.cwd||!n.projectRoot||!n.projectKey)throw Error(n.error??`HTTP ${t.status}`);await i({cwd:n.cwd,projectRoot:n.projectRoot,projectKey:n.projectKey},e)||N(s("projectCreate.saveFailed"))}catch(e){N(e instanceof Error?e.message:String(e))}finally{M.current=!1,S(!1)}}}$.current={browsing:w,onCancel:r},(0,u.useEffect)(()=>{f(document.body)},[]),(0,u.useLayoutEffect)(()=>{if(!m)return;let e=tD(document,c.current);p.current?.focus({preventScroll:!0});let t=e=>{$.current.browsing||"Escape"!==e.key||(e.stopPropagation(),!e.isComposing&&229!==e.keyCode&&(e.preventDefault(),M.current||$.current.onCancel()))};return document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("keydown",t,!0),e()}},[m]);let A=!!ed(x);return m?(0,g.createPortal)((0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:rl().backdrop,onClick:e=>{e.target!==e.currentTarget||M.current||r()},children:(0,d.jsxs)("div",{ref:c,className:rl().dialog,role:"dialog","aria-modal":"true","aria-labelledby":l,"aria-busy":k,tabIndex:-1,inert:w,"aria-hidden":w||void 0,onKeyDown:e=>{if("Tab"!==e.key)return;let t=Array.from(e.currentTarget.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), summary, [tabindex="0"]')).filter(e=>e.getClientRects().length>0),n=t[0],r=t[t.length-1];n?e.shiftKey&&(document.activeElement===n||document.activeElement===c.current)?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n.focus()):e.preventDefault()},children:[(0,d.jsxs)("header",{className:rl().header,children:[(0,d.jsx)("h2",{id:l,children:s("projectCreate.title")}),(0,d.jsx)("button",{className:rl().close,type:"button",onClick:r,disabled:k,"aria-label":s("i18n.close"),children:(0,d.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,d.jsxs)("form",{onSubmit:e=>{e.preventDefault(),R()},children:[(0,d.jsxs)("label",{className:rl().nameField,htmlFor:a,children:[(0,d.jsx)("span",{className:rl().nameIcon,children:(0,d.jsx)(n3,{size:23})}),(0,d.jsx)("input",{ref:p,id:a,value:x,placeholder:s("projectCreate.name"),"aria-label":s("projectCreate.name"),disabled:k,autoComplete:"off",onChange:e=>{E.current=!0,v(e.target.value),N(null)}})]}),x.trim()&&!A&&(0,d.jsx)("p",{className:rl().error,role:"alert",children:s("projectCreate.invalidName",{max:80})}),(0,d.jsxs)("section",{className:rl().sources,"aria-labelledby":o,children:[(0,d.jsx)("h3",{id:o,children:s("projectCreate.sourceFolder")}),(0,d.jsx)("div",{className:`${rl().sourceCard}${b?` ${rl().hasFolder}`:""}`,children:b?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:rl().folderRow,children:[(0,d.jsx)(n3,{size:25}),(0,d.jsxs)("div",{className:rl().folderText,children:[(0,d.jsx)("strong",{children:eW(b)}),(0,d.jsx)("span",{children:b})]}),(0,d.jsx)("button",{type:"button",className:rl().close,disabled:k,"aria-label":s("projectCreate.removeFolder"),onClick:()=>{y(""),N(null),E.current||v("")},children:"\xd7"})]}),(0,d.jsxs)("button",{ref:h,className:rl().add,type:"button",disabled:k,onClick:()=>j(!0),children:[(0,d.jsx)(n3,{size:18}),s("projectCreate.changeFolder")]})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("p",{children:s("projectCreate.addOnComputer")}),(0,d.jsxs)("button",{ref:h,className:rl().add,type:"button",disabled:k,onClick:()=>j(!0),children:[(0,d.jsx)(n6,{size:21}),s("projectCreate.addFolder")]})]})}),(0,d.jsxs)("div",{className:rl().sourceOptions,children:[(0,d.jsx)("button",{type:"button",disabled:k,onClick:()=>void T(),children:s("sidebar.useDefaultDirectory")}),t.length>0&&(0,d.jsxs)("label",{className:rl().recent,children:[(0,d.jsx)(n_,{size:14}),(0,d.jsxs)("select",{"aria-label":s("projectCreate.existingFolder"),disabled:k,value:"",onChange:e=>I(e.target.value),children:[(0,d.jsx)("option",{value:"",disabled:!0,children:s("projectCreate.existingFolder")}),t.map(e=>(0,d.jsxs)("option",{value:e.root,children:[e.alias??eW(e.root)," — ",e.root]},e.key))]})]})]}),(0,d.jsx)("p",{className:rl().hint,children:s("projectCreate.folderHint")})]}),C&&(0,d.jsx)("p",{className:rl().error,role:"alert",children:C}),(0,d.jsxs)("footer",{className:rl().footer,children:[(0,d.jsx)("button",{className:rl().cancel,type:"button",disabled:k,onClick:r,children:s("i18n.cancel")}),(0,d.jsx)("button",{className:rl().submit,type:"submit",disabled:k||!b||!A,children:k?s("projectCreate.creating"):s("projectCreate.title")})]})]})]})}),w&&(0,d.jsx)(nO,{initialPath:b||n,onSelect:I,onCancel:()=>{j(!1),requestAnimationFrame(()=>h.current?.focus({preventScroll:!0}))}})]}),m):null}function ro(e){let{onClick:t,title:n}=e;return(0,d.jsx)("button",{type:"button",onClick:t,title:n,"aria-label":n,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"m6 6 12 12"}),(0,d.jsx)("path",{d:"m18 6-12 12"})]})})}let rc="/icons/catppuccin";function rd(e){let{name:t,size:n=14}=e,r={width:n,height:n,"--catppuccin-icon-light":`url(${rc}/latte/${t}.svg)`,"--catppuccin-icon-dark":`url(${rc}/mocha/${t}.svg)`};return(0,d.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:r})}function ru(e){let{size:t=14,open:n=!1}=e;return(0,d.jsx)(rd,{name:n?"_folder_open":"_folder",size:t})}function rp(e){let{size:t=14}=e;return(0,d.jsx)(rd,{name:"_file",size:t})}let rh={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function rm(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:14,n=e.toLowerCase(),r="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(r)return(0,d.jsx)(rd,{name:r,size:t});let i=rh[n.split(".").pop()??""];return i?(0,d.jsx)(rd,{name:i,size:t}):(0,d.jsx)(rp,{size:t})}function rf(e){let{open:t,children:n}=e,[r,i]=(0,u.useState)(t),s=(0,u.useRef)(null),l=(0,u.useRef)(t),a=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let e,n=s.current;if(!n||l.current===t)return;l.current=t;let r=a.current?n.getBoundingClientRect().height:t?0:n.scrollHeight,o=a.current?getComputedStyle(n).opacity:t?.84:1;a.current?.cancel(),a.current=null;let c=window.matchMedia("(prefers-reduced-motion: reduce)"),d=()=>{e?.disconnect(),a.current?.cancel(),a.current=null,n.style.overflow="",i(t)};if(c.matches||document.hidden||"function"!=typeof n.animate)return void d();t&&i(!0),n.style.overflow="hidden";let u=n.animate([{height:`${r}px`,opacity:o},{height:`${t?n.scrollHeight:0}px`,opacity:+!!t}],{duration:200,easing:"cubic-bezier(.2, .8, .2, 1)",fill:"both"});if(a.current=u,u.onfinish=d,t&&"u">typeof ResizeObserver&&n.firstElementChild){let t=n.scrollHeight;(e=new ResizeObserver(()=>{let e=n.firstElementChild?.getBoundingClientRect().height??0;if(1>Math.abs(e-t)||a.current!==u)return;t=e;let r=n.getBoundingClientRect().height,i=getComputedStyle(n).opacity;u.effect.setKeyframes([{height:`${r}px`,opacity:i},{height:`${t}px`,opacity:1}]),u.currentTime=0})).observe(n.firstElementChild)}let p=()=>{c.matches&&d()},h=()=>{document.hidden&&d()};return c.addEventListener("change",p),document.addEventListener("visibilitychange",h),()=>{e?.disconnect(),c.removeEventListener("change",p),document.removeEventListener("visibilitychange",h),u.onfinish=null}},[t]),(0,u.useLayoutEffect)(()=>()=>{a.current?.cancel()},[]),(0,d.jsx)("div",{ref:s,className:"ui-disclosure",hidden:!t&&!r,inert:!t,"aria-hidden":!t||void 0,children:(t||r)&&(0,d.jsx)("div",{className:"ui-disclosure-body",children:"function"==typeof n?n():n})})}function rg(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function rx(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function rv(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function rb(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function ry(e,t,n,r){return new Promise((i,s)=>{let l=new FormData;t.forEach(e=>l.append("files",e,e.name));let a=new XMLHttpRequest;a.open("POST",`/api/files/${e1(e)}?type=upload&conflict=${n}`),a.upload.onprogress=e=>{r&&e.lengthComputable&&e.total>0&&r(Math.round(e.loaded/e.total*100))},a.onerror=()=>s(Error("Network error while uploading files")),a.onabort=()=>s(Error("Upload cancelled")),a.onload=()=>{let e={};try{e=JSON.parse(a.responseText)}catch{a.responseText&&(e.error=a.responseText)}i({status:a.status,data:e})},a.send(l)})}function rw(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t}function rj(e){return Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)}function rk(e){let t=[];for(let n of Array.from(e.items)){if("file"!==n.kind)continue;let e=n.webkitGetAsEntry?.();if(e?.isDirectory){t.push({kind:"folder",name:e.name});continue}let r=n.getAsFile();r&&t.push({kind:"file",file:r})}return t.length>0?t:Array.from(e.files).map(e=>({kind:"file",file:e}))}let rS=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=new Map;return{save(n,r){if(t.delete(n),0!==r.size)for(let i of(t.set(n,new Set(r)),t.keys())){if(t.size<=e)break;t.delete(i)}},restore:e=>new Set(t.get(e))}}();async function rC(e,t){let n=`${t} (HTTP ${e.status})`;try{let t=await e.json();t.error&&(n=t.error)}catch{}return Error(n)}async function rN(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e1(e),r=await fetch(`/api/files/${n}?type=list${t?"&hidden=1":""}`);if(!r.ok)throw await rC(r,"Failed to load files");return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:e8(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir,outsideLinkTarget:t.outsideLinkTarget,outsideLinkEncloses:t.outsideLinkEncloses,hidden:t.hidden}))}async function rE(e,t){let n=await fetch(`/api/files/${e1(e)}?type=allow-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t})});if(!n.ok)throw await rC(n,"Failed to allow the linked folder")}async function rM(e,t){let n=new URLSearchParams({cwd:e}),r=await fetch(`/api/git/status?${n.toString()}`,{signal:t});if(!r.ok)throw Error(`Failed to load Git status (HTTP ${r.status})`);return r.json()}let r$={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},rI={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function rT(e){let{status:t,t:n}=e;return(0,d.jsx)("span",{title:n(r$[t.status]),"aria-label":n(r$[t.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:rI[t.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:t.code})}function rR(e){let{size:t=11}=e;return(0,d.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,d.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function rA(e){let{size:t=11}=e;return(0,d.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M15 3h6v6"}),(0,d.jsx)("path",{d:"M10 14 21 3"}),(0,d.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})}let rL={ignored:"files.hiddenIgnored",excluded:"files.hiddenExcluded"};function rP(e){let{node:t,depth:n,cwd:r,onOpenFile:i,onAtMention:s,expandedPaths:l,onToggleExpanded:a,refreshToken:o,highlightedPaths:c,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:m=!1,parentHidden:f,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b}=e,y=l.has(t.fullPath),w=t.hidden??f,j=t.isDir&&g===t.fullPath,k=c.has(t.fullPath),S=e0(t.fullPath),C=p.get(S),N=t.isDir&&(void 0!==C||h.has(S)),[E,M]=(0,u.useState)(t.children??[]),[$,I]=(0,u.useState)(t.loaded??!1),[T,R]=(0,u.useState)(!1),[A,L]=(0,u.useState)(null),[P,z]=(0,u.useState)(!1),[O,W]=(0,u.useState)(null),[F,D]=(0,u.useState)(!1),[_,B]=(0,u.useState)(null),H=t.outsideLinkTarget&&t.outsideLinkTarget!==O?t.outsideLinkTarget:null;(0,u.useEffect)(()=>{W(null),B(null)},[t.outsideLinkTarget]);let U=(0,u.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!$||e){R(!0),L(null);try{let e=await rN(t.fullPath,m);M(e),I(!0)}catch(e){L(e instanceof Error?e.message:String(e))}finally{R(!1)}}},[$,t.fullPath,m]),K=(0,u.useRef)(m);(0,u.useEffect)(()=>{K.current===m||(K.current=m,$&&(y&&!H?U(!0):I(!1)))},[m]),(0,u.useEffect)(()=>{t.isDir&&y&&!$&&!H&&U()},[]),(0,u.useEffect)(()=>{void 0!==o&&$&&!H&&(y?U(!0):I(!1))},[o]);let q=(0,u.useCallback)(()=>{if(t.isDir){let e=!y;a(t.fullPath,e),!e||$||H||U()}else i(t.fullPath,t.name)},[t.isDir,t.fullPath,t.name,$,y,H,U,i,a]),V=(0,u.useCallback)(async e=>{if((e.stopPropagation(),H)&&(!t.outsideLinkEncloses||window.confirm(b("files.allowEnclosingLinkConfirm",{target:H})))){D(!0),B(null);try{await rE(t.fullPath,H),W(H),await U(!0)}catch(e){B(e instanceof Error?e.message:String(e))}finally{D(!1)}}},[t.fullPath,t.outsideLinkEncloses,H,U,b]);return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{onClick:q,onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),onDragOver:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="copy",v?.(t.fullPath))}:void 0,onDrop:t.isDir?e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),v?.(null),x?.(t.fullPath,rk(e.dataTransfer)))}:void 0,style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:j?"color-mix(in srgb, var(--accent) 16%, transparent)":P?"var(--bg-hover)":"transparent",outline:j?"1px dashed var(--accent)":"none",outlineOffset:-1,borderRadius:4,userSelect:"none"},children:[t.isDir&&(0,d.jsx)("svg",{className:"file-tree-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:y?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,d.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!t.isDir&&(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:w?.55:1},children:t.isDir?(0,d.jsx)(ru,{size:14,open:y}):rm(t.name,14)}),(0,d.jsx)("span",{className:"file-tree-name","data-hidden-reason":w,style:{fontSize:12,color:w?"var(--text-muted)":"var(--text)",opacity:w?.55:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:w?`${t.fullPath}
|
|
4
|
+
${b(rL[w])}`:t.fullPath,children:t.name}),!P&&H&&(0,d.jsx)("span",{title:b("files.outsideLink",{target:H}),"aria-label":b("files.outsideLink",{target:H}),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)"},children:(0,d.jsx)(rA,{})}),k&&(0,d.jsx)("span",{title:b("files.newlyUploaded"),"aria-label":b("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!P&&!t.isDir&&C&&(0,d.jsx)(rT,{status:C,t:b}),!P&&N&&(0,d.jsx)("span",{title:b("files.containsChangedFiles"),"aria-label":b("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),T&&(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,d.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),s&&P&&(0,d.jsxs)("button",{onClick:e=>{e.stopPropagation(),s(e3(t.fullPath,r),t.isDir)},title:b("files.insertPath"),style:{position:"absolute",right:t.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,d.jsx)(rR,{}),b("files.mention")]}),P&&!t.isDir&&(0,d.jsx)("a",{href:`/api/files/${e1(t.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:b("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,d.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,d.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),t.isDir&&y&&H&&(0,d.jsxs)("div",{style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:5,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,fontSize:11,color:"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{wordBreak:"break-all"},children:b("files.outsideLink",{target:H})}),t.outsideLinkEncloses&&(0,d.jsx)("span",{style:{color:"#f59e0b"},children:b("files.outsideLinkEncloses")}),(0,d.jsx)("button",{type:"button",onClick:V,disabled:F,title:b("files.allowOutsideLinkTitle",{target:H}),style:{height:"calc(var(--file-row-height) - 4px)",padding:"0 8px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:F?"default":"pointer",opacity:F?.6:1,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:b("files.allowOutsideLink")}),_&&(0,d.jsx)("span",{role:"alert",style:{color:"#f87171",wordBreak:"break-word"},children:_})]}),t.isDir&&!H&&(0,d.jsxs)(rf,{open:y,children:[E.map(e=>(0,d.jsx)(rP,{node:e,depth:n+1,cwd:r,onOpenFile:i,onAtMention:s,expandedPaths:l,onToggleExpanded:a,refreshToken:o,highlightedPaths:c,gitStatusByPath:p,changedDirectoryPaths:h,showHidden:m,parentHidden:w,dropTargetPath:g,onDropFiles:x,onDropTargetChange:v,t:b},e.fullPath)),0===E.length&&$&&!A&&(0,d.jsx)("div",{style:{paddingLeft:8+(n+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),A&&(0,d.jsx)("div",{role:"alert",style:{paddingLeft:8+(n+1)*14,paddingRight:8,paddingTop:3,paddingBottom:3,fontSize:11,color:"#f87171",wordBreak:"break-word"},children:A})]})]})}function rz(e){let{status:t,cwd:n,onOpenFile:r,onAtMention:i,t:s,depth:l=0,treeMode:a=!1}=e,[o,c]=(0,u.useState)(!1),p=e2(t.filePath),h=e3(t.filePath,n),m=h.lastIndexOf("/"),f=!a&&m>=0?h.slice(0,m+1):"",g=a?p:m>=0?h.slice(m+1):h;return(0,d.jsxs)("div",{onClick:()=>r(t.filePath,p,{modeHint:"diff"}),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),title:t.filePath,style:{display:"flex",alignItems:"center",gap:a?4:6,paddingLeft:a?8+14*l:10,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:o?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,d.jsx)(rT,{status:t,t:s}),a&&(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:rm(p,13)}),(0,d.jsxs)("span",{title:t.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[f&&(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:f}),(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:+!!a,maxWidth:"100%"},children:g})]}),i&&o&&(0,d.jsxs)("button",{onClick:e=>{e.stopPropagation(),i(h,!1)},title:s("files.insertPath"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:"calc(var(--file-row-height) - 4px)",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,d.jsx)(rR,{}),s("files.mention")]})]})}function rO(e){let{node:t,depth:n,open:r,onToggle:i}=e,[s,l]=(0,u.useState)(!1);return(0,d.jsxs)("div",{onClick:()=>i(t.path,!r),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),title:t.path,style:{display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*n,paddingRight:8,height:"var(--file-row-height)",cursor:"pointer",background:s?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,d.jsx)("svg",{className:"file-tree-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:r?"rotate(90deg)":"none",transition:"transform 0.1s"},"aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,d.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:(0,d.jsx)(ru,{size:14,open:r})}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name})]})}function rW(e){let{nodes:t,depth:n,cwd:r,statusByPath:i,collapsedPaths:s,onToggleExpanded:l,onOpenFile:a,onAtMention:o,t:c}=e;return(0,d.jsx)(d.Fragment,{children:t.map(e=>{if(e.isDir){let t=!s.has(e.path);return(0,d.jsxs)("div",{children:[(0,d.jsx)(rO,{node:e,depth:n,open:t,onToggle:l}),(0,d.jsx)(rf,{open:t,children:(0,d.jsx)(rW,{nodes:e.children,depth:n+1,cwd:r,statusByPath:i,collapsedPaths:s,onToggleExpanded:l,onOpenFile:a,onAtMention:o,t:c})})]},`dir:${e.path}`)}let t=i.get(e.path);return t?(0,d.jsx)(rz,{status:t,cwd:r,onOpenFile:a,onAtMention:o,t:c,depth:n,treeMode:!0},t.filePath):null})})}function rF(e){let{mode:t}=e;return"tree"===t?(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M8 6h13"}),(0,d.jsx)("path",{d:"M8 12h13"}),(0,d.jsx)("path",{d:"M8 18h13"}),(0,d.jsx)("path",{d:"M3 6h.01"}),(0,d.jsx)("path",{d:"M3 12h.01"}),(0,d.jsx)("path",{d:"M3 18h.01"})]}):(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M6 3v12"}),(0,d.jsx)("path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,d.jsx)("path",{d:"M6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,d.jsx)("path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"}),(0,d.jsx)("path",{d:"M9 12h6"}),(0,d.jsx)("path",{d:"M12 12v3"})]})}let rD=(0,u.forwardRef)(function(e,t){let{cwd:n,onOpenFile:r,refreshKey:i,onAtMention:s,onAtMentions:l,onUploadBusyChange:a,changesCollapsed:o,onChangesCountChange:c,fileSearchOpen:p=!1,searchAlwaysVisible:h=!1,onFileSearchOpenChange:m,showHidden:f=!1}=e,{t:g}=(0,ns.s)(),[x,v]=(0,u.useState)([]),[b,y]=(0,u.useState)(!0),[w,j]=(0,u.useState)(null),[k,S]=(0,u.useState)(new Set),[C,N]=(0,u.useState)(0),[E,M]=(0,u.useState)(new Set),[$,I]=(0,u.useState)([]),[T,R]=(0,u.useState)({additions:0,deletions:0}),[A,L]=(0,u.useState)("list"),[P,z]=(0,u.useState)(()=>new Set),[O,W]=(0,u.useState)("idle"),[F,D]=(0,u.useState)(0),[_,B]=(0,u.useState)(null),[H,U]=(0,u.useState)(null),[K,q]=(0,u.useState)(null),[V,Z]=(0,u.useState)(""),[J,Y]=(0,u.useState)([]),[G,X]=(0,u.useState)(!1),[Q,ee]=(0,u.useState)(!1),[et,en]=(0,u.useState)(new Set),er=(0,u.useRef)(null),[ei,es]=(0,u.useState)(!1),[el,ea]=(0,u.useState)(null),eo=(0,u.useRef)(0),ec=(0,u.useRef)(null),ed=(0,u.useRef)(k),eu=(0,u.useRef)(null),ep=`${i??0}:${C}`,eh="idle"!==O,em=V.trim().length>0,ef=p||h;(0,u.useEffect)(()=>{if(!ef)return;let e=V.trim();if(!e){Y([]),X(!1),ee(!1);return}let t=new AbortController;X(!0),ee(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(n)}&q=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>Y((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{t.signal.aborted||(Y([]),ee(!0))}).finally(()=>{t.signal.aborted||X(!1)})},150);return()=>{clearTimeout(r),t.abort()}},[n,ef,V]),(0,u.useEffect)(()=>{p&&er.current?.focus()},[p]),(0,u.useEffect)(()=>{if(0===J.length)return;let e=new Set;for(let t of J){let r=t.split("/"),i="";for(let t=0;t<r.length-1;t++)i=i?`${i}/${r[t]}`:r[t],e.add(e8(n,i))}en(t=>{let n=!1,r=new Set(t);for(let t of e)r.has(t)||(r.add(t),n=!0);return n?r:t})},[n,J]);let eg=(0,u.useMemo)(()=>{let e=t=>({name:t.name,fullPath:e8(n,t.path),isDir:t.isDir,size:0,children:t.children.map(e),loaded:!0});return rw(J).map(e)},[n,J]),ex=(0,u.useMemo)(()=>new Map($.map(e=>[e0(e.filePath),e])),[$]),ev=(0,u.useMemo)(()=>{let e=new Set,t=e0(n).replace(/\/$/,"");for(let n of $){let r=e4(e0(n.filePath));for(;(r===t||r.startsWith(`${t}/`))&&(e.add(r),r!==t);){let e=e4(r);if(e===r)break;r=e}}return e},[n,$]),eb=(0,u.useMemo)(()=>new Map($.map(e=>[e0(e3(e.filePath,n)).replace(/^\/+/,""),e])),[n,$]),ey=(0,u.useMemo)(()=>rw([...eb.keys()]),[eb]),ew=(0,u.useCallback)((e,t)=>{S(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ej=(0,u.useCallback)((e,t)=>{let n=e.uploaded??[];U({directory:t,uploaded:n,skipped:e.skipped??[],errors:e.errors??[]}),n.length>0&&(M(new Set(n.map(e=>e8(t,e)))),N(e=>e+1))},[]),ek=(0,u.useCallback)(async(e,t,n)=>{q(null),B(null),D(0),W("uploading");try{let{status:r,data:i}=await ry(n,e,t,D);if(409===r&&i.conflicts?.length)return void q({directory:n,files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);D(100),ej(i,n)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}},[ej]),eS=(0,u.useCallback)(async(e,t)=>{if(0!==e.length&&!eh){U(null),M(new Set),q(null),B(null),D(0),W("checking");try{let n=await fetch(`/api/files/${e1(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void q({directory:t,files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ek(e,"error",t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{W("idle")}}},[ek,eh]),eC=(0,u.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eS(t,n)},[n,eS]);(0,u.useImperativeHandle)(t,()=>({openUploadPicker(){eh||eu.current?.click()}}),[eh]);let eN=(0,u.useCallback)(()=>{eo.current=0,es(!1),ea(null)},[]),eE=(0,u.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),eo.current+=1,es(!0))},[]),eM=(0,u.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy",ea(e=>null===e?e:null))},[]),e$=(0,u.useCallback)(()=>{eo.current<=0||(eo.current-=1,0===eo.current&&(eo.current=0,es(!1),ea(null)))},[]),eI=(0,u.useCallback)((e,t)=>{eN();let n=t.flatMap(e=>"file"===e.kind?[e.file]:[]),r=t.flatMap(e=>"folder"===e.kind?[e.name]:[]);eS(n,e).then(()=>{if(0===r.length)return;let e=g("chat.dropFoldersUnsupported",{names:r.join(", ")});B(t=>t&&n.length>0?t:e)})},[eS,eN,g]),eT=(0,u.useCallback)(e=>{e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e.stopPropagation(),eI(el??n,rk(e.dataTransfer)))},[n,el,eI]),eR=(0,u.useCallback)(e=>{ea(t=>t===e?t:e)},[]);(0,u.useEffect)(()=>{a?.(eh)},[a,eh]),(0,u.useEffect)(()=>()=>a?.(!1),[a]),(0,u.useEffect)(()=>{ed.current=k},[k]),(0,u.useEffect)(()=>()=>{null!==ec.current&&rS.save(ec.current,ed.current)},[]),(0,u.useEffect)(()=>{let e=ec.current,t=e!==n;if(ec.current=n,t){null!==e&&rS.save(e,ed.current);let t=rS.restore(n);ed.current=t,S(t),M(new Set),U(null),q(null),B(null)}y(t),j(null);let r=!1;return rN(n,f).then(e=>{r||v(e)}).catch(e=>{r||j(e instanceof Error?e.message:String(e))}).finally(()=>{r||y(!1)}),()=>{r=!0}},[n,i,C,f]),(0,u.useEffect)(()=>{let e=()=>N(e=>e+1);return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[]),(0,u.useEffect)(()=>{let e=!1,t=new AbortController;return rM(n,t.signal).then(t=>{e||(I(t.isGitRepository?t.files:[]),R(t.isGitRepository?{additions:t.additions,deletions:t.deletions}:{additions:0,deletions:0}))}).catch(()=>{e||(I([]),R({additions:0,deletions:0}))}),()=>{e=!0,t.abort()}},[n,i,C]),(0,u.useEffect)(()=>{c?.($.length)},[$,c]),(0,u.useEffect)(()=>{L(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return"list";try{return"tree"===e.getItem(th)?"tree":"list"}catch{return"list"}}())},[]);let eA=(0,u.useCallback)((e,t)=>{z(n=>{let r=new Set(n);return t?r.delete(e):r.add(e),r})},[]),eL=(0,u.useCallback)(()=>{L(e=>{let t="list"===e?"tree":"list";return!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(th,e)}catch{}}(t),t})},[]),eP=eh||null!==K||null!==_||null!==H,ez=(0,u.useCallback)(()=>{H&&0!==H.uploaded.length&&l?.(H.uploaded.map(e=>e3(e8(H.directory,e),n)))},[n,l,H]);return(0,d.jsxs)("div",{style:{minHeight:"100%"},onDragEnter:eE,onDragOver:eM,onDragLeave:e$,onDrop:eT,children:[(0,d.jsx)("input",{ref:eu,type:"file",multiple:!0,hidden:!0,onChange:eC}),eP&&(0,d.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[eh&&(0,d.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===O?g("files.checking"):g("files.uploading",{progress:F}),children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===O?(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M12 16V4"}),(0,d.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,d.jsx)("path",{d:"M5 20h14"})]}),"uploading"===O&&(0,d.jsxs)("span",{style:{fontSize:10},children:[F,"%"]})]}),"uploading"===O&&(0,d.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,d.jsx)("div",{style:{width:`${F}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),K&&(0,d.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,d.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:g("files.conflictSummary",{count:K.conflicts.length,countSuffix:1===K.conflicts.length?"":"s",files:K.conflicts.join(", ")})}),K.nonReplaceable.length>0&&(0,d.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:g("files.cannotReplace",{files:K.nonReplaceable.join(", ")})}),(0,d.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,d.jsx)("button",{type:"button",onClick:()=>void ek(K.files,"overwrite",K.directory),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:g("files.replace")}),(0,d.jsx)("button",{type:"button",onClick:()=>void ek(K.files,"skip",K.directory),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:g("files.skipExisting")}),(0,d.jsx)("button",{type:"button",onClick:()=>q(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:g("files.cancel")})]})]}),_&&(0,d.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,d.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:_}),(0,d.jsx)(ro,{onClick:()=>B(null),title:g("files.dismissError")})]}),H&&(0,d.jsxs)("div",{"aria-live":"polite",children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,d.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[H.uploaded.length>0&&(0,d.jsxs)("span",{title:g("files.uploadedCount",{count:H.uploaded.length}),"aria-label":g("files.uploadedCount",{count:H.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,d.jsx)("span",{children:H.uploaded.length})]}),H.skipped.length>0&&(0,d.jsxs)("span",{title:g("files.skippedCount",{count:H.skipped.length}),"aria-label":g("files.skippedCount",{count:H.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M8 12h8"})]}),(0,d.jsx)("span",{children:H.skipped.length})]}),H.errors.length>0&&(0,d.jsxs)("span",{title:g("files.failedCount",{count:H.errors.length}),"aria-label":g("files.failedCount",{count:H.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,d.jsx)("path",{d:"M12 9v4"}),(0,d.jsx)("path",{d:"M12 17h.01"})]}),(0,d.jsx)("span",{children:H.errors.length})]})]}),H.uploaded.length>0&&l&&(0,d.jsxs)("button",{type:"button",onClick:ez,title:1===H.uploaded.length?g("files.addUploadedFile"):g("files.addAllUploadedFiles"),"aria-label":1===H.uploaded.length?g("files.addUploadedFile"):g("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,d.jsx)(rR,{}),g("files.mention")]}),(0,d.jsx)(ro,{onClick:()=>U(null),title:g("files.dismissUploadResults")})]}),H.errors.map(e=>(0,d.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M12 8v5"}),(0,d.jsx)("path",{d:"M12 17h.01"})]}),(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),ef&&(0,d.jsxs)("div",{className:"file-explorer-search",style:{padding:"2px 8px 6px"},children:[(0,d.jsxs)("div",{style:{position:"relative"},children:[(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,d.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,d.jsx)("path",{d:"m20 20-4-4"})]}),(0,d.jsx)("input",{ref:er,className:"file-explorer-search-input",id:"file-search-input",value:V,onChange:e=>Z(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),h?Z(""):m?.(!1))},placeholder:g("sidebar.searchFilesPlaceholder"),"aria-label":g("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}}),V&&(0,d.jsx)("button",{type:"button",onClick:()=>Z(""),title:g("sidebar.clearSearch"),"aria-label":g("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M18 6 6 18"}),(0,d.jsx)("path",{d:"m6 6 12 12"})]})})]}),em&&(0,d.jsxs)("div",{style:{paddingTop:3},children:[G&&(0,d.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:g("sidebar.searchingFiles")}),!G&&Q&&(0,d.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:g("i18n.networkError")}),!G&&!Q&&0===J.length&&(0,d.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:g("sidebar.noMatchingFiles")}),!G&&!Q&&J.length>0&&(0,d.jsx)("div",{children:eg.map(e=>(0,d.jsx)(rP,{node:e,depth:0,cwd:n,onOpenFile:r,onAtMention:s,expandedPaths:et,onToggleExpanded:(e,t)=>{en(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:E,gitStatusByPath:ex,changedDirectoryPaths:ev,dropTargetPath:el,onDropFiles:eI,onDropTargetChange:eR,t:g},`${V}:${e.fullPath}`))})]})]}),!o&&$.length>0&&(0,d.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,d.jsxs)("div",{"aria-label":g("files.changeStats",{count:$.length,additions:T.additions,deletions:T.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 6px 0 10px",fontSize:12},children:[(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:g("files.changedCount",{count:$.length})}),(0,d.jsxs)("span",{style:{color:rI.added,fontFamily:"var(--font-mono)"},children:["+",T.additions]}),(0,d.jsxs)("span",{style:{color:rI.deleted,fontFamily:"var(--font-mono)"},children:["-",T.deletions]}),(0,d.jsx)("span",{style:{flex:1}}),(0,d.jsx)("button",{type:"button",onClick:eL,title:"list"===A?g("files.viewAsTree"):g("files.viewAsList"),"aria-label":"list"===A?g("files.viewAsTree"):g("files.viewAsList"),"aria-pressed":"tree"===A,style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,d.jsx)(rF,{mode:A})})]}),"tree"===A?(0,d.jsx)(rW,{nodes:ey,depth:0,cwd:n,statusByPath:eb,collapsedPaths:P,onToggleExpanded:eA,onOpenFile:r,onAtMention:s,t:g}):$.map(e=>(0,d.jsx)(rz,{status:e,cwd:n,onOpenFile:r,onAtMention:s,t:g},e.filePath))]}),h&&!em&&(0,d.jsxs)("div",{className:"file-explorer-tree-heading",children:[(0,d.jsx)(ru,{size:14}),(0,d.jsx)("span",{children:g("workbench.allFiles")})]}),(o||0===$.length)&&(!ef||!em)&&(0,d.jsxs)("div",{style:{padding:"2px 4px"},children:[b?(0,d.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:g("files.loading")}):w?(0,d.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:w}):x.map(e=>(0,d.jsx)(rP,{node:e,depth:0,cwd:n,onOpenFile:r,onAtMention:s,expandedPaths:k,onToggleExpanded:ew,refreshToken:ep,highlightedPaths:E,gitStatusByPath:ex,changedDirectoryPaths:ev,showHidden:f,dropTargetPath:el,onDropFiles:eI,onDropTargetChange:eR,t:g},e.fullPath)),!b&&!w&&0===x.length&&(0,d.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:g("files.noFiles")})]}),ei&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",style:{position:"sticky",bottom:0,zIndex:1,display:"flex",alignItems:"center",gap:6,padding:"6px 8px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)",fontSize:11,color:"var(--accent)",userSelect:"none",pointerEvents:"none"},children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,d.jsx)("path",{d:"M12 16V4"}),(0,d.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,d.jsx)("path",{d:"M5 20h14"})]}),g("files.dropToUpload",{directory:el?e3(el,n)||el:e2(n)||n})]})]})}),r_="[data-sidebar-menu-filter]",rB="[data-sidebar-menu-autofocus]",rH="button, input, textarea, select, a[href], [tabindex]";function rU(e,t,n){let r,i,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8,l=n.left+s,a=n.top+s,o=n.left+n.width-s,c=n.top+n.height-s;if("point"===e.kind)r=e.x+t.width>o&&e.x-t.width>=l?e.x-t.width:e.x,i=e.y+t.height>c&&e.y-t.height>=a?e.y-t.height:e.y;else{let{rect:n}=e;r="end"===e.align?n.right-t.width:n.left;let s=n.bottom+4,l=n.top-4-t.height;i=s+t.height>c&&l>=a?l:s}return{left:Math.max(l,Math.min(r,o-t.width)),top:Math.max(a,Math.min(i,c-t.height))}}function rK(e){return u.Children.toArray(e).length>0}function rq(e){return"item"===e.type&&void 0!==e.checked}function rV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return(e??[]).filter(rq).length>=t}function rZ(e){return e.getClientRects().length>0}function rJ(e){return!e.disabled&&"true"!==e.getAttribute("aria-disabled")&&rZ(e)}function rY(e){return Array.from(e.querySelectorAll("[data-sidebar-menu-item]")).filter(rJ)}function rG(e){let t=Array.from(e.querySelectorAll(rB)).find(rJ);if(t)return t;let n=rY(e);return n.length>0?n[0]:Array.from(e.querySelectorAll(rH)).filter(e=>e.tabIndex>=0&&rJ(e))[0]??null}function rX(e){e.stopPropagation()}let rQ={onClick:rX,onDoubleClick:rX,onMouseDown:rX,onMouseUp:rX,onPointerDown:rX,onPointerUp:rX,onKeyDown:rX,onKeyUp:rX,onFocus:rX,onBlur:rX,onContextMenu:function(e){e.preventDefault(),e.stopPropagation()}};function r0(e,t){return n=>{"Enter"!==n.key||n.nativeEvent.isComposing||229===n.keyCode||(n.preventDefault(),t(e,n.shiftKey))}}function r1(e){let{item:t,onActivate:n}=e,r=void 0!==t.checked,i=["sidebar-menu-item",r?"is-choice":"",t.danger?"is-danger":"",t.checked?"is-checked":""].filter(Boolean).join(" "),s=["sidebar-menu-label",t.mono?"is-mono":"",t.path?"is-path":""].filter(Boolean).join(" "),l=null;t.disabled&&t.disabledReason?l=(0,d.jsx)("span",{className:"sidebar-menu-note",children:t.disabledReason}):t.note?l=(0,d.jsx)("span",{className:"sidebar-menu-note",children:t.note}):t.shortcut&&(l=(0,d.jsx)("kbd",{className:"sidebar-menu-shortcut",children:t.shortcut}));let a=(0,d.jsxs)("button",{type:"button",role:r?"menuitemradio":"menuitem","aria-checked":r?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:i,onClick:e=>n(t,e.shiftKey),onKeyDown:r0(t,n),children:[(0,d.jsx)("span",{className:"sidebar-menu-icon",children:r?t.checked?(0,d.jsx)(n1,{size:13}):null:t.icon}),(0,d.jsx)("span",{className:s,children:t.path?(0,d.jsx)("span",{children:t.label}):t.label}),t.badge,l]}),o=t.secondary;return o?(0,d.jsxs)("div",{className:r?"sidebar-menu-row is-choice":"sidebar-menu-row",role:"none",children:[a,(0,d.jsx)("button",{type:"button",role:"menuitem","aria-label":o.label,"aria-disabled":!!o.disabled||void 0,tabIndex:-1,title:o.label,"data-sidebar-menu-item":"",className:["sidebar-menu-secondary",o.danger?"is-danger":"",o.revealOnHover?"is-hover-reveal":""].filter(Boolean).join(" "),onClick:e=>n(o,e.shiftKey),onKeyDown:r0(o,n),children:o.icon})]}):a}function r2(e){var t;let n,{sheet:r,ariaLabel:i,title:s,items:l,filter:a,filterQuery:o="",onFilterQueryChange:c,children:u,cancelLabel:p,focusCancel:h=!1,width:m=208,classic:f=!1,footer:g,surfaceRef:x,onActivate:v,onClose:b}=e,y=rK(u),w=!y&&rK(g),j=void 0!==a&&!y&&rV(l,a.minChoices),k=j?(t=l??[],(n=o.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]):l??[],S=k.map(e=>"separator"===e.type?(0,d.jsx)("div",{className:"sidebar-menu-separator",role:"separator"},e.id):"header"===e.type?(0,d.jsx)("div",{className:"sidebar-menu-header",role:"presentation",children:e.label},e.id):"custom"===e.type?(0,d.jsx)("div",{className:"sidebar-menu-custom",role:"none",children:e.content},e.id):(0,d.jsx)(r1,{item:e,onActivate:v},e.id)),C=y?u:j||w?(0,d.jsxs)(d.Fragment,{children:[j&&(0,d.jsx)("div",{className:"sidebar-menu-filter",children:(0,d.jsx)("input",{className:"sidebar-menu-filter-input",value:o,placeholder:a.placeholder,"aria-label":a.placeholder,autoComplete:"off",spellCheck:!1,"data-sidebar-menu-filter":"","data-sidebar-menu-autofocus":r?void 0:"",onChange:e=>c?.(e.target.value)})}),j&&(0,d.jsx)("div",{role:"status",children:o.trim()&&!k.some(rq)&&(0,d.jsx)("div",{className:"sidebar-menu-empty",children:a.emptyLabel})}),(0,d.jsx)("div",{role:"menu","aria-label":i,children:S}),w&&g]}):S,N=y||j||w?void 0:"menu";return r?(0,d.jsxs)("div",{className:"sidebar-sheet-layer",...rQ,children:[(0,d.jsx)("div",{className:"sidebar-sheet-backdrop","aria-hidden":"true",onClick:()=>b("outside")}),(0,d.jsxs)("div",{ref:x,className:"sidebar-sheet",role:"dialog","aria-modal":"true","aria-label":i,children:[s?(0,d.jsx)("div",{className:"sidebar-sheet-title",children:s}):null,(0,d.jsx)("div",{className:"sidebar-sheet-body",role:N,"aria-label":N?i:void 0,children:C}),(0,d.jsx)("button",{type:"button",className:"sidebar-sheet-cancel","data-sidebar-menu-autofocus":h?"":void 0,onClick:()=>b("cancel"),children:p})]})]}):(0,d.jsx)("div",{ref:x,className:f?"sidebar-menu is-classic":"sidebar-menu",role:N??"dialog","aria-label":i,style:{width:m},...rQ,children:C})}function r4(e){let{open:t,anchor:n,sheet:r,ariaLabel:i,title:s,items:l,filter:a,children:o,cancelLabel:c,focusCancel:p,onClose:h,returnFocusTo:m,width:f,classic:x=!1,footer:v,focusKey:b=""}=e,[y,w]=(0,u.useState)(null),[j,k]=(0,u.useState)(""),S=(0,u.useRef)(j);S.current=j;let C=(0,u.useRef)(null),N=(0,u.useRef)(h);N.current=h;let E=(0,u.useRef)(l);E.current=l;let M=(0,u.useRef)(m??null);M.current=m??null;let $=(0,u.useRef)(n);$.current=n,(0,u.useEffect)(()=>{w(document.body)},[]);let I=t&&null!==y&&(r||null!==n),T=rK(o),R=n?JSON.stringify(n):"",A=!T&&void 0!==a&&rV(l,a.minChoices),L=(e,t)=>{if(e.disabled)return;let n=!1;e.onSelect({shiftKey:t,keepOpen:()=>{n=!0}}),n||N.current("select")},P=(0,u.useRef)(L);P.current=L,(0,u.useLayoutEffect)(()=>{let e=C.current;if(!I||r||!e)return;let t=window.visualViewport,n=null,i=()=>{let r=$.current;if(!r)return;let i=e.getBoundingClientRect(),{left:s,top:l}=rU(r,{width:i.width,height:i.height},{left:t?.offsetLeft??0,top:t?.offsetTop??0,width:t?.width??window.innerWidth,height:t?.height??window.innerHeight});null===n&&(n=l);let a=A?Math.max((t?.offsetTop??0)+8,Math.min(n,(t?.offsetTop??0)+(t?.height??innerHeight)-8-i.height)):l;e.style.left=`${s}px`,e.style.top=`${a}px`},s=()=>{n=null,i()};i();let l="u"<typeof ResizeObserver?null:new ResizeObserver(i);return l?.observe(e),window.addEventListener("resize",s),t?.addEventListener("resize",s),t?.addEventListener("scroll",s),()=>{l?.disconnect(),window.removeEventListener("resize",s),t?.removeEventListener("resize",s),t?.removeEventListener("scroll",s)}},[I,r,R,T,A]),(0,u.useEffect)(()=>{k("")},[I,T]);let z=(0,u.useRef)(!1);return((0,u.useLayoutEffect)(()=>{let e=C.current;if(!I||!e){z.current=!1;return}let t=!z.current;z.current=!0,(t?rG(e):Array.from(e.querySelectorAll(rB)).filter(e=>!e.matches(r_)&&rJ(e))[0]??rG(e))?.focus({preventScroll:!0})},[I,r,T,b]),(0,u.useLayoutEffect)(()=>{let e=C.current;if(!I||!e)return;let t=M.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(rZ(e))return e;let t=e.closest("[data-row-key]");if(!t)return null;for(let e of Array.from(t.querySelectorAll(rH)))if(e.tabIndex>=0&&rJ(e))return e;return null}(t);r&&(r.focus({preventScroll:!0}),t&&r!==t&&rZ(t)&&t.focus({preventScroll:!0}))}},[I,r]),(0,u.useEffect)(()=>{if(!I)return;let e=e=>{let t=C.current;if(!t||e.isComposing||229===e.keyCode)return;if("Escape"===e.key){e.preventDefault(),e.stopPropagation();let n=t.querySelector(r_);if(n&&S.current){k(""),n.focus({preventScroll:!0});return}N.current("escape");return}let n=e.target instanceof Element?e.target:null,r=null!==n&&t.contains(n),i=null===n||n===document.body||n===document.documentElement;if(!r&&!i)return;if("Tab"===e.key){var s;let i,l;r&&(s=e.shiftKey,i=Array.from(t.querySelectorAll(rH)).filter(e=>e!==n&&e.tabIndex>=0&&rJ(e)),l=s?Node.DOCUMENT_POSITION_PRECEDING:Node.DOCUMENT_POSITION_FOLLOWING,i.some(e=>(n.compareDocumentPosition(e)&l)!=0))||N.current("outside");return}let l=("ArrowDown"===e.key||"ArrowUp"===e.key)&&n?.matches(r_);if(r&&function(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"TEXTAREA"===t||"SELECT"===t||"INPUT"===t&&!["button","checkbox","radio","range","reset","submit","image","color","file"].includes((e.type||"text").toLowerCase())}(n)&&!l)return;if("ArrowDown"===e.key||"ArrowUp"===e.key||"Home"===e.key||"End"===e.key){let r,i=rY(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 a=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}(E.current,e.key);a&&!T&&(e.preventDefault(),e.stopPropagation(),P.current(a,e.shiftKey))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[I,T]),(0,u.useEffect)(()=>{if(!I||r)return;let e=e=>{let t=C.current,n=e.target instanceof Node?e.target:null;if(!t||n&&t.contains(n))return;let r=M.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),N.current("outside")};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)},[I,r]),I&&y)?(0,g.createPortal)((0,d.jsx)(r2,{sheet:r,ariaLabel:i,title:s,items:l,filter:a,filterQuery:j,onFilterQueryChange:k,cancelLabel:c,focusCancel:p,width:f,classic:x,footer:v,surfaceRef:C,onActivate:(e,t)=>P.current(e,t),onClose:e=>N.current(e),children:o}),y):null}let r3="PI-YUN";function r8(e){let{canCreate:t=!1,onNewSession:n,onOpenProject:r,onOpenSettings:i}=e,{t:s}=(0,ns.s)(),l=(0,u.useRef)(null),[a,o]=(0,u.useState)(null),c=s("navigation.appMenu",{name:r3}),p=()=>{let e=l.current?.getBoundingClientRect();e&&o({kind:"rect",rect:e,align:"start"})},h=[{type:"item",id:"new",label:s("i18n.newSession"),icon:(0,d.jsx)(n8,{size:16}),disabled:!t,onSelect:()=>n?.()},{type:"item",id:"project",label:s("sidebar.openOtherProject"),icon:(0,d.jsx)(n6,{size:16}),onSelect:()=>r?.(l.current)},...i?[{type:"separator",id:"settings-separator"},{type:"item",id:"settings",label:s("common.settings"),icon:(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M4 7h16M4 17h16"}),(0,d.jsx)("circle",{cx:"9",cy:"7",r:"3",fill:"var(--bg-panel)"}),(0,d.jsx)("circle",{cx:"15",cy:"17",r:"3",fill:"var(--bg-panel)"})]}),onSelect:i}]:[]];return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{ref:l,type:"button",className:"sidebar-brand","aria-label":c,"aria-haspopup":"menu","aria-expanded":!!a,onClick:()=>{a?o(null):p()},onKeyDown:e=>{"ArrowDown"!==e.key||a||(e.preventDefault(),p())},children:[(0,d.jsx)("span",{className:"sidebar-brand-label",children:r3}),(0,d.jsx)("svg",{className:"sidebar-brand-chevron",width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m4 6 4 4 4-4"})})]}),(0,d.jsx)(r4,{open:!!a,anchor:a,sheet:!1,ariaLabel:c,title:r3,items:h,cancelLabel:s("sidebar.cancel"),onClose:()=>o(null),returnFocusTo:l.current})]})}let r6=[{id:"auto",label:"settings.themeSystem",scheme:null},{id:"breeze",label:"settings.themeBreeze",scheme:"light"},{id:"sunbeam",label:"settings.themeSunbeam",scheme:"light"},{id:"light",label:"settings.themeLight",scheme:"light"},{id:"mist",label:"settings.themeMist",scheme:"light"},{id:"lilac",label:"settings.themeLilac",scheme:"light"},{id:"sand",label:"settings.themeSand",scheme:"light"},{id:"rose",label:"settings.themeRose",scheme:"light"},{id:"dark",label:"settings.themeDark",scheme:"dark"},{id:"pine",label:"settings.themePine",scheme:"dark"},{id:"dusk",label:"settings.themeDusk",scheme:"dark"},{id:"ember",label:"settings.themeEmber",scheme:"dark"},{id:"slate",label:"settings.themeSlate",scheme:"dark"},{id:"contrast-light",label:"settings.themeContrastLight",scheme:"light"},{id:"contrast-dark",label:"settings.themeContrastDark",scheme:"dark"},{id:"zenburn",label:"settings.themeZenburn",scheme:"dark"}],r5=[{id:"fox",label:"settings.avatarFox"},{id:"radio",label:"settings.avatarRadio"},{id:"sprout",label:"settings.avatarSprout"},{id:"orbital",label:"settings.avatarOrbital"},{id:"coral",label:"settings.avatarCoral"}];function r9(e){let t=0;for(let n of e)t=Math.imul(t,31)+n.charCodeAt(0);return`${((t>>>0)%4+1)*25}%`}function r7(e){return{"--chat-avatar-position":r9(e)}}function ie(e){return{"--chat-subagent-avatar-position":r9(`subagent/${e}`)}}r6.flatMap(e=>"light"===e.scheme?[e.id]:[]);let it=r6.flatMap(e=>"dark"===e.scheme?[e.id]:[]);function ir(e){return it.includes(e)}var ii=n(2730);let is={desktop:32,mobile:48};function il(e,t,n,r){return Math.hypot(n-e,r-t)}function ia(e){return e.getClientRects().length>0}function io(e){let t=e5(e.firstMessage)??e.firstMessage;return e.name||t.slice(0,50)||e.id.slice(0,12)}function ic(e){return e.nativeEvent.isComposing||229===e.keyCode}function id(e){var t;let n,r,i,s,l,{rows:a,layout:o,emptyLabel:c,loading:p,error:h,renamingRootId:m,renamingProjectKey:f,confirmDeleteRootId:g,activeMenuRowKey:x,reveal:v}=e,{t:b}=(0,ns.s)(),y=(0,u.useRef)(e);y.current=e;let w=(0,u.useRef)(null),j=(0,u.useRef)(null),k=(0,u.useRef)(null),S=(0,u.useRef)(null);nj(j);let[C,N]=(0,u.useState)(0),[E,M]=(0,u.useState)(0),[$,I]=(0,u.useState)(null),[T,R]=(0,u.useState)(()=>Date.now()),A=(0,u.useRef)(null),L=(0,u.useCallback)(()=>{null===A.current&&(A.current=requestAnimationFrame(()=>{A.current=null;let e=j.current;e&&N(e.scrollTop)}))},[]);(0,u.useLayoutEffect)(()=>{let e=j.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(),M(e.clientHeight),N(e.scrollTop),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(()=>{t(),M(e.clientHeight),N(e.scrollTop)});return n.observe(e),()=>n.disconnect()},[]),(0,u.useEffect)(()=>()=>{null!==A.current&&cancelAnimationFrame(A.current)},[]),(0,u.useEffect)(()=>{let e=window.setInterval(()=>R(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let P=(0,u.useCallback)(e=>{let t=e.target instanceof Element?e.target.closest("[data-row-key]"):null;I(t?.getAttribute("data-row-key")??null)},[]),z=(0,u.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||I(null)},[]),O=(0,u.useMemo)(()=>(function(e,t){let n=eE[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})(a,o),[a,o]),W=!!e.onMoveGroup,F=(0,u.useMemo)(()=>{let e={pinned:0,other:0};for(let t of a)"group"===t.kind&&e[t.project.pinned?"pinned":"other"]++;return e},[a]),D=function(e){let{rows:t,offsets:n,enabled:r}=e,i=(0,u.useRef)(e);i.current=e;let s=(0,u.useMemo)(()=>(function(e,t){let n=[],r=0;for(;r<e.length;){var i;let s=e[r];if("group"!==s.kind){r++;continue}let l=r;for(;l>0&&"spacer"===e[l-1].kind;)l--;let a=r+1;for(;a<e.length&&("group-more"===(i=e[a]).kind||"group-empty"===i.kind||"session"===i.kind&&"group"===i.context);)a++;let o=a;for(;o<e.length&&"spacer"===e[o].kind;)o++;n.push({key:s.project.key,pinned:s.project.pinned,top:t[r],bottom:t[a],gapAbove:t[r]-t[l],gapBelow:t[o]-t[a]}),r=a}return n})(t,n),[t,n]),l=(0,u.useRef)(s);l.current=s;let a=(0,u.useRef)(null),o=(0,u.useRef)(0),[c,d]=(0,u.useState)(null),p=(0,u.useMemo)(()=>{let e=e=>{d("armed"===e.phase||"dragging"===e.phase?{projectKey:e.projectKey,phase:e.phase,drop:e.drop}:null)},t=e=>{let t=i.current.innerRef.current;return t?function(e,t,n){let r=e.find(e=>e.key===t);if(!r)return null;let i=e.filter(e=>e.pinned===r.pinned),s=i.indexOf(r),l=i.filter(e=>e!==r);if(0===l.length)return null;let a=l.filter(e=>(e.top+e.bottom)/2<n).length;if(a===s)return null;let o=l[l.length-1],c=Math.max(3,a<l.length?l[a].top-l[a].gapAbove/2:o.bottom+o.gapBelow/2);return a>0?{anchorKey:l[a-1].key,position:"after",lineY:c}:{anchorKey:l[0].key,position:"before",lineY:c}}(l.current,e.projectKey,e.clientY-t.getBoundingClientRect().top):null},n=()=>{let e=a.current,t=i.current.ghostRef.current,n=i.current.treeRef.current,r=i.current.innerRef.current,s=i.current.scrollRef.current;if(!e?.ghost||!t||!n||!s)return;let l=n.getBoundingClientRect().top,o=s.getBoundingClientRect(),c=t.offsetHeight,d=function(e){let{pointerY:t,lineY:n,ghostHeight:r,pointerGap:i,lineGap:s,minTop:l,maxTop:a}=e,o=Math.max(l,a),c=t-i-r,d=null!==n&&n>=l&&n<=o+r?n:null,u=e=>e>=l&&e<=o,p=e=>null!==d&&e>d-s-r&&e<d+s,h=null===d?[c,l,t+i,o]:[c,d-s-r,l,t+i,d+s,o],m=e=>{let t=null;for(let n of h)e(n)&&(null===t||Math.abs(n-c)<Math.abs(t-c))&&(t=n);return t};return m(e=>u(e)&&!(e>c&&e<t+i)&&!p(e))??m(e=>u(e)&&!p(e))??Math.min(o,Math.max(l,c))}({pointerY:e.clientY,lineY:e.drop&&r?r.getBoundingClientRect().top+e.drop.lineY:null,ghostHeight:c,pointerGap:"mouse"===e.pointerType?8:28,lineGap:8,minTop:o.top,maxTop:o.bottom-c});t.style.top=`${d-l}px`,t.style.left=`${e.ghost.left}px`},r=e=>{null!==e.timer&&window.clearTimeout(e.timer),null!==e.frame&&cancelAnimationFrame(e.frame),e.timer=null,e.frame=null,i.current.scrollRef.current?.removeEventListener("scroll",p);try{e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId)}catch{}},s=()=>{let e=a.current;e&&(a.current=null,r(e),window.removeEventListener("pointermove",g,!0),window.removeEventListener("pointerup",x,!0),window.removeEventListener("pointercancel",v,!0),window.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",y,!0),window.removeEventListener("contextmenu",w,!0),window.removeEventListener("blur",j),document.removeEventListener("visibilitychange",k),d(null))},c=()=>{let e=a.current;if(e){if("armed"!==e.phase&&"dragging"!==e.phase){"pending"===e.phase&&s();return}e.phase="cancelled",e.drop=null,r(e),d(null)}},u=function(){var r;let s=arguments.length>0&&void 0!==arguments[0]&&arguments[0],l=a.current;if(!l||"dragging"!==l.phase)return;let o=i.current.scrollRef.current;if(!o||!ia(o))return void c();let d=t(l),u=s||d!==(r=l.drop)&&(null===d||null===r||d.anchorKey!==r.anchorKey||d.position!==r.position||d.lineY!==r.lineY);l.drop=d,n(),u&&e(l)};function p(){u()}let h=()=>{let e=a.current;if(!e||"dragging"!==e.phase)return;e.frame=null;let t=i.current.scrollRef.current;if(!t||!ia(t))return void c();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,is[i.current.layout]);if(0!==r){let n=Math.min(Math.max(0,(i.current.offsets[i.current.offsets.length-1]??0)-t.clientHeight),Math.max(0,t.scrollTop+r));n!==t.scrollTop&&(t.scrollTop=n,e.expectedScrollTop=t.scrollTop,u())}a.current===e&&"dragging"===e.phase&&(e.frame=requestAnimationFrame(h))},m=e=>{let t=i.current.scrollRef.current,n=i.current.treeRef.current;if(!t||!n||!ia(t)||!e.element.isConnected)return void c();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),u(!0)},f=()=>{let t=a.current;t&&"pending"===t.phase&&(t.timer=null,t.phase="armed",t.armX=t.clientX,t.armY=t.clientY,t.expectedScrollTop=i.current.scrollRef.current?.scrollTop??0,e(t))};function g(e){let t=a.current;if(!t||e.pointerId!==t.pointerId)return;if("mouse"===t.pointerType&&0===e.buttons)return void s();t.clientX=e.clientX,t.clientY=e.clientY;let n=il(t.startX,t.startY,e.clientX,e.clientY);switch(t.phase){case"pending":"mouse"===t.pointerType?n>=4&&m(t):n>8&&s();break;case"armed":il(t.armX,t.armY,e.clientX,e.clientY)>=4&&m(t);break;case"dragging":u()}}function x(e){let n=a.current;if(n&&e.pointerId===n.pointerId){if("dragging"===n.phase){n.clientX=e.clientX,n.clientY=e.clientY;let r=t(n);r&&i.current.onMove(n.projectKey,r.anchorKey,r.position)}"pending"!==n.phase&&(o.current=e.timeStamp+600),s()}}function v(e){a.current&&e.pointerId===a.current.pointerId&&s()}function b(e){a.current&&e.pointerId!==a.current.pointerId&&c()}function y(e){let t=a.current;t&&"Escape"===e.key&&("armed"===t.phase||"dragging"===t.phase)&&(e.preventDefault(),e.stopPropagation(),c())}function w(e){let t=a.current;if(t){if("pending"===t.phase)return void s();e.preventDefault(),e.stopPropagation()}}function j(){s()}function k(){"hidden"===document.visibilityState&&s()}return{handlers:{onPointerDown(e,t){if(!i.current.enabled||a.current||!e.isPrimary||0!==e.button||e.ctrlKey||e.target instanceof Element&&e.target.closest(".session-tree-group-actions"))return;let n=e.currentTarget,r={pointerId:e.pointerId,pointerType:e.pointerType,projectKey:t,element:n,startX:e.clientX,startY:e.clientY,armX:e.clientX,armY:e.clientY,clientX:e.clientX,clientY:e.clientY,phase:"pending",timer:null,frame:null,expectedScrollTop:0,drop:null,ghost:null};a.current=r,window.addEventListener("pointermove",g,!0),window.addEventListener("pointerup",x,!0),window.addEventListener("pointercancel",v,!0),window.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",y,!0),window.addEventListener("contextmenu",w,!0),window.addEventListener("blur",j),document.addEventListener("visibilitychange",k),"mouse"!==e.pointerType&&(r.timer=window.setTimeout(f,350))},onTouchMove(e){let t=a.current;if(!t||"armed"!==t.phase&&"dragging"!==t.phase)return;if(e.cancelable)return void e.preventDefault();let n=i.current.scrollRef.current;n&&n.scrollTop!==t.expectedScrollTop&&s()}},cancel:c,teardown:s,updateDrag:u,placeGhost:n}},[]);(0,u.useLayoutEffect)(()=>{let e=a.current;e&&("armed"===e.phase||"dragging"===e.phase)&&(t.some(t=>"group"===t.kind&&t.project.key===e.projectKey)?p.updateDrag():p.cancel())},[t,n,p]),(0,u.useEffect)(()=>{r||p.cancel()},[r,p]);let h=c?.phase==="dragging";(0,u.useLayoutEffect)(()=>{h&&p.placeGhost()},[h,p]),(0,u.useEffect)(()=>()=>p.teardown(),[p]);let m=(0,u.useCallback)(e=>{let t=o.current;0===t||(o.current=0,e.timeStamp>t||(e.preventDefault(),e.stopPropagation()))},[]),f=(0,u.useCallback)(()=>{o.current=0},[]);return{view:(0,u.useMemo)(()=>{if(!c)return null;let e="dragging"===c.phase?s.find(e=>e.key===c.projectKey)??null:null;return{...c,source:e}},[c,s]),handlers:p.handlers,onClickCapture:m,onPointerDownCapture:f}}({rows:a,offsets:O,layout:o,enabled:W&&!p,scrollRef:j,innerRef:k,treeRef:w,ghostRef:S,onMove:(e,t,n)=>y.current.onMoveGroup?.(e,t,n)}),_=D.view,B=_?`group:${_.projectKey}`:null,[H,U]=(0,u.useState)(null),K=v&&v.id!==H?v:null,q=K?.rowKey??null,V=(0,u.useMemo)(()=>{let e=[];return a.forEach((t,n)=>{t.key===$||t.key===x||t.key===q||t.key===B||"session"===t.kind&&(t.family.root.id===m||t.family.root.id===g)?e.push(n):"group"===t.kind&&t.project.key===f&&e.push(n)}),e},[a,$,x,q,B,m,f,g]),Z=(0,u.useMemo)(()=>p?[]:function(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],s=Math.max(0,e.length-1),l=Number.isFinite(t)?Math.max(0,t):0,a=Number.isFinite(n)&&n>0?n:600,o=Number.isFinite(r)&&r>0?r:0,c=l-o,d=l+a+o,u=0,p=s;for(;u<p;){let t=u+p>>>1;e[t+1]>c?p=t:u=t+1}let h=u;for(u=h,p=s;u<p;){let t=u+p>>>1;e[t]>=d?p=t:u=t+1}let m=u,f=[];for(let e=h;e<m;e++)f.push(e);if(0===i.length)return f;let g=i.filter(e=>Number.isInteger(e)&&e>=0&&e<s&&(e<h||e>=m));return 0===g.length?f:[...new Set([...f,...g])].sort((e,t)=>e-t)}(O,C,E,240,V),[p,O,C,E,V]),J=(0,u.useRef)(null),Y=(0,u.useRef)(null),G=(0,u.useCallback)((e,t,n,r)=>{let i=document.activeElement===r,s=i&&r.matches(":focus-visible");J.current={rowKey:e,fallbackKey:t===eM?"pinned-header":`group:${t}`,focus:i,scroll:"less"===n||s},"more"===n?y.current.onShowMore(t):y.current.onShowLess(t)},[]);(0,u.useLayoutEffect)(()=>{let e=J.current;if(!e)return;J.current=null;let t=j.current,n=a.findIndex(t=>t.key===e.rowKey);if(n<0&&(n=a.findIndex(t=>t.key===e.fallbackKey)),e.scroll&&t&&n>=0){let e=eQ(O,n,t.scrollTop,t.clientHeight);null!==e&&(t.scrollTop=e),N(t.scrollTop)}e.focus&&(Y.current={rowKey:e.rowKey,fallbackKey:e.fallbackKey,tries:0})},[a,O]);let X=(0,u.useRef)(null);(0,u.useLayoutEffect)(()=>{if(!K)return;let e=a.findIndex(e=>e.key===K.rowKey),t=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"}}(X.current,K,e>=0,Date.now());if(X.current=t.misses,"wait"!==t.action){if("reveal"===t.action){let t=j.current;if(t&&t.getClientRects().length>0){let n=eQ(O,e,t.scrollTop,t.clientHeight,K.block);null!==n&&(t.scrollTop=n),N(t.scrollTop)}K.takeFocusFrom&&(Y.current={rowKey:K.rowKey,fallbackKey:K.rowKey,tries:0,takeFocusFrom:K.takeFocusFrom})}U(K.id),y.current.onRevealHandled?.(K.id)}},[K,a,O]),(0,u.useLayoutEffect)(()=>{let e=Y.current;if(!e)return;let t=document.activeElement;if(t&&t!==document.body&&document.contains(t)&&!e.takeFocusFrom?.(t)){Y.current=null;return}let n=j.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}),Y.current=null):++e.tries>2&&(Y.current=null)},[Z]);let Q=a.some(e=>"session"===e.kind||"group"===e.kind||"archive-group"===e.kind||"subagent"===e.kind),ee=!p&&!h&&null!==c&&!Q,et=_?.source??null,en=_?.drop?.lineY??null,er=_?.phase==="dragging"?a.find(e=>"group"===e.kind&&e.project.key===_.projectKey)?.project??null:null,ei=(t=_?.phase==="dragging",n=(0,u.useRef)(null),r=(0,u.useRef)(new Set),i=(0,u.useRef)(null),s=(0,u.useCallback)(()=>{for(let e of r.current)e.cancel();r.current.clear(),n.current=null,null!==i.current&&clearTimeout(i.current),i.current=null},[]),(0,u.useLayoutEffect)(()=>{let e=j.current,t=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>{t.matches&&s()},r=()=>{document.hidden&&s()},i="u"<typeof ResizeObserver?null:new ResizeObserver(s);return e&&i?.observe(e),e?.addEventListener("scroll",s,{passive:!0}),t.addEventListener("change",n),document.addEventListener("visibilitychange",r),()=>{e?.removeEventListener("scroll",s),t.removeEventListener("change",n),document.removeEventListener("visibilitychange",r),i?.disconnect(),s()}},[s,j]),l=(0,u.useCallback)(e=>{let r=j.current;if(!r||t||e.defaultPrevented||!(e.target instanceof Element)||!e.target.closest(".session-tree-group-toggle, .session-tree-pinned-toggle, .session-tree-recents-toggle, .session-tree-section-toggle")||document.hidden||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;let l=new Map,a=r.getBoundingClientRect();r.querySelectorAll("[data-row-key]").forEach(e=>{let t=e.getBoundingClientRect();t.bottom>a.top&&t.top<a.bottom&&l.set(e.dataset.rowKey,t.top)}),s(),n.current={tops:l,scrollTop:r.scrollTop},i.current=setTimeout(()=>{n.current=null,i.current=null},0)},[s,t,j]),(0,u.useLayoutEffect)(()=>{if(t)return void s();let e=n.current,i=j.current;if(!e||!i||(n.current=null,Math.abs(i.scrollTop-e.scrollTop)>1||!i.getClientRects().length))return;let l=i.getBoundingClientRect(),a=[];for(let{row:t,delta:n,entering:s}of(i.querySelectorAll("[data-row-key]").forEach(t=>{if("function"!=typeof t.animate)return;let n=t.getBoundingClientRect();if(n.bottom<=l.top||n.top>=l.bottom)return;let r=e.tops.get(t.dataset.rowKey),i=void 0===r?-4:r-n.top;.5>Math.abs(i)||a.push({row:t,delta:i,entering:void 0===r})}),a)){let e=t.animate([{transform:`translateY(${n}px)`,opacity:s?.84:1},{transform:"translateY(0)",opacity:1}],{duration:200,easing:"cubic-bezier(.2, .8, .2, 1)"});r.current.add(e),e.onfinish=()=>{r.current.delete(e)}}}),l);return(0,d.jsxs)("div",{ref:w,className:`session-tree${"mobile"===o?" is-mobile":""}${er?" is-group-dragging":""}`,children:[p&&(0,d.jsx)("div",{className:"session-tree-message",children:b("sidebar.loading")}),h&&(0,d.jsx)("div",{className:"session-tree-message is-error",children:h}),ee&&(0,d.jsx)("div",{className:"session-tree-message",children:c}),(0,d.jsx)("div",{ref:j,className:"session-tree-scroll scrollbar-subtle",onScroll:L,onFocus:P,onBlur:z,onPointerDownCapture:D.onPointerDownCapture,onClickCapture:e=>{D.onClickCapture(e),ei(e)},children:!p&&(0,d.jsxs)("div",{ref:k,className:"session-tree-inner",style:{height:O[a.length]},children:[Z.map(e=>{let t=a[e];if("spacer"===t.kind)return null;let n=O[e],r=O[e+1]-n,i=t.key===x;if("session"===t.kind)return(0,d.jsx)(ip,{row:t,layout:o,top:n,height:r,now:T,renaming:t.family.root.id===m,confirming:t.family.root.id===g,menuOpen:i,handlers:y},t.key);if("archive-group"===t.kind)return(0,d.jsx)(ib,{row:t,top:n,height:r,menuOpen:i,handlers:y},t.key);if("group"===t.kind){let e=t.project.key===f;return(0,d.jsx)(ix,{row:t,top:n,height:r,menuOpen:i,renaming:e,canDrag:W&&!e&&F[t.project.pinned?"pinned":"other"]>1,dragPhase:_?.projectKey===t.project.key?_.phase:null,drag:D.handlers,handlers:y},t.key)}return(0,d.jsx)(iv,{row:t,top:n,height:r,handlers:y,onMoreAction:G},t.key)}),et&&(0,d.jsx)("div",{className:"session-tree-drag-source","aria-hidden":"true",style:{top:et.top,height:et.bottom-et.top}}),null!==en&&(0,d.jsx)("div",{className:"session-tree-drop-line","aria-hidden":"true",style:{top:en}})]})}),er&&(0,d.jsxs)("div",{ref:S,className:"session-tree-drag-ghost","aria-hidden":"true",children:[(0,d.jsx)(n3,{size:14,className:"session-tree-group-icon"}),(0,d.jsx)("span",{className:"session-tree-group-name",children:er.name})]})]})}function iu(e,t){return{top:e,height:t}}let ip=(0,u.memo)(function(e){let t,n,{row:r,layout:i,top:s,height:l,now:a,renaming:o,confirming:c,menuOpen:u,handlers:p}=e,{locale:h,t:m}=(0,ns.s)(),{family:f,context:g,status:x}=r,v=f.root,b=io(v),y=new Date(a),w=["session-tree-row session-tree-session",x.selected?"is-selected":"",x.running?"is-running":"","archive"===g?"is-archived":"",u?"is-menu-open":"",c?"is-confirming":"",o?"is-renaming":""].filter(Boolean).join(" ");if(c){let e=b.slice(0,22)+(b.length>22?"…":"");return(0,d.jsx)("div",{className:w,style:iu(s,l),"data-row-key":r.key,onKeyDown:e=>{"Escape"!==e.key||ic(e)||(e.preventDefault(),e.stopPropagation(),p.current.onDeleteCancel())},children:(0,d.jsx)(im,{label:m("sidebar.deleteSession",{title:e}),deleteLabel:m("sidebar.delete"),cancelLabel:m("sidebar.cancel"),onConfirm:e=>{e.stopPropagation(),p.current.onDeleteConfirm(f,e)},onCancel:e=>{e.stopPropagation(),p.current.onDeleteCancel()}})})}if(o)return(0,d.jsx)("div",{className:w,style:iu(s,l),"data-row-key":r.key,children:(0,d.jsx)(ih,{initialValue:b,label:m("sidebar.rename"),onCommit:e=>p.current.onRenameCommit(f,e),onCancel:()=>p.current.onRenameCancel()})});let j=v.isWorktree&&v.branch?v.branch:null,k=v.name&&v.relation?.kind==="fork"?te(v.name):null,S=v.detailsPending?"…":m("sidebar.messagesCount",{count:v.messageCount}),C=`${b}
|
|
5
|
+
${S} \xb7 ${(0,ii.fw)(v.modified,h,y)}${j?` \xb7 ⑂ ${j}`:""}`,N="";x.awaiting?(t=(0,d.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":m("sidebar.agentAwaitingInput")}),N=" is-awaiting",n=m("sidebar.agentAwaitingInput")):x.running?(t=(0,d.jsx)(ri,{size:12,label:m("sidebar.agentRunning")}),N=" is-running",n=m("sidebar.agentRunning")):x.unread?(t=(0,d.jsx)("span",{className:"session-tree-unread",role:"img","aria-label":m("sidebar.newSessionActivity")}),N=" is-unread",n=m("sidebar.newActivity")):t="pinned"===g?(0,d.jsx)("span",{className:"session-tree-project",children:r.project.name}):(0,ii.Rg)(f.latestModified,h,y);let E="desktop"===i&&("archive"===g||!x.running),M=(0,d.jsxs)(d.Fragment,{children:[k?(0,d.jsxs)("span",{className:"session-tree-title has-fork-suffix",children:[(0,d.jsx)("span",{className:"session-tree-title-base",children:k.base}),(0,d.jsx)("span",{className:"session-tree-title-suffix",children:k.suffix})]}):(0,d.jsx)("span",{className:"session-tree-title",children:b}),j&&(0,d.jsxs)("span",{className:"session-tree-branch",children:[(0,d.jsx)(nZ,{size:10,className:"session-tree-branch-icon"}),j]}),(0,d.jsx)("span",{className:`session-tree-meta${N}`,title:n,children:t})]});return(0,d.jsxs)("div",{className:w,style:iu(s,l),"data-row-key":r.key,onClick:()=>p.current.onSelectFamily(f),onContextMenu:e=>p.current.onRowContextMenu(r,e),children:[x.transient?(0,d.jsx)("button",{type:"button",className:"session-tree-main",title:C,"aria-current":x.selected?"true":void 0,children:M}):(0,d.jsx)("a",{className:"session-tree-main",href:J(v.id),title:C,"aria-current":x.selected?"true":void 0,onClick:e=>{e.stopPropagation(),Y(e)&&(e.preventDefault(),p.current.onSelectFamily(f))},children:M}),!x.transient&&(0,d.jsxs)("span",{className:"session-tree-actions",children:[E&&("archive"===g?(0,d.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.restore"),title:m("sidebar.restore"),onClick:e=>{e.stopPropagation(),p.current.onRestoreFamily(f)},children:(0,d.jsx)(nU,{size:13})}):(0,d.jsx)("button",{type:"button",className:"session-tree-action session-tree-quick-action","aria-label":m("sidebar.archive"),title:m("sidebar.archive"),onClick:e=>{e.stopPropagation(),p.current.onArchiveFamily(f)},children:(0,d.jsx)(nH,{size:13})})),(0,d.jsx)("button",{type:"button",className:`session-tree-action session-tree-more-action${u?" is-active":""}`,"aria-label":m("sidebar.moreActions"),title:m("sidebar.moreActions"),"aria-haspopup":"menu","aria-expanded":u,onClick:e=>{let t;e.stopPropagation();let n=e.currentTarget;p.current.onOpenRowMenu(r,{kind:"rect",rect:{left:(t=n.getBoundingClientRect()).left,top:t.top,right:t.right,bottom:t.bottom},align:"end"},n)},children:(0,d.jsx)(nB,{size:14})})]})]})});function ih(e){let{initialValue:t,label:n,maxLength:r,onCommit:i,onCancel:s}=e,[l,a]=(0,u.useState)(t),o=(0,u.useRef)(null),c=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let e=o.current;e&&(e.focus(),e.select())},[]);let p=e=>{c.current||(c.current=!0,i(e))};return(0,d.jsx)("input",{ref:o,className:"session-tree-rename",value:l,"aria-label":n,maxLength:r,onChange:e=>a(e.target.value),onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{if(!ic(e)){if("Enter"===e.key)e.preventDefault(),p(e.currentTarget.value);else if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),c.current)return;c.current=!0,s()}}}})}function im(e){let{label:t,deleteLabel:n,cancelLabel:r,onConfirm:i,onCancel:s}=e,l=(0,u.useRef)(null);return(0,u.useEffect)(()=>{let e=document.activeElement;e&&e!==document.body||l.current?.focus()},[]),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"session-tree-confirm-text",children:t}),(0,d.jsxs)("button",{type:"button",className:"session-tree-confirm-delete",onClick:i,children:[(0,d.jsx)(nG,{size:12}),n]}),(0,d.jsx)("button",{ref:l,type:"button",className:"session-tree-confirm-cancel",onClick:s,children:r})]})}function ig(e){let{running:t,awaiting:n=0,unread:r,t:i}=e;return 0===t&&0===n&&0===r?null:(0,d.jsxs)("span",{className:"session-tree-summary",children:[t>0&&(0,d.jsxs)("span",{className:"session-tree-summary-running",role:"img",title:i("sidebar.agentRunning"),"aria-label":`${i("sidebar.agentRunning")} (${t})`,children:[(0,d.jsx)(ri,{size:10}),t]}),n>0&&(0,d.jsxs)("span",{className:"session-tree-summary-awaiting",role:"img",title:i("sidebar.agentAwaitingInput"),"aria-label":`${i("sidebar.agentAwaitingInput")} (${n})`,children:[(0,d.jsx)("span",{className:"session-tree-summary-dot is-awaiting"}),n]}),r>0&&(0,d.jsxs)("span",{className:"session-tree-summary-unread",role:"img",title:i("sidebar.newSessionActivity"),"aria-label":`${i("sidebar.newSessionActivity")} (${r})`,children:[(0,d.jsx)("span",{className:"session-tree-summary-dot"}),r]})]})}let ix=(0,u.memo)(function(e){let{row:t,top:n,height:r,menuOpen:i,renaming:s,canDrag:l,dragPhase:a,drag:o,handlers:c}=e,{t:p}=(0,ns.s)(),{project:h,expanded:m}=t,f=(0,u.useRef)(null),g=["session-tree-row session-tree-group",h.current?"is-current":"",i?"is-active":"","armed"===a?"is-drag-armed":""].filter(Boolean).join(" ");return((0,u.useEffect)(()=>{let e=f.current;if(!l||!e)return;let t=e=>o.onTouchMove(e);return e.addEventListener("touchmove",t,{passive:!1}),()=>e.removeEventListener("touchmove",t)},[l,o]),s)?(0,d.jsx)("div",{ref:f,className:`${g} is-renaming`,style:iu(n,r),"data-row-key":t.key,children:(0,d.jsx)(ih,{initialValue:h.name,label:p("sidebar.projectName"),maxLength:80,onCommit:e=>c.current.onRenameProjectCommit(h,e),onCancel:()=>c.current.onRenameProjectCancel()})}):(0,d.jsxs)("div",{ref:f,className:g,style:iu(n,r),"data-row-key":t.key,onPointerDown:l?e=>o.onPointerDown(e,h.key):void 0,children:[(0,d.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":m,title:h.root,onClick:e=>c.current.onToggleGroup(h.key,e.altKey),children:[(0,d.jsx)(n3,{size:14,open:m,className:`session-tree-group-icon${m?" is-open":""}`}),(0,d.jsx)("span",{className:"session-tree-group-name",children:h.name}),!m&&(0,d.jsx)(ig,{running:t.running,awaiting:t.awaiting,unread:t.unread,t:p})]}),(0,d.jsxs)("span",{className:"session-tree-group-actions",children:[(0,d.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(),c.current.onGroupNew(h)},children:(0,d.jsx)(n_,{size:13})}),(0,d.jsx)("button",{type:"button",className:`session-tree-group-action${i?" is-active":""}`,"aria-label":p("sidebar.projectActions",{name:h.name}),title:p("sidebar.projectActions",{name:h.name}),"aria-haspopup":"menu","aria-expanded":i,onClick:e=>{e.stopPropagation(),c.current.onGroupMenu(h,e.currentTarget)},children:(0,d.jsx)(nB,{size:13})})]})]})}),iv=(0,u.memo)(function(e){let{row:t,top:n,height:r,handlers:i,onMoreAction:s}=e,{t:l}=(0,ns.s)(),a=iu(n,r);switch(t.kind){case"section":return(0,d.jsx)("div",{className:`session-tree-row session-tree-section${"projects"===t.label?" is-projects":""}`,style:a,"data-row-key":t.key,role:"projects"!==t.label?"heading":void 0,"aria-level":"projects"!==t.label?2:void 0,children:"projects"!==t.label?(0,d.jsxs)("button",{type:"button",className:`session-tree-section-toggle${"recents"===t.label?" session-tree-recents-toggle":""}`,disabled:0===t.count,"aria-expanded":t.count>0?!t.collapsed:void 0,onClick:()=>{"recents"===t.label?i.current.onToggleRecents?.():i.current.onToggleSubagents?.()},children:["recents"===t.label?(0,d.jsx)(nF,{size:12,strokeWidth:2}):(0,d.jsx)(nW,{size:12,strokeWidth:2}),(0,d.jsx)("span",{children:l("recents"===t.label?"sidebar.recents":"sidebar.subagents")}),(0,d.jsx)("span",{className:"session-tree-section-count",children:t.count}),t.count>0&&(0,d.jsx)(nV,{size:12,className:`session-tree-chevron${t.collapsed?"":" is-open"}`})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{role:"heading","aria-level":2,children:l("sidebar.projects")}),(0,d.jsx)("button",{type:"button",className:"session-tree-section-action","aria-label":l("projectCreate.title"),title:l("projectCreate.title"),"aria-haspopup":"dialog",onClick:e=>i.current.onOpenOtherProject(e.currentTarget),children:(0,d.jsx)(n_,{size:16})})]})});case"recent":case"subagent":{let e="subagent"===t.kind,n=e?t.session:t.family.root,r=e?b(n):io(n);return(0,d.jsx)("div",{className:`session-tree-row session-tree-${t.kind}${t.status.selected?" is-selected":""}`,style:a,"data-row-key":t.key,children:(0,d.jsxs)("a",{className:"session-tree-main",href:J(n.id),title:`${r} \xb7 ${t.project.name}`,"aria-current":t.status.selected?"page":void 0,onClick:n=>{Y(n)&&(!e||i.current.onSelectSubagent)&&(n.preventDefault(),e?i.current.onSelectSubagent?.(t.session):i.current.onSelectFamily(t.family))},children:[e&&(0,d.jsx)("span",{className:"session-tree-subagent-avatar","aria-hidden":"true",style:ie(n.id),children:(0,d.jsx)(nW,{size:15})}),(0,d.jsx)("span",{className:"session-tree-title",children:r}),(0,d.jsx)(ig,{running:Number(t.status.running),awaiting:e?Number(t.status.awaiting):0,unread:Number(t.status.unread),t:l})]})})}case"pinned-header":return(0,d.jsx)("div",{className:"session-tree-row session-tree-pinned-header",style:a,"data-row-key":t.key,children:(0,d.jsxs)("button",{type:"button",className:"session-tree-pinned-toggle","aria-expanded":!t.collapsed,onClick:()=>i.current.onTogglePinned(),children:[(0,d.jsx)(nV,{size:12,strokeWidth:3,className:`session-tree-chevron${t.collapsed?"":" is-open"}`}),(0,d.jsx)("span",{className:"session-tree-pinned-label",children:l("sidebar.pinned")}),(0,d.jsxs)("span",{className:"session-tree-pinned-count",children:["\xb7 ",t.count]}),t.collapsed&&t.running>0&&(0,d.jsx)("span",{className:"session-tree-pinned-dot is-running",role:"img",title:l("sidebar.agentRunning"),"aria-label":`${l("sidebar.agentRunning")} (${t.running})`}),t.collapsed&&t.awaiting>0&&(0,d.jsx)("span",{className:"session-tree-pinned-dot is-awaiting",role:"img",title:l("sidebar.agentAwaitingInput"),"aria-label":`${l("sidebar.agentAwaitingInput")} (${t.awaiting})`}),t.collapsed&&t.unread>0&&(0,d.jsx)("span",{className:"session-tree-pinned-dot is-unread",role:"img",title:l("sidebar.newSessionActivity"),"aria-label":`${l("sidebar.newSessionActivity")} (${t.unread})`})]})});case"pinned-more":case"group-more":{let e="pinned-more"===t.kind?eM:t.projectKey;return(0,d.jsxs)("div",{className:"session-tree-row session-tree-more",style:a,"data-row-key":t.key,children:[t.hidden>0&&(0,d.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"more",onClick:n=>s(t.key,e,"more",n.currentTarget),children:l("sidebar.showMore",{count:t.hidden})}),t.canShowLess&&(0,d.jsx)("button",{type:"button",className:"session-tree-more-toggle","data-more-action":"less",onClick:n=>s(t.key,e,"less",n.currentTarget),children:l("sidebar.showLess")})]})}case"group-empty":return(0,d.jsxs)("div",{className:"session-tree-row session-tree-group-empty",style:a,"data-row-key":t.key,children:[(0,d.jsx)("span",{className:"session-tree-group-empty-label",children:l("sidebar.noLiveSessions")}),!t.project.pinned&&(0,d.jsx)("button",{type:"button",className:"session-tree-more-toggle",onClick:()=>i.current.onPinEmptyGroup(t.project),children:l("sidebar.pinToKeep")})]});case"footer-open":return(0,d.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,d.jsxs)("button",{type:"button",className:"session-tree-footer-button","aria-haspopup":"dialog",onClick:e=>i.current.onOpenOtherProject(e.currentTarget),children:[(0,d.jsx)(n6,{size:12}),(0,d.jsx)("span",{className:"session-tree-footer-label",children:l("projectCreate.title")})]})});case"footer-archived":return(0,d.jsx)("div",{className:"session-tree-row session-tree-footer",style:a,"data-row-key":t.key,children:(0,d.jsxs)("button",{type:"button",className:"session-tree-footer-button",onClick:()=>i.current.onOpenArchive(),children:[(0,d.jsx)(nH,{size:12}),(0,d.jsx)("span",{className:"session-tree-footer-label",children:l("sidebar.archivedCount",{count:t.count})}),(0,d.jsx)(nV,{size:10,className:"session-tree-footer-chevron"})]})})}}),ib=(0,u.memo)(function(e){let{row:t,top:n,height:r,menuOpen:i,handlers:s}=e,{t:l}=(0,ns.s)(),{project:a,expanded:o}=t,c=["session-tree-row session-tree-group session-tree-archive-group",a.current?"is-current":"",i?"is-active":""].filter(Boolean).join(" ");return(0,d.jsxs)("div",{className:c,style:iu(n,r),"data-row-key":t.key,children:[(0,d.jsxs)("button",{type:"button",className:"session-tree-group-toggle","aria-expanded":o,title:a.root,onClick:e=>s.current.onToggleArchiveGroup?.(a.key,e.altKey),children:[(0,d.jsx)(nV,{size:12,strokeWidth:3,className:`session-tree-chevron${o?" is-open":""}`}),(0,d.jsx)(n3,{size:14,open:o,className:`session-tree-group-icon${o?" is-open":""}`}),(0,d.jsx)("span",{className:"session-tree-group-name",children:a.name}),(0,d.jsxs)("span",{className:"session-tree-archive-group-count",children:["\xb7 ",t.count]})]}),(0,d.jsx)("span",{className:"session-tree-group-actions",children:(0,d.jsx)("button",{type:"button",className:`session-tree-group-action${i?" is-active":""}`,"aria-label":l("sidebar.archivedProjectActions",{name:a.name}),title:l("sidebar.archivedProjectActions",{name:a.name}),"aria-haspopup":"menu","aria-expanded":i,onClick:e=>{e.stopPropagation(),s.current.onArchiveGroupMenu?.(a,e.currentTarget)},children:(0,d.jsx)(nB,{size:13})})})]})});function iy(e){let{heading:t,busy:n,error:r,showCancel:i,onCreate:s,onCancel:l}=e,{t:a}=(0,ns.s)(),[o,c]=(0,u.useState)(""),p=o.trim(),h=()=>{p&&!n&&s(p)};return(0,d.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,d.jsx)("div",{className:"sidebar-menu-header",children:t}),(0,d.jsx)("input",{className:"sidebar-worktree-input","data-sidebar-menu-autofocus":"",value:o,readOnly:n,placeholder:a("sidebar.branchName"),"aria-label":a("sidebar.branchName"),onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),h())}}),(0,d.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[(0,d.jsx)("button",{type:"button",className:"sidebar-worktree-create",disabled:n||!p,onClick:h,children:a(n?"sidebar.creating":"sidebar.create")}),i&&(0,d.jsx)("button",{type:"button",className:"sidebar-worktree-cancel",onClick:l,children:a("sidebar.cancel")})]}),r&&(0,d.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:r})]})}function iw(e,t){return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function ij(e){return e.branch??eW(e.path)}function ik(e){let{heading:t,dirty:n,busy:r,error:i,showCancel:s,onForce:l,onCancel:a}=e,{t:o}=(0,ns.s)();return(0,d.jsxs)("div",{className:"sidebar-worktree-form",children:[t&&(0,d.jsx)("div",{className:"sidebar-menu-header",children:t}),n&&(0,d.jsx)("div",{className:"sidebar-worktree-message",children:o("sidebar.forceRemoveCheckout")}),(n||s)&&(0,d.jsxs)("div",{className:"sidebar-worktree-form-buttons",children:[n&&(0,d.jsx)("button",{type:"button",className:"sidebar-worktree-force",disabled:r,onClick:l,children:o("sidebar.force")}),s&&(0,d.jsx)("button",{type:"button",className:"sidebar-worktree-cancel","data-sidebar-menu-autofocus":"",onClick:a,children:o("sidebar.cancel")})]}),i&&(0,d.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:i})]})}function iS(e){let{busy:t,onForce:n,onCancel:r}=e,{t:i}=(0,ns.s)(),s=(0,u.useId)();return(0,d.jsxs)("div",{className:"sidebar-worktree-confirm",children:[(0,d.jsx)("span",{id:s,className:"sidebar-worktree-confirm-text",title:i("sidebar.forceRemoveCheckout"),children:i("sidebar.forceRemoveCheckout")}),(0,d.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","aria-describedby":s,"aria-disabled":!!t||void 0,className:"sidebar-worktree-force",onClick:()=>{t||n()},children:i("sidebar.force")}),(0,d.jsx)("button",{type:"button",role:"menuitem",tabIndex:-1,"data-sidebar-menu-item":"","data-sidebar-menu-autofocus":"",className:"sidebar-worktree-cancel",onClick:r,children:i("sidebar.cancel")})]})}function iC(e){let t,n,{layout:r,context:i,mobile:s,label:l,placeholder:a="",homeDir:o,projectActivity:c,worktreeHint:p=null,newWorktreeTitle:h,handleRef:m,onPick:f,onUseDefaultDirectory:g,onOpenFolder:x,onRefreshWorktrees:v,onCreateWorktree:b,onRemoveWorktree:y}=e,{t:w}=(0,ns.s)(),[j,k]=(0,u.useState)(null),S=(0,u.useRef)(j);S.current=j;let C=(0,u.useRef)(0),N=(0,u.useRef)(null),E=(0,u.useRef)(null),M=(0,u.useRef)(!1),$=(0,u.useRef)(f);$.current=f;let I="inline"!==r,T=!I,R=!s,{project:A,worktrees:L}=i,P=(t=i.worktrees??[]).find(e=>e.path===i.currentWorktreePath)??t.find(e=>e.isMain)??null,z=T&&A?t$(tE(i)).find(e=>{let{choice:t}=e;return t.key===A.key}):void 0;(0,u.useEffect)(()=>(M.current=!0,()=>{M.current=!1}),[]);let O=()=>(C.current+=1,C.current),W=()=>k(null),F=(e,t)=>{let n=t.getBoundingClientRect(),i=Math.max(I?220:"project"===e?260:240,Math.round(n.width));k({id:O(),kind:e,anchor:{kind:"rect",rect:{left:n.left,top:n.top,right:n.right,bottom:n.bottom},align:"row"===r&&"worktree"===e?"end":"start"},opener:t,width:i,body:null,removing:!1}),"worktree"===e&&v()},D=(0,u.useRef)(F);D.current=F,(0,u.useImperativeHandle)(m,()=>({button:e=>("worktree"===e?E:N).current,openMenu:(e,t)=>{let n=t??("worktree"===e?E:N).current;n&&D.current(e,n)}}),[]);let _=(e,t)=>{k(n=>n?.id===e?t(n):n)},B=e=>{let t=O();k(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)=>{_(r,n=>({...n,body:{kind:"create",busy:e,error:t}}))};i(!0,null);try{t=await b(A,e)}catch(e){t={error:e instanceof Error?e.message:String(e)}}M.current&&("error"in t?i(!1,t.error):S.current?.id===r&&(k(null),$.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;_(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)}}M.current&&_(i,t=>{if("removed"===n)return{...t,removing:!1,body:null};let r="dirty"===n||t.body?.kind==="remove"&&t.body.dirty;return{...t,removing:!1,body:{kind:"remove",worktree:e,dirty:r,busy:!1,error:"dirty"===n?null:n.error}}})},K=()=>[...(L??[]).map(e=>R&&q?.kind==="remove"&&q.dirty&&q.worktree.path===e.path?{type:"custom",id:`worktree:${e.path}`,content:(0,d.jsx)(iS,{busy:q.busy,onForce:()=>{U(e,!0)},onCancel:()=>B(null)})}:{type:"item",id:`worktree:${e.path}`,label:R?e.branch??iw(e.path,o):ij(e),mono:R,path:R,note:e.isMain?w("sidebar.main"):void 0,title:e.path,checked:e.path===P?.path,secondary:y&&!e.isMain?{label:w("sidebar.removeWorktreeTitle",{path:e.path}),icon:(0,d.jsx)(nG,{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&&f({cwd:e.path,projectKey:A.key,projectRoot:A.root},"worktree")}}),...R?[]:[{type:"separator",id:"separator"}],...R&&q?.kind==="create"?[]:[{type:"item",id:"new-worktree",label:w("sidebar.newWorktree"),icon:(0,d.jsx)(n_,{size:13}),onSelect:e=>{let{keepOpen:t}=e;t(),B({kind:"create",busy:!1,error:null})}}]],q=j?.kind==="worktree"?j.body:null,V="",Z=null,J=null;if(R&&j?.kind==="worktree")V=w("sidebar.switchWorktree"),n=K(),q?.kind==="create"?J=(0,d.jsx)(iy,{heading:null,busy:q.busy,error:q.error,showCancel:!0,onCreate:e=>{H(e)},onCancel:()=>B(null)}):q?.kind==="remove"&&q.error&&(J=(0,d.jsx)("div",{className:"sidebar-worktree-error",role:"alert",children:q.error}));else if(q?.kind==="create")V=h,Z=(0,d.jsx)(iy,{heading:s?null:V,busy:q.busy,error:q.error,showCancel:!s,onCreate:e=>{H(e)},onCancel:W});else if(q?.kind==="remove")V=w("sidebar.removeWorktreeHeading",{name:ij(q.worktree)}),Z=(0,d.jsx)(ik,{heading:s?null:V,dirty:q.dirty,busy:q.busy,error:q.error,showCancel:!s,onForce:()=>{U(q.worktree,!0)},onCancel:W});else if(j?.kind==="project"){let e,t;V=w("workspace.project"),t=(e=t$(tE(i)).map(e=>{let{choice:t,name:n,note:r}=e,i=c?.get(t.key),s=R&&void 0===t.alias;return{type:"item",id:`project:${t.key}`,label:s?iw(t.root,o):n,note:s?void 0:r??void 0,mono:R,path:s,title:t.root,checked:t.key===A?.key,badge:i?(0,d.jsx)(ig,{running:i.running,unread:i.unread,t:w}):void 0,onSelect:()=>{f({cwd:t.key===A?.key&&L?P?.path??t.root:t.root,projectKey:t.key,projectRoot:t.root},"project")}}})).length>0?[{type:"separator",id:"separator"}]:[],n=[...e,...t,{type:"item",id:"default-directory",label:w("sidebar.useDefaultDirectory"),icon:(0,d.jsx)(n3,{size:13}),onSelect:()=>g()},{type:"item",id:"open-folder",label:w(R?"sidebar.customPath":"sidebar.openOtherProject"),icon:R?(0,d.jsx)(n_,{size:13}):(0,d.jsx)(n6,{size:13}),onSelect:()=>x(j?.opener??null)}]}else j?.kind==="worktree"&&(V=w("sidebar.switchWorktree"),n=K());let Y=j?.kind==="project"?{placeholder:w("sidebar.filterProjects"),emptyLabel:w("sidebar.noMatchingProjects"),minChoices:R?9:void 0}:{placeholder:w("sidebar.filterWorktrees"),emptyLabel:w("sidebar.noMatchingWorktrees")},G=I&&void 0!==c&&[...c].some(e=>{let[t,{running:n,unread:r}]=e;return t!==A?.key&&(n>0||r>0)});return(0,d.jsxs)("div",{className:`project-picker is-${r}`,role:"group","aria-label":l,children:[(0,d.jsxs)("button",{ref:N,type:"button",className:A?"project-picker-button is-project":"project-picker-button is-project is-empty",title:A?.root??"","aria-haspopup":"menu","aria-expanded":j?.kind==="project",onClick:e=>F("project",e.currentTarget),children:[T&&(0,d.jsx)(n3,{size:12,className:"project-picker-icon"}),T&&A?(0,d.jsxs)("span",{className:"project-picker-name",children:[void 0===A.alias&&z?.note&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"project-picker-parent",children:z.note}),"/"]}),(0,d.jsx)("span",{className:"project-picker-leaf",children:A.alias??z?.name??eW(A.root)})]}):A?.alias!==void 0?(0,d.jsx)("span",{className:"project-picker-label is-alias",children:A.alias}):A?(0,d.jsx)("span",{className:"project-picker-path",children:(0,d.jsx)("span",{children:iw(A.root,o)})}):(0,d.jsx)("span",{className:"project-picker-label",children:a}),G&&(0,d.jsx)("span",{className:"project-picker-activity",role:"img",title:w("sidebar.newActivity"),"aria-label":w("sidebar.newActivity")}),T&&(0,d.jsx)(nV,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),L&&(0,d.jsxs)("button",{ref:E,type:"button",className:"project-picker-button",title:P?w("sidebar.worktreePath",{path:P.path}):w("sidebar.switchWorktree"),"aria-haspopup":"menu","aria-expanded":j?.kind==="worktree",onClick:e=>F("worktree",e.currentTarget),children:[(0,d.jsx)(nZ,{size:11,className:P&&!P.isMain?"project-picker-icon is-linked":"project-picker-icon"}),(0,d.jsx)("span",{className:"project-picker-path",children:(0,d.jsx)("span",{children:P?P.branch??iw(P.path,o):"…"})}),P?.isMain&&"stacked"===r&&(0,d.jsx)("span",{className:"project-picker-note",children:w("sidebar.main")}),I&&L.length>1&&(0,d.jsx)("span",{className:"project-picker-note",children:L.length}),(0,d.jsx)(nV,{size:9,className:"project-picker-chevron sidebar-icon-down"})]}),!L&&I&&p&&(0,d.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:p.title,className:"project-picker-button is-inactive",children:[(0,d.jsx)(nZ,{size:11,className:"project-picker-icon"}),(0,d.jsx)("span",{className:"project-picker-label",children:p.label})]}),(0,d.jsx)(r4,{open:null!==j,anchor:j?.anchor??null,sheet:s,ariaLabel:V,title:V,items:n,filter:Y,cancelLabel:w("sidebar.cancel"),focusCancel:q?.kind==="remove",onClose:W,returnFocusTo:j?.opener??null,width:j?.width,classic:R,footer:J,focusKey:q?`${q.kind}:${"remove"===q.kind&&q.dirty}`:"list",children:Z})]})}function iN(e,t,n){if(e.relation?.kind!=="side")return null;let r=e.relation.parentSessionId,i=t.find(e=>e.id===r),s=i?.name||i?.firstMessage||void 0,l=t.filter(e=>e.relation?.kind==="side"&&e.relation.parentSessionId===r),a=l.some(t=>t.id===e.id)?l:[...l,e];return{parentSessionId:r,...s?{parentTitle:s}:{},label:x(e,n,a)}}function iE(e){let{open:t,query:n,children:r,selectedSessionId:i,onSelectSession:s,onSelectSideChat:l,sessions:a,archivedSessionIds:o,projectNames:c}=e,{t:p,locale:h}=(0,ns.s)(),[m,f]=(0,u.useState)({query:""}),g=n.trim(),x=m.query===g?m.response:void 0,v=m.query===g&&m.failed;return(0,u.useEffect)(()=>{if(!t||!g)return;let e=new AbortController;f({query:g});let n=setTimeout(async()=>{try{let t=await fetch(`/api/sessions/search?${new URLSearchParams({q:g})}`,{signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e.signal.aborted||f({query:g,response:n})}catch{e.signal.aborted||f({query:g,failed:!0})}},300);return()=>{clearTimeout(n),e.abort()}},[t,g]),t&&g?(0,d.jsxs)("div",{className:"session-search-results min-h-20 flex-1 overflow-y-auto","aria-busy":!x&&!v,onKeyDown:e=>{if(e.nativeEvent.isComposing||229===e.keyCode)return;let t=Array.from(e.currentTarget.querySelectorAll("[data-session-search-result]")),n=t.indexOf(e.target);if(!(n<0)){if("Escape"===e.key||"ArrowUp"===e.key&&0===n)e.preventDefault(),e.stopPropagation(),document.getElementById("session-search-input")?.focus({preventScroll:!0});else if(["ArrowDown","ArrowUp","Home","End"].includes(e.key)){e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:Math.max(0,Math.min(t.length-1,n+("ArrowUp"===e.key?-1:1)));t[r]?.focus()}}},children:[(0,d.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:v?p("sidebar.sessionSearchFailed"):x?0===x.results.length?p("sidebar.sessionSearchEmpty"):p("sidebar.sessionSearchCount",{count:x.results.length}):p("sidebar.sessionSearching")}),x?.truncated&&(0,d.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:p("sidebar.sessionSearchPartial")}),x?.results.map(e=>{let t,n,{session:r,entryId:u,blockIndex:m,titleMatch:f,before:g,match:x,after:v}=e,b=r.relation?.kind==="side"?r.relation:null,y=b?iN(r,a,p("agentSwitcher.sideChat")):null,w=y?y.label:r.name||r.firstMessage;return(0,d.jsxs)("button",{"data-session-search-result":"",type:"button",onClick:()=>{b&&r.id!==i?l(r):s(r,u,m)},"aria-current":r.id===i?"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 ${r.id===i?"bg-bg-selected":""}`,children:[(0,d.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,d.jsx)("span",{className:"min-w-0 truncate text-xs font-medium text-text",children:f?(0,d.jsxs)(d.Fragment,{children:[g,(0,d.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:x}),v]}):w}),o?.has(r.id)&&(0,d.jsx)("span",{className:"shrink-0 rounded-[4px] border border-border px-1 text-[10px] leading-[14px] text-text-dim",children:p("sidebar.archived")})]}),y&&(0,d.jsx)("span",{className:"mt-1 block truncate text-[10px] text-text-dim",title:y.parentTitle,children:y.parentTitle?p("sidebar.sideChatOf",{name:y.parentTitle}):p("agentSwitcher.sideChat")}),(0,d.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,d.jsxs)("span",{className:"min-w-0 flex-1 truncate",title:r.cwd,children:[(0,d.jsx)("span",{className:"font-medium text-text-muted",children:(t=et(r),n=r.projectRoot??r.cwd,c&&Object.hasOwn(c,t)?c[t]:eW(n))}),r.cwd!==(r.projectRoot??r.cwd)&&` \xb7 ${r.cwd}`]}),(0,d.jsx)("span",{className:"shrink-0",children:(0,ii.fw)(r.modified,h)})]}),!f&&(0,d.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[g,(0,d.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:x}),v]})]},r.id)})]}):r}function iM(e){let{toast:t,dismissLabel:n,durationMs:r,onDismissRef:i}=e,s=(0,u.useRef)(null),[l,a]=(0,u.useState)(!1),[o,c]=(0,u.useState)(!1),p=l||o;return(0,u.useLayoutEffect)(()=>{let e=s.current;e&&window.matchMedia?.("(hover: hover)").matches&&e.matches(":hover")&&a(!0)},[]),(0,u.useEffect)(()=>{if(p)return;let e=window.setTimeout(()=>i.current(),r);return()=>window.clearTimeout(e)},[p,r,i]),(0,d.jsxs)("div",{ref:s,className:"sidebar-toast",onPointerEnter:e=>{"mouse"===e.pointerType&&a(!0)},onPointerLeave:()=>a(!1),onFocus:()=>c(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||c(!1)},children:[t.tail?(0,d.jsxs)("span",{className:"sidebar-toast-message has-tail",title:t.message+t.tail,children:[(0,d.jsx)("span",{className:"sidebar-toast-message-head",children:t.message}),(0,d.jsx)("span",{className:"sidebar-toast-message-tail",children:t.tail})]}):(0,d.jsx)("span",{className:"sidebar-toast-message",title:t.message,children:t.message}),t.actions.map(e=>(0,d.jsx)("button",{type:"button",className:"sidebar-toast-action",onClick:()=>{i.current(),e.onClick()},children:e.label},e.id)),(0,d.jsx)("button",{type:"button",className:"sidebar-toast-dismiss","aria-label":n,title:n,onClick:()=>i.current(),children:(0,d.jsx)(n2,{size:12})})]})}function i$(e){let{toast:t,onDismiss:n,dismissLabel:r,durationMs:i=1e4}=e,s=(0,u.useRef)(n);return s.current=n,(0,d.jsx)("div",{className:"sidebar-toast-region",role:"status","aria-live":"polite",children:t?(0,d.jsx)(iM,{toast:t,dismissLabel:r,durationMs:i,onDismissRef:s},t.id):null})}let iI={remote:"sidebar.openInExplorerRemoteOnly","unsupported-platform":"sidebar.openInExplorerUnsupported"};function iT(e){let{ref:t,onClick:n,title:r,disabled:i,pressed:s,expanded:l,controls:a,done:o,className:c,children:u}=e;return(0,d.jsx)("button",{ref:t,type:"button",onClick:n,disabled:i,title:r,"aria-label":r,"aria-pressed":s,"aria-expanded":l,"aria-controls":a,className:`sidebar-tool-button${s||l?" is-active":""}${o?" is-done":""}${c?` ${c}`:""}`,children:u})}let iR="pi-web:last-custom-cwd",iA={"open-new-tab":"sidebar.openInNewTab",pin:"sidebar.pin",unpin:"sidebar.unpin",rename:"sidebar.rename",fork:"sidebar.fork","mark-read":"sidebar.markRead","mark-unread":"sidebar.markUnread",archive:"sidebar.archive",unarchive:"sidebar.unarchive",delete:"sidebar.delete"};function iL(){try{return window.localStorage.getItem(iR)??""}catch{return""}}function iP(e){try{window.localStorage.setItem(iR,e)}catch{}}function iz(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 iO(e,t){return e.length>t?`${e.slice(0,t)}…`:e}function iW(e){let t=document.activeElement;e&&t instanceof HTMLElement&&t!==document.body&&(0===t.getClientRects().length||null!==t.closest("[inert]"))?e.focus({preventScroll:!0}):t_(document,e)}function iF(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 iD(e){var t,n,r;let i,s,l,a,o,c,p,h,{onOpenArchive:m,archiveActive:g=!1,onArchiveStateChange:x,fileExplorerTarget:b,selectedSessionId:j,onSelectSession:k,onSelectSideChat:S,onNewSession:C,onOpenSettings:N,controlRef:E,onNewSessionContextChange:M,initialSessionId:$,initialSessionLinked:I,skipInitialProjectSelection:T,onInitialRestoreDone:R,refreshKey:A,onSessionDeleted:L,selectedCwd:P,onCwdChange:z,onOpenFile:O,onOpenTerminal:W,explorerRefreshKey:F,onExplorerRefresh:D,onAtMention:_,onAtMentions:B,onBackgroundTaskDone:H,hiddenFinishedSessionIds:K,onRunningSessionIdsChange:q,onSessionsChange:V}=e,{t:Z}=(0,ns.s)(),Y=nf(),[G,X]=(0,u.useState)([]),Q=(0,u.useRef)(null),ee=(0,u.useRef)(0),er=(0,u.useRef)(null),[es,el]=(0,u.useState)(!0),[ea,eo]=(0,u.useState)(!1),[ec,eh]=(0,u.useState)(null),[ev,eb]=(0,u.useState)(null),[eE,eL]=(0,u.useState)(""),[eQ,e0]=(0,u.useState)(!1),[e1,e4]=(0,u.useState)(iL),[e3,e8]=(0,u.useState)(null),[e6,e5]=(0,u.useState)(!1),[e9,e7]=(0,u.useState)(!1),[tt,th]=(0,u.useState)(null),tC=(0,u.useRef)(null),[t$,tI]=(0,u.useState)(null),[tA,tO]=(0,u.useState)(null),tW=(0,u.useRef)(null);tW.current??=new Set(tw());let[tF,tD]=(0,u.useState)(0),[tB,tH]=(0,u.useState)(!1),[tU,tK]=(0,u.useState)(!1),[tq,tV]=(0,u.useState)(!1),[tZ,tJ]=(0,u.useState)(""),[tY,tG]=(0,u.useState)(0),[tQ,t0]=(0,u.useState)(!0),[t6,t7]=(0,u.useState)(!1),[nn,nr]=(0,u.useState)(!1),[nl,na]=(0,u.useState)(null),[no,nc]=(0,u.useState)(null),[nd,nu]=(0,u.useState)(()=>new Set),[np,nh]=(0,u.useState)(()=>new Set),[nm,ng]=(0,u.useState)(()=>new Set),[nx,nv]=(0,u.useState)(()=>(function(){try{return t4(window.localStorage.getItem(t1))}catch{return new Map}})()),nb=(0,u.useRef)(new Set),ny=(0,u.useRef)(new Set),nS=(0,u.useRef)({latest:null,before:null}),nE=(0,u.useRef)(null);nE.current??=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Date.now,t=0;return{note(e,n,r){t2(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 nM=(0,u.useRef)(new Set),n$=(0,u.useRef)(new Set),nI=(0,u.useRef)(new Set),nT=(0,u.useRef)(new Set),nR=(0,u.useRef)(!1),nA=(0,u.useRef)(null),nL=(0,u.useRef)(null),nP=(0,u.useRef)(null),nz=ni.use(),nW=!!b,nF=!nW&&!Y&&"below"===nz,[nD,n_]=(0,u.useState)("sessions"),[nZ,n2]=(0,u.useState)(!1),n4=(0,u.useRef)(null),n6=(0,u.useRef)(null),ri=(0,u.useRef)(null),rs=(0,u.useRef)(null),rl=(0,u.useRef)(new WeakMap),[rc,rd]=(0,u.useState)({}),[ru,rp]=(0,u.useState)(()=>new Set),[rh,rm]=(0,u.useState)({}),[rf,rg]=(0,u.useState)(!1),[rx,rv]=(0,u.useState)(!1),[rb,ry]=(0,u.useState)(!1),[rw,rj]=(0,u.useState)(!1),[rk,rS]=(0,u.useState)([]),[rC,rN]=(0,u.useState)(!1),{phase:rE,start:rM,end:r$}=f(),{phase:rI,start:rT,end:rR}=f(),rA=(0,u.useRef)(nZ);rA.current=nZ;let rL=(0,u.useRef)(rC);rL.current=rC;let rP=(0,u.useCallback)(e=>{e!==rL.current&&rT(e?"in":"out"),rN(e)},[rT]),rz=(i=nZ&&"out"===rE,s=!nZ&&"in"===rE,{bodyHidden:nZ&&!i,bodyInert:i,moving:i||s,open:!nZ&&!s}),rO=(l=rC&&"in"===rI,a=!rC&&"out"===rI,{mainHidden:rC&&!l,mainInert:l,archiveMounted:rC||a,archiveInert:a,archiveClass:l?"is-entering":a?"is-leaving":null}),[rW,rF]=(0,u.useState)(null),[r_,rB]=(0,u.useState)(null),[rH,rU]=(0,u.useState)(null),[rK,rq]=(0,u.useState)(null),[rV,rZ]=(0,u.useState)(null),rJ=(0,u.useRef)(0),rY=(0,u.useCallback)(e=>{rZ(t=>t?.id===e?null:t)},[]),[rG,rX]=(0,u.useState)(null),rQ=(0,u.useCallback)(e=>{rX(t=>t?.id===e?null:t)},[]),r0=(0,u.useRef)(j);r0.current=j;let[r1,r2]=(0,u.useState)(null),r3=(0,u.useRef)(0),r6=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2?arguments[2]:void 0;r3.current+=1,r2({id:r3.current,message:e,...n?{tail:n}:{},actions:t})},[]),[r5,r9]=(0,u.useState)(0),r7=(0,u.useRef)(0),ie=(0,u.useRef)(null),[it,ir]=(0,u.useState)(0),ii=(0,u.useRef)(null),is=(0,u.useRef)(null),il=(0,u.useRef)(null),ia=(0,u.useRef)(null),[ic,iu]=(0,u.useState)(0),ip=(0,u.useCallback)(e=>{ia.current=e,iu(e=>e+1)},[]);(0,u.useEffect)(()=>{let e=ia.current;ia.current=null,e&&t_(document,e())},[ic]);let{state:ih,loaded:im,synced:ig,error:ix,apply:iv,snapshot:ib,noteRevision:iy,refresh:iw}=function(){let[e,t]=(0,u.useState)(ey),[n,r]=(0,u.useState)(!1),[i,s]=(0,u.useState)(!1),[l,a]=(0,u.useState)(null),o=(0,u.useRef)(e),c=(0,u.useRef)(e),d=(0,u.useRef)([]),p=(0,u.useRef)(Promise.resolve()),h=(0,u.useRef)(0),m=(0,u.useRef)(null),f=(0,u.useCallback)(()=>{let e=o.current;for(let{request:t,now:n}of d.current)e=function e(t,n,r){var i,s,l,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.removedProjects&&(r.removedProjects={...e.removedProjects}),e.readAt&&(r.readAt={...e.readAt}),r}(t),c=!1;switch(n.action){case"create-project":{let i=ed(n.name);if(!i)return{state:o,changed:!1};let s=eS(o,n.projectKey,i);if(eu(o,n.projectKey)!==i)return{state:t,changed:!1};let l=e(o,{action:"pin-project",projectKey:n.projectKey,root:n.root,pinned:!0},r);return{state:l.state,changed:s||l.changed}}case"set":for(let e of n.ids){let t=ei(o.sessions,e)?o.sessions[e]:void 0;ej(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}(t,n,r))&&(c=!0)}break;case"restore":for(let e of n.entries){let t={};null!==e.pinnedAt&&(t.pinnedAt=e.pinnedAt),null!==e.archivedAt&&(t.archivedAt=e.archivedAt),ej(o.sessions,e.id,t)&&(c=!0)}break;case"remove-project":{let{projectKey:e}=n;ep(o,e)||(o.removedProjects={...o.removedProjects,[e]:r},c=!0),ei(o.projects,e)&&(delete o.projects[e],c=!0);break}case"pin-project":{let{projectKey:e,root:t}=n,a=ei(o.projects,e)?o.projects[e]:void 0;if(n.pinned?(ep(o,e)&&(delete o.removedProjects[e],0===Object.keys(o.removedProjects).length&&delete o.removedProjects,c=!0),a?.root!==t&&(o.projects[e]={pinnedAt:r,root:t},c=!0)):a&&(delete o.projects[e],c=!0),(n.pinned?void 0===a:void 0!==a)&&o.projectOrder){let t,r,a=(i=o.projectOrder,s=o.projects,l=n.pinned,r=i.filter(t=>t!==e),l?(t=0,r.forEach((e,n)=>{ei(s,e)&&(t=n+1)})):(t=r.findIndex(e=>!ei(s,e)))<0&&(t=r.length),r.splice(t,0,e),r);eg(a.length,ef(a))&&ek(o,a)&&(c=!0)}break}case"add-projects":ek(o,function(e,t){let n=eC(e,t),r=e.length,i=ef(e),s=n.length;for(;s>0;){let e=em(n[s-1]);if(!eg(r+1,i+e))break;r++,i+=e,s--}return[...n.slice(s),...e]}(o.projectOrder??[],n.keys))&&(c=!0);break;case"move-project":{let e,t,{projectKey:r,anchorKey:i,position:s,add:l}=n,d=o.projectOrder??[];ek(o,function(e,t){let n=e.length,r=ef(e);if(eg(n,r))return e;let i=new Set;for(let s=e.length-1;s>=0&&!eg(n,r);s--)t.has(e[s])||(i.add(s),n--,r-=em(e[s]));let s=e.filter((e,t)=>!i.has(t));return eg(n,r)?s:ex(s)}((a=[...eC(d,l),...d],(e=a.filter(e=>e!==r)).includes(i)||e.unshift(i),t=e.indexOf(i),e.splice("before"===s?t:t+1,0,r),e),new Set([r,i,...l])))&&(c=!0);break}case"rename-project":{let e=ed(n.name);void 0!==e&&eS(o,n.projectKey,e)&&(c=!0);break}case"read":{let e={...o.readAt};for(let t of n.ids){let n=ei(e,t)?e[t]:void 0;void 0!==n&&n>=r||(e[t]=r,c=!0)}c&&(o.readAt=ew(e))}}return{state:o,changed:c}}(e,t,n).state;c.current=e,t(e)},[]),g=(0,u.useCallback)(async e=>{let t=++h.current;m.current=t;try{let n=await fetch(nk,{cache:"no-store"}),i=await nN(n);if(t!==h.current)return;o.current=i,f(),e||a(null),r(!0),s(!0)}catch(e){if(t!==h.current)return;a(nC(e)),r(!0)}finally{m.current===t&&(m.current=null)}},[f]),x=(0,u.useCallback)(()=>g(!1),[g]),v=(0,u.useCallback)(e=>{"number"!=typeof e||!Number.isFinite(e)||d.current.length>0||e===o.current.revision||(null===m.current||m.current!==h.current)&&x()},[x]),b=(0,u.useCallback)(e=>{let t={request:e,now:Date.now()};d.current=[...d.current,t],f();let n=async()=>{let n=!1;try{let t=await fetch(nk,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),cache:"no-store"}),i=await nN(t);h.current++,o.current=i,a(null),r(!0),s(!0),n=!0}catch(e){a(nC(e))}return d.current=d.current.filter(e=>e!==t),f(),n||await g(!0),n},i=p.current.then(n,n);return p.current=i,i},[g,f]),y=(0,u.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=ei(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,u.useEffect)(()=>{x()},[x]),(0,u.useMemo)(()=>({state:e,loaded:n,synced:i,error:l,refresh:x,noteRevision:v,apply:b,snapshot:y}),[e,n,i,l,x,v,b,y])}(),ij=(0,u.useCallback)(async e=>{let t=await iv(e);return t||r9(e=>e+1),t},[iv]),ik=(0,u.useCallback)((e,t)=>{ij({action:"pin-project",projectKey:e,root:t,pinned:!0})},[ij]),iS=ih.readAt,iN=(0,u.useMemo)(()=>new Set(t3(nx,iS).keys()),[nx,iS]);(0,u.useEffect)(()=>{let e=t3(nx,iS);e!==nx&&nv(e)},[iS,nx]);let iM=(0,u.useRef)({allSessions:G,readAt:iS,unreadMarks:nx,runningSessionIds:nd,subagentsActiveSessionIds:nm});iM.current={allSessions:G,readAt:iS,unreadMarks:nx,runningSessionIds:nd,subagentsActiveSessionIds:nm};let iR=(0,u.useCallback)(e=>{let t=n$.current,n=[...new Set(e)].filter(e=>!t.has(e));if(0!==n.length){for(let e of n)t.add(e);iv({action:"read",ids:n}).then(e=>{for(let r of n)t.delete(r),e&&nM.current.delete(r)})}},[iv]),iD=(0,u.useCallback)((e,t)=>{var n;let r=iM.current;if(r.runningSessionIds.has(e)||r.subagentsActiveSessionIds.has(e))return;if(!nt()){t&&nM.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:nM.current.has(e)}).marked||n.pending||void 0===n.readAt||void 0!==n.modifiedMs&&n.modifiedMs>n.readAt)&&iR([e])},[iR]);(0,u.useEffect)(()=>{var e;let t,n;return e=()=>{let e=r0.current;e&&iD(e,!1)},t=ne().onAttended(e),0==t5++&&(t9=function(){let e=ne(),t=()=>e.noteInput(),n=()=>e.notePageChange(),r={capture:!0,passive:!0};for(let e of t8)window.addEventListener(e,t,r);return window.addEventListener("focus",n),window.addEventListener("blur",n),document.addEventListener("visibilitychange",n),()=>{for(let e of t8)window.removeEventListener(e,t,r);window.removeEventListener("focus",n),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",n)}}()),n=!1,()=>{n||(n=!0,t(),0==--t5&&(t9?.(),t9=null))}},[iD]);let iB=(0,u.useRef)(null),iH=(0,u.useRef)(null);nj(iH);let iU=(0,u.useRef)(null),iK=(0,u.useRef)(null),iq=(0,u.useRef)(320),iV=(0,u.useCallback)(()=>{let e=iK.current,t=iB.current;return e&&t&&0!==e.clientHeight?e.clientHeight-t.offsetHeight:window.innerHeight-36},[]),iZ=(0,u.useCallback)(()=>Math.round(.45*iV()),[iV]),iJ=(0,u.useCallback)(()=>iV()-120,[iV]),iY=nw({ariaLabel:Z("sidebar.resizeFiles"),axis:"vertical",cssVariable:"--sidebar-files-height",defaultWidth:320,getDefaultWidth:iZ,getMaxWidth:iJ,growthDirection:"up",maxWidth:2e3,minWidth:220,persistClamp:!1,storageKey:"pi-web:sidebar-files-height",widthRef:iq}),iG=iY.panelRef,iX=(0,u.useCallback)(e=>{iK.current=e,iG.current=e},[iG]),iQ=iY.reclampWidth;(0,u.useEffect)(()=>{let e=iK.current;if(!nF||!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>iQ());return t.observe(e),()=>t.disconnect()},[iQ,nF]),(0,u.useEffect)(()=>{let e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return"sessions";try{return"files"===e.getItem(ti)?"files":"sessions"}catch{return"sessions"}}();"sessions"!==e&&n_(e);let t=function(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!t)return{};try{let e=t.getItem(ts);if(null!==e)return tx(JSON.parse(e))}catch{return{}}try{let n=t.getItem(tl);if(null===n)return{};e=tx(JSON.parse(n))}catch{e={}}let n=Object.fromEntries(Object.entries(e).filter(e=>{let[,t]=e;return!t}));return tv(n,t),n}();Object.keys(t).length>0&&rd(t),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return!1;try{return"true"===e.getItem(to)}catch{return!1}}()&&rg(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return!1;try{return"true"===e.getItem(tc)}catch{return!1}}()&&rv(!0),tn(td)&&ry(!0);let n=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return[];try{let t=e.getItem(ta),n=null===t?[]:JSON.parse(t);if(!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e&&""!==e);return[...new Set(r)].slice(-300)}catch{return[]}}();n.length>0&&rS(n),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return!1;try{return"true"===e.getItem(tp)}catch{return!1}}()&&n2(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(!e)return!1;try{return"true"===e.getItem(tu)}catch{return!1}}()&&t7(!0),rj(!0),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:tg();if(e)for(let t of tf)try{e.removeItem?.(t)}catch{}}()},[]);let i0=(0,u.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=++ee.current;try{e&&el(!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!==ee.current)return!1;Q.current=s.sessionListVersion,X(s.sessions);let l=s.sessions.some(e=>!0===e.detailsPending);n&&l||eo(!0),nR.current||(nI.current=new Set(s.completionNotificationSuppressedSessionIds??[]),nS.current={latest:Date.now(),before:nS.current.latest},nu(e=>iz(e,s.runningSessionIds??[])),nh(e=>iz(e,s.awaitingInputSessionIds??[])));let a=new Set(s.sessions.filter(e=>!v(e.relation)).map(e=>e.id));return nv(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}),eh(null),l}catch(e){return r===ee.current&&eh(String(e)),!1}finally{r===ee.current&&el(!1)}},[]),i1=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let e=!i1.current;i1.current=!0;let t=!0;return e?(er.current=Date.now(),i0(!0,!1,!0).then(e=>{er.current=null,t&&e&&(nA.current=setTimeout(()=>{nA.current=null,t&&i0(!1,!0)},750))})):i0(),()=>{t=!1,nA.current&&(clearTimeout(nA.current),nA.current=null)}},[i0,A]),(0,u.useEffect)(()=>{let e=!1;return fetch("/api/open-in-explorer").then(e=>e.ok?e.json():null).then(t=>{!e&&t&&na(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,u.useEffect)(()=>{nc(null)},[ev,P]);let i2=(0,u.useCallback)(async()=>{let e=ev??P;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 nc(null),!1;let n=await t.json().catch(()=>({}));nc(n.error??`HTTP ${t.status}`)}catch(e){nc(e instanceof Error?e.message:String(e))}return!0},[ev,P]),i4=Z(nl?.platform==="darwin"?"sidebar.openInFinder":nl?.platform==="win32"?"sidebar.openInExplorer":"sidebar.openInFileManager"),i3=nl?.supported===!1,i8=no?Z(iI[no]??no):null;(0,u.useEffect)(()=>{try{let e=0===nx.size?null:JSON.stringify(Object.fromEntries(nx));null===e?window.localStorage.removeItem(t1):window.localStorage.setItem(t1,e)}catch{}},[nx]),(0,u.useEffect)(()=>{let e=e=>{(null===e.key||e.key===t1)&&nv(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,t4(e.newValue)))};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),(0,u.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;let l=Date.now(),a=null,o="error",c=null;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(c=t.status,!t.ok)return;o="ok";let r=await t.json();if(a=Date.now(),e||n!==s)return;nR.current=!0,"number"==typeof r.serverNow&&nE.current?.note(r.serverNow,l,a),nS.current={latest:l,before:nS.current.latest},nI.current=new Set(r.completionNotificationSuppressedSessionIds??[]),nu(e=>iz(e,r.runningSessionIds??[])),nh(e=>iz(e,r.awaitingInputSessionIds??[])),ng(e=>iz(e,r.subagentsActiveSessionIds??[])),iy(r.sessionUiStateRevision);let i=er.current;null!==i&&Date.now()-i<15e3||r.sessionListVersion===Q.current||await i0()}catch{o=s.signal.aborted?"aborted":"error"}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500)),function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=Date.now();tX.count+=1,"error"===t&&(tX.failures+=1),tX.last={at:i,durationMs:Math.max(0,(r??i)-e),outcome:t,httpStatus:n}}(l,o,c,a)}},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)}},[i0,iy]),(0,u.useEffect)(()=>{q?.(nd)},[q,nd]),(0,u.useEffect)(()=>{V?.(G)},[G,V]),(0,u.useEffect)(()=>{!function(e){let t,n;if("u"<typeof document)return;let r=(n=(t=tT(e.awaiting))+tT(e.unread))<=0?null:{kind:t>0?"awaiting":"unread",count:Math.min(n,99)},i=r?`${r.kind}:${r.count}`:"none";if(i!==tR){if(tR=i,!r){for(let[e,t]of tL)e.href=t;return}for(let e of tP())tL.has(e)||tL.set(e,e.href);tz(r,i)}}({awaiting:np.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}(iN,K)})},[np,iN,K]),(0,u.useEffect)(()=>{let e=nb.current,t=[...e].filter(e=>!nd.has(e)&&e!==j),n=new Set([...nd,...nm]),r=[...ny.current].filter(e=>!n.has(e)&&e!==j),i=new Set(G.filter(e=>v(e.relation)).map(e=>e.id)),s=r.filter(e=>!nT.current.has(e)&&!i.has(e)),l=[...nd].filter(t=>!e.has(t));if(s.length>0||l.length>0){let e=nS.current.before,t=nE.current.toServer(e??void 0);nv(e=>{let n=new Map(e);return nd.forEach(e=>n.delete(e)),s.forEach(e=>n.set(e,t)),n})}j&&ny.current.has(j)&&!n.has(j)&&(nt()?iR([j]):nM.current.add(j));let a=l.some(e=>!G.some(t=>t.id===e));if((t.length>0||a)&&i0(),s.length>0){let e=nS.current.before??Date.now()-5e3;H?.(s,e)}nb.current=nd,ny.current=n;let o=nT.current;nT.current=new Set([...n].filter(e=>nI.current.has(e)||i.has(e)||o.has(e)&&!nd.has(e)))},[nd,nm,j,G,i0,H,iR]),(0,u.useEffect)(()=>{if(!j)return;let e=iM.current.unreadMarks.has(j);iD(j,e),e&&nv(e=>{if(!e.has(j))return e;let t=new Map(e);return t.delete(j),t})},[j,iD]),(0,u.useEffect)(()=>{void 0!==F&&tD(e=>e+1)},[F]),(0,u.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&eL(e.home)}).catch(()=>{})},[]);let i6=(0,u.useRef)(!1),i5=(0,u.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:et(s)}:{root:e,key:e}}(e,{validated:tt,listing:t$,sessions:G}):null,[tt,t$,G]),i9=(0,u.useMemo)(()=>i5(ev),[i5,ev]),i7=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=i5(ev),t=i7.current;(t?.cwd!==ev||t.key!==(e?.key??null))&&(i7.current={cwd:ev,key:e?.key??null},z?.(ev,e?.root??null,e?.key??null))},[ev,z,i5]);let se=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(!P){se.current=null;return}P!==se.current&&(se.current=P,eb(P))},[P]);let[st,sn]=(0,u.useState)(0);(0,u.useLayoutEffect)(()=>{if(!ev){tI(null),tO(null);return}let e=!1;return tO(ev),fetch(`/api/worktrees?cwd=${encodeURIComponent(ev)}`).then(e=>e.json()).then(t=>{if(!e){if(tO(null),t.error||!t.projectRoot)return void tI(null);t.isGit?tW.current?.delete(ev):tW.current?.add(ev),function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:tg();if(!n||!e)return;let r=tw(n),i=r.indexOf(e);if(t?-1===i:-1!==i&&i===r.length-1)return;let s=r.filter(t=>t!==e);t||s.push(e);try{n.setItem(tm,JSON.stringify(s.slice(-50)))}catch{}}(ev,!!t.isGit),tI({forCwd:ev,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||(tO(null),tI(null))}),()=>{e=!0}},[ev,st,A]),(0,u.useEffect)(()=>{if(0!==G.length&&!T&&null===ev){if($&&!i6.current){i6.current=!0;let e=G.find(e=>e.id===$);if(e){eb(e.cwd),k(e,!0);return}R?.(),I&&r6(Z("sidebar.sessionNotFound"))}let e=en(G);e.length>0&&eb(e[0].root)}},[G,ev,$,I,T,k,R,r6,Z]);let sr=t$?t$.worktrees.find(e=>e.path===ev)??(t$.forCwd===ev&&t$.currentWorktreePath?t$.worktrees.find(e=>e.path===t$.currentWorktreePath):void 0)??t$.worktrees.find(e=>e.isMain):void 0,si=sr?.path??null,ss=(0,u.useCallback)(async function(e){let{remember:t=!0,purpose:n=eQ}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e??e1).trim();if(r&&!e6){e5(!0),e8(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r})}),i=await e.json().catch(()=>({}));if(!e.ok||i.error||!i.cwd||!i.projectRoot||!i.projectKey)return void e8(i.error??`HTTP ${e.status}`);if(t&&(iP(i.cwd),e4(i.cwd)),e0(!1),"new-session"===n){let e=is.current,t=il.current;is.current=null,il.current=null,e?.({cwd:i.cwd,projectKey:i.projectKey,projectRoot:i.projectRoot}),ip(()=>t?.isConnected?t:null);return}il.current=null,ik(i.projectKey,i.projectRoot),th({cwd:i.cwd,root:i.projectRoot,key:i.projectKey}),eb(i.cwd)}catch(e){e8(e instanceof Error?e.message:String(e))}finally{e5(!1)}}},[eQ,e1,e6,ip,ik]),sl=(0,u.useCallback)(e=>{il.current=e,e0("files"),e8(null)},[]),sa=(0,u.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 ss(n.cwd,{remember:!1,purpose:e})}catch{}},[ss]),so=(0,u.useRef)(sa);so.current=sa;let sc=(0,u.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:Z(t.key,{...t.params,path:tS(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),sn(e=>e+1),{path:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[Z]),sd=(0,u.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 si===t&&eb(e.root),sn(e=>e+1),"removed"}catch(e){return{error:e instanceof Error?e.message:String(e)}}},[si]),su=(0,u.useCallback)(()=>sn(e=>e+1),[]),sp=(0,u.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r}=e;n&&r&&ik(n,r),n&&r&&th({cwd:t,root:r,key:n}),eb(t)},[ik]),sh=(0,u.useCallback)((e,t,n,r)=>{X(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&eb(e.cwd),k(e,!1,t,n,r)},[k]),sm=(0,u.useCallback)(e=>{let{cwd:t,projectKey:n,projectRoot:r,carryComposer:i}=e;n&&r&&ik(n,r),n&&r&&th({cwd:t,root:r,key:n}),eb(t),C?.("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)},[C,ik]),sf=(0,u.useRef)(sm);sf.current=sm;let sg=(0,u.useRef)(async()=>!1),sx=(0,u.useRef)(async()=>!1),sv=(0,u.useRef)(async()=>!1);(0,u.useImperativeHandle)(E,()=>({restoreArchivedSession:e=>sg.current(e),deleteArchivedSession:e=>sx.current(e),deleteArchivedSessions:e=>sv.current(e),refreshArchive:iw,startNewSessionIn:e=>sf.current(e),openFolderForNewSession:(e,t)=>{is.current=e,il.current=t,e8(null),e0("new-session")},openDefaultDirectoryForNewSession:e=>{is.current=e,il.current=null,so.current("new-session")},refreshWorktrees:su,createWorktree:sc}),[sc,su,iw]);let sb=(0,u.useCallback)(()=>{ev&&sm({cwd:ev})},[ev,sm]),sy=(0,u.useMemo)(()=>en(G),[G]),sw=(0,u.useMemo)(()=>y(G),[G]),sj=(0,u.useMemo)(()=>new Map(sw.map(e=>[e.root.id,e])),[sw]),sk=(0,u.useMemo)(()=>y(G).filter(e=>ez(e,ih,nd)).map(e=>{let{root:t}=e,n=et(t),r=t.projectRoot||t.cwd;return{session:t,archivedAt:ih.sessions[t.id].archivedAt,project:{key:n,root:r,name:eu(ih,n)??(e2(r)||r)}}}).sort((e,t)=>t.archivedAt-e.archivedAt||e.session.id.localeCompare(t.session.id)),[G,ih,nd]);(0,u.useEffect)(()=>{x?.({entries:sk,loaded:im&&!es,error:ix})},[sk,im,es,ix,x]);let sS=(0,u.useMemo)(()=>{let e=new Set,t=new Map;for(let n of sw){if(!ez(n,ih,nd))continue;for(let t of eA(n))e.add(t);let r=et(n.root);t.set(r,(t.get(r)??0)+1)}return{ids:e,countByProject:t}},[sw,ih,nd]),sC=(0,u.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=et(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===sS.ids.size?G:G.filter(e=>!sS.ids.has(e.id)),nd,iN),[G,sS,nd,iN]),sN=!!(t$?.isGit&&t$.isTopLevel&&ev&&i9?.key===t$.projectKey),sE=ev&&t$?.isGit&&i9?.key===t$.projectKey&&!sN?{label:Z("sidebar.openRepoRoot"),title:Z("sidebar.openRepoRootTitle")}:null,sM=!!(ev&&tA===ev),s$=sE??(!sM||sN||ev&&tW.current?.has(ev)?null:{label:Z("sidebar.worktrees"),title:Z("sidebar.checkingWorktrees")}),sI=i9?.key??null,sT=i9?.root??null,sR=(0,u.useMemo)(()=>sI&&sT?{key:sI,root:sT}:null,[sI,sT]),sA=(0,u.useRef)(new Set);(0,u.useEffect)(()=>{if(es||!ig||!ea||!sR)return;let{key:e,root:t}=sR;ep(ih,e)||Object.hasOwn(ih.projects,e)||!(tt?.cwd===ev||t$?.forCwd===ev||G.some(e=>e.cwd===ev))||sA.current.has(e)||(sA.current.add(e),ik(e,t))},[es,ig,ea,sR,ih,tt,ev,t$,G,ik]);let sL=(0,u.useMemo)(()=>0===ru.size?rc:Object.fromEntries([...[...ru].filter(e=>!Object.hasOwn(rc,e)).map(e=>[e,!0]),...Object.entries(rc)]),[rc,ru]),sP=(0,u.useMemo)(()=>(function(e){let{uiState:t,runningIds:n,currentProject:r}=e,i=y(e.sessions),s=eU(t,r),l=0,a=[],o=new Map,c=new Map,d=new Set;for(let e of i){if(ez(e,t,n)){l++;continue}s.noteFamily(e);let r=eB(e),i=eT(e.latestModified);if(c.set(r,Math.max(c.get(r)??-1/0,i)),e.root.transient||d.add(r),eO(e,t,n)){a.push(e);continue}let u=o.get(r);u?u.push(e):o.set(r,[e])}let u=[{kind:"spacer",key:"top-spacer"}];if(a.length>0){let n=e=>eI(e$(t,e.root.id)?.pinnedAt)??0,r=a.map((e,t)=>({family:e,index:t})).sort((e,t)=>eR(n(e.family),n(t.family))||e.index-t.index).map(e=>{let{family:t}=e;return t}),{running:i,awaiting:l,unread:o}=e_(r,e);if(u.push({kind:"pinned-header",key:"pinned-header",count:r.length,collapsed:e.pinnedCollapsed,running:i,awaiting:l,unread:o}),!e.pinnedCollapsed){let{visible:t,revealed:n,nextShown:i}=eq(r,8,eV(e.moreShown,eM),e);for(let n of t)u.push(eK(n,"pinned",s.get(eB(n)),e));let l=eJ(r.length,t.length,n);l&&u.push({kind:"pinned-more",key:"pinned-more",...l,nextShown:i})}u.push({kind:"spacer",key:"pinned-spacer"})}let p=[...o.keys()],h=new Set(p),m=e=>{h.has(e)||(h.add(e),p.push(e))};for(let e of(r&&m(r.key),Object.keys(t.projects)))m(e);let f=p.filter(e=>!ep(t,e)).map(e=>s.get(e)),g=new Map;(t.projectOrder??[]).forEach((e,t)=>{g.has(e)||g.set(e,t)});let x=e=>e.pinned||d.has(e.key),v=(e,t)=>[...e.filter(e=>{let{project:t}=e;return!g.has(t.key)}).sort((e,n)=>Number(x(e.project))-Number(x(n.project))||t(e,n)),...e.filter(e=>{let{project:t}=e;return g.has(t.key)}).sort((e,t)=>(g.get(e.project.key)??0)-(g.get(t.project.key)??0))].map(e=>{let{project:t}=e;return t}),b=e=>c.get(e.key)??(e.current?1/0:-1/0),w=e=>eI(t.projects[e.key]?.pinnedAt)??0,j=f.map((e,t)=>({project:e,index:t})),k=v(j.filter(e=>{let{project:t}=e;return t.pinned}),(e,t)=>eR(w(t.project),w(e.project))||e.index-t.index),S=v(j.filter(e=>{let{project:t}=e;return!t.pinned}),(e,t)=>eR(b(e.project),b(t.project))||e.index-t.index),C=[...k,...S],N=e=>e.filter(e=>!g.has(e.key)).map(e=>e.key),E={pinned:N(k),other:N(S)},M=C.filter(e=>!g.has(e.key)&&x(e)).map(e=>e.key);for(let[t,n]of(e.sections&&u.push({kind:"section",key:"section-projects",label:"projects"}),C.entries())){t>0&&u.push({kind:"spacer",key:`group-spacer:${n.key}`});let r=o.get(n.key)??[],i=eF(n,e.groupExpansion),{running:s,awaiting:l,unread:a}=e_(r,e);if(u.push({kind:"group",key:`group:${n.key}`,project:n,expanded:i,running:s,awaiting:l,unread:a}),i)if(0===r.length)u.push({kind:"group-empty",key:`empty:${n.key}`,project:n});else{let{visible:t,revealed:i,nextShown:s}=eq(r,6,eV(e.moreShown,n.key),e);for(let r of t)u.push(eK(r,"group",n,e));let l=eJ(r.length,t.length,i);l&&u.push({kind:"group-more",key:`more:${n.key}`,projectKey:n.key,...l,nextShown:s})}}if(C.length>0&&u.push({kind:"spacer",key:"footer-spacer"}),e.sections||u.push({kind:"footer-open",key:"footer-open"}),e.sections){let r=e.selectedSessionId?i.find(t=>eP(t,e.selectedSessionId)):void 0,l=r?.subagents.filter(eH)??[];if(u.push({kind:"section",key:"section-subagents",label:"subagents",collapsed:!!e.subagentsCollapsed,count:l.length}),r&&l.length>0&&!e.subagentsCollapsed){s.noteFamily(r);let t=s.get(eB(r));for(let r of(l.sort((e,t)=>eR(eT(e.modified),eT(t.modified))||e.id.localeCompare(t.id)),l)){let i=e.awaitingIds?.has(r.id)??!1;u.push({kind:"subagent",key:`subagent:${r.id}`,session:r,project:t,status:{running:n.has(r.id)&&!i,awaiting:i,unread:e.unreadIds.has(r.id),selected:r.id===e.selectedSessionId}})}}let a=i.filter(e=>!e.root.transient&&!ez(e,t,n)).slice(0,10);if(u.push({kind:"section",key:"section-recents",label:"recents",collapsed:!!e.recentsCollapsed,count:a.length}),!e.recentsCollapsed)for(let t of a)u.push({kind:"recent",key:`recent:${t.root.id}`,family:t,project:s.get(eB(t)),status:eD(t,e)})}if(u.some(e=>"subagent"===e.kind&&e.status.selected))for(let e of u)("session"===e.kind||"recent"===e.kind)&&e.status.selected&&(e.status.selected=!1);return l>0&&u.push({kind:"footer-archived",key:"footer-archived",count:l}),{rows:u,projects:C,archivedCount:l,unorderedKeysByBand:E,projectKeysToRecord:M}})({sections:!0,recentsCollapsed:rx,subagentsCollapsed:rb,sessions:G,uiState:ih,runningIds:nd,awaitingIds:np,unreadIds:iN,selectedSessionId:j,currentProject:sR,groupExpansion:sL,moreShown:rh,pinnedCollapsed:rf}),[G,ih,nd,np,iN,j,sR,sL,rh,rf,rx,rb]),sz=(0,u.useMemo)(()=>m?sP.rows.filter(e=>"footer-archived"!==e.kind):sP.rows,[sP.rows,m]),sO=rO.archiveMounted,sW=(0,u.useMemo)(()=>new Set(rk),[rk]),sF=(0,u.useMemo)(()=>sO?function(e){let{uiState:t,runningIds:n}=e,r=eU(t,e.currentProject),i=new Map;for(let s of y(e.sessions)){if(!ez(s,t,n))continue;r.noteFamily(s);let e=eI(e$(t,s.root.id)?.archivedAt)??0,l=eB(s),a=i.get(l);a?(a.families.push({family:s,archivedAt:e}),a.newest=Math.max(a.newest,e)):i.set(l,{newest:e,families:[{family:s,archivedAt:e}]})}let s=[];for(let{key:t,group:n}of[...i.entries()].map((e,t)=>{let[n,r]=e;return{key:n,group:r,index:t}}).sort((e,t)=>eR(e.group.newest,t.group.newest)||e.index-t.index)){let i=r.get(t),l=!e.collapsed?.has(t);if(s.push({kind:"archive-group",key:`archive:${t}`,project:i,count:n.families.length,expanded:l}),l)for(let{family:t}of n.families.map((e,t)=>({...e,index:t})).sort((e,t)=>eR(e.archivedAt,t.archivedAt)||e.index-t.index))s.push(eK(t,"archive",i,e))}return s}({sessions:G,uiState:ih,runningIds:nd,awaitingIds:np,unreadIds:iN,selectedSessionId:j,currentProject:sR,collapsed:sW}):[],[sO,G,ih,nd,np,iN,j,sR,sW]),sD=(0,u.useMemo)(()=>sF.flatMap(e=>"archive-group"===e.kind?[e]:[]),[sF]),s_=(0,u.useMemo)(()=>new Map(sP.projects.map(e=>[e.key,e])),[sP.projects]),sB=(0,u.useRef)(new Set),sH=sP.projectKeysToRecord,sU=ih.projectOrder?.length??0;(0,u.useEffect)(()=>{if(es||!ig||!ea||sU>=1e3)return;let e=sB.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)}(sH,e);if(0!==t.length){for(let n of t)e.add(n);iv({action:"add-projects",keys:t})}},[iv,es,sH,ea,sU,ig]);let sK=ih.projectNames,sq=(0,u.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(tM(s,n)));return i})(sP.projects,sy,sK),[sP.projects,sy,sK]),sV=(0,u.useMemo)(()=>{if(!ev||!i9)return null;let e=sN&&null!==t$;return{cwd:ev,project:tM(i9,sK),worktrees:e?t$.worktrees.map(e=>{let{path:t,branch:n,isMain:r}=e;return{path:t,branch:n,isMain:r}}):null,currentWorktreePath:e?si:null,projects:sq}},[ev,i9,sN,t$,si,sq,sK]),sZ=(0,u.useRef)(sV);sZ.current=sV;let sJ=sV?JSON.stringify([sV.cwd,sV.project.key,sV.project.root,sV.project.alias??null,sV.currentWorktreePath,sV.worktrees?.map(e=>[e.path,e.branch,e.isMain])??null,sV.projects.map(e=>[e.key,e.root,e.alias??null])]):"";(0,u.useEffect)(()=>{M?.(sZ.current)},[sJ,M]);let sY=(0,u.useRef)(sI);(0,u.useLayoutEffect)(()=>{let e=sY.current;if(sY.current=sI,null===e||e===sI)return;let t=s_.get(e);rp(e=>!t||t.current||t.pinned||e.has(t.key)||Object.hasOwn(rc,t.key)?e:new Set(e).add(t.key))},[sI,rc,s_]);let sG=(0,u.useCallback)((e,t)=>{rd(e),tv(e),rp(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)),rm(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))},[]),sX=(0,u.useCallback)(()=>(ri.current?.hidden?n6:n4).current??iU.current,[]),sQ=(0,u.useCallback)(e=>{let t=ri.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 sX()},[sX]),s0=(0,u.useCallback)(e=>{let t=CSS.escape(`group:${e}`),n=ri.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);return n&&n.getClientRects().length>0?n:sX()},[sX]);(0,u.useEffect)(()=>{r5!==r7.current&&(r7.current=r5,r6(Z("sidebar.uiStateFailed",{error:ix??""})))},[r5,ix,r6,Z]);let s1=(0,u.useCallback)((e,t,n)=>{let r=s_.get(e),i=s_.get(t);r&&i&&r!==i&&r.pinned===i.pinned&&(ij({action:"move-project",projectKey:e,anchorKey:t,position:n,add:sP.unorderedKeysByBand[r.pinned?"pinned":"other"].slice(-500)}),rJ.current+=1,rZ({id:rJ.current,at:Date.now(),rowKey:`group:${e}`}))},[ij,sP.unorderedKeysByBand,s_]),s2=(0,u.useCallback)(e=>{nF||(n_(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(ti,e)}catch{}}(e))},[nF]),s4=(0,u.useCallback)(e=>{e!==rA.current&&rM(e?"out":"in"),n2(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(tp,String(e))}catch{}}(e)},[rM]),s3=(0,u.useCallback)(e=>{let t=e.target;t instanceof Element&&rl.current.set(t,t.scrollTop)},[]);(0,u.useLayoutEffect)(()=>{for(let e of[ri.current,rs.current])if(e&&!e.hidden)for(let t of e.querySelectorAll(".session-tree-scroll, .sidebar-files-scroll")){let e=rl.current.get(t);void 0!==e&&t.scrollTop!==e&&(t.scrollTop=e)}},[nD,rC,nF,nZ]);let s8=(0,u.useCallback)(e=>{if(rq(null),m)return void m(e);if(rP(!0),tV(!1),s2("sessions"),void 0!==e){if(rk.includes(e)){let t=rk.filter(t=>t!==e);rS(t),tb(t)}rJ.current+=1,rX({id:rJ.current,at:Date.now(),rowKey:`archive:${e}`,block:"start"})}},[rk,m,rP,s2]),s6=(0,u.useRef)(null),s5=(0,u.useRef)(rC),s9=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(s5.current===rC)return;if(s5.current=rC,rC)return void iW(s6.current);let e=ri.current?.querySelector('[data-row-key="footer-archived"] button'),t=e&&e.getClientRects().length>0?e:sX();iW(t),t&&document.activeElement===t&&(s9.current=t)},[rC,sX]);let s7=(0,u.useRef)(null),le=(0,u.useRef)(nF);(0,u.useLayoutEffect)(()=>{if(le.current===nF)return;le.current=nF;let e=s7.current;e&&(!e.isConnected||0===e.getClientRects().length)&&iW(sX())},[nF,sX]);let lt=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"===nD?"files":"sessions";s2(t),("sessions"===t?n4:n6).current?.focus()},ln=(0,u.useCallback)((e,t)=>{ij({action:"set",ids:[e.root.id],pinned:t})},[ij]),lr=(0,u.useCallback)((e,t)=>{var n;if(t){let t=iM.current.unreadMarks;iR([e.root.id,...eA(e).filter(e=>t.has(e))])}let r=iM.current.readAt,i=r&&Object.prototype.hasOwnProperty.call(r,e.root.id)?r[e.root.id]:void 0,s=(n=nE.current.toServer(),void 0===i?n:Math.max(n,i+1));nv(n=>{let r=new Map(n);if(t)for(let t of eA(e))r.delete(t);else r.set(e.root.id,s);return r})},[iR]),li=(0,u.useCallback)(e=>{0!==e.length&&nv(t=>{let n=new Map(t);for(let[t,r]of e)t===r0.current||n.has(t)||n.set(t,r);return n.size===t.size?t:n})},[]),ls=(0,u.useCallback)(e=>{let t=e.filter(e=>!e.root.transient);if(0===t.length)return;let n=ib(t.map(e=>e.root.id)),r=t.flatMap(e=>eA(e)),i=r.flatMap(e=>{let t=nx.get(e);return void 0!==t&&iN.has(e)?[[e,t]]:[]});for(let e of eN(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=>eA(e)));li(i.filter(e=>{let[t]=e;return n.has(t)}))});i.length>0&&nv(e=>{let t=new Map(e);for(let e of r)t.delete(e);return t}),r6(1===t.length?Z("sidebar.archivedToast",{title:iO(io(t[0].root),28)}):Z("sidebar.archivedManyToast",{count:t.length}),[{id:"undo",label:Z("sidebar.undo"),onClick:()=>{for(let e of eN(n))ij({action:"restore",entries:e});li(i),ip(()=>sQ(t[0].root.id))}},{id:"view",label:Z("sidebar.viewArchive"),onClick:()=>s8()}])},[ij,ip,sQ,s8,li,r6,ib,Z,nx,iN]),ll=(0,u.useCallback)(e=>{eA(e).some(e=>nd.has(e))||ls([e])},[ls,nd]),la=(0,u.useCallback)(e=>{if(0===e.length)return;let t=e.map(e=>e.root.id),n=ib(t);for(let e of eN(t))ij({action:"set",ids:e,archived:!1});r6(1===e.length?Z("sidebar.restoredToast",{title:iO(io(e[0].root),28)}):Z("sidebar.restoredManyToast",{count:e.length}),[{id:"undo",label:Z("sidebar.undo"),onClick:()=>{for(let e of eN(n))ij({action:"restore",entries:e});ip(()=>sQ(e[0].root.id))}}])},[ij,sQ,ip,r6,ib,Z]),lo=(0,u.useCallback)(e=>la([e]),[la]);sg.current=async e=>{let t=sj.get(e);if(!t||!ez(t,ih,nd))return!0;let n=await ij({action:"set",ids:[t.root.id],archived:!1});return n&&r6(Z("sidebar.restoredToast",{title:iO(io(t.root),28)})),n};let lc=(0,u.useCallback)(e=>{e.root.transient||(rU(null),rF(e.root.id))},[]),ld=(0,u.useCallback)(async(e,t)=>{let n=e.root,r=io(n),i=t.trim();if(rF(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})}),i0()}catch{}},[i0]),lu=(0,u.useCallback)(e=>{rB(e.key)},[]),lp=(0,u.useCallback)(e=>{rB(t=>t===e?null:t),ip(()=>s0(e))},[ip,s0]),lh=(0,u.useCallback)((e,t)=>{lp(e.key);let n=function(e,t){let n=t.trim();if(n===e.name)return null;let r=""===n||n===eW(e.root);return r&&null===e.customName?null:{action:"rename-project",projectKey:e.key,name:r?null:n}}(e,t);n&&ij(n)},[ij,lp]),lm=(0,u.useCallback)(async e=>{let t=e.root;if(!t.transient){rU(e=>e===t.id?null:e);try{(await fetch(`/api/sessions/${encodeURIComponent(t.id)}`,{method:"DELETE"})).ok&&[t,...e.subagents].forEach(e=>U(e.id)),L?.(t.id),i0()}catch{}}},[i0,L]),lf=(0,u.useCallback)((e,t)=>{t?lm(e):(rF(null),rU(e.root.id))},[lm]),lg=(nF||"sessions"===nD)&&!rC&&!(tq&&""!==tZ.trim()),lx=(0,u.useRef)(null),lv=(0,u.useRef)(null),lb=(0,u.useRef)(null);(0,u.useEffect)(()=>{j!==lv.current&&(lv.current=j,lx.current=j);let e=lx.current;if(!e||es||!im||!rw||!lg)return;lx.current=null;let t=lb.current;lb.current=null;let n=function(e,t){let n=w(e.sessions,t);if(!n)return null;let r=eB(n);if(e.sections&&!e.subagentsCollapsed&&n.subagents.some(e=>e.id===t&&eH(e)))return{rowKey:`subagent:${t}`,projectKey:r,unfoldPinned:!1,unfoldGroup:!1};if(ez(n,e.uiState,e.runningIds))return null;if(eO(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}}({sections:!0,subagentsCollapsed:rb,sessions:G,uiState:ih,runningIds:nd,groupExpansion:sL,pinnedCollapsed:rf},e);if(n){if(n.unfoldPinned&&(rg(!1),ty(!1)),n.unfoldGroup){let e={...rc};delete e[n.projectKey],e[n.projectKey]=!0,sG(e,[n.projectKey])}rJ.current+=1,rZ({id:rJ.current,at:Date.now(),rowKey:n.rowKey,block:"nearest",...t?.sessionId===e?{takeFocusFrom:t.takeFocusFrom}:{}})}},[j,G,ih,nd,sL,rc,rf,rb,es,im,rw,lg,sG]);let ly=(e,t)=>{if(s9.current=null,rC){let e=ri.current?.querySelector(".sidebar-sessions-view .session-tree-scroll");e&&rl.current.delete(e),rP(!1)}let n=t?`[data-row-key="${CSS.escape(t)}"]`:null;lb.current={sessionId:e.id,takeFocusFrom:e=>null!==n&&null!==e.closest(n)||e===s9.current},sh(e,void 0,void 0,{keepSidebarOpen:null!==t}),i0()},lw=(0,u.useRef)(ly);lw.current=ly;let lj=(0,u.useRef)(new Set),lk=(0,u.useCallback)(async e=>{let t=e.family.root;if(t.transient||lj.current.has(t.id))return;lj.current.add(t.id);let n=r0.current;try{var r;let i,s,l=await fetch(`/api/sessions/${encodeURIComponent(t.id)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),a=await l.json().catch(()=>({}));if(!l.ok||!a.session){let{key:e,params:t}=tj(a.code,a.error??`HTTP ${l.status}`);r6(Z(e,t)),"not_found"===a.code&&i0();return}let o=a.session,c=io(o),{head:d,tail:u}=(r=Z("sidebar.forkedToast",{title:c}),((s=(i=te(c)?.suffix)?r.lastIndexOf(i):-1)>0?{head:r.slice(0,s),tail:r.slice(s)}:null)??{head:Z("sidebar.forkedToast",{title:iO(c,28)}),tail:void 0});if(r0.current!==n){X(e=>e.some(e=>e.id===o.id)?e:[o,...e]);let e=nE.current.toServer();nv(t=>new Map(t).set(o.id,e)),i0(),r6(d,[{id:"open",label:Z("sidebar.open"),onClick:()=>lw.current(o,null)}],u);return}lw.current(o,e.key),r6(d,[],u)}catch(e){r6(Z("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)}))}finally{lj.current.delete(t.id)}},[i0,r6,Z]),lS=(0,u.useCallback)(e=>{e.root.transient||window.open(J(e.root.id),"_blank","noopener,noreferrer")},[]),lC=(0,u.useCallback)((e,t,n)=>{e.status.transient||rq({kind:"row",row:e,anchor:t,opener:n})},[]),lN=(0,u.useCallback)((e,t)=>{let n=e.family.root;if(n.id===rW||n.id===rH)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:()=>{i0()}})){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?iF(r,"start"):{kind:"point",x:t.clientX,y:t.clientY},s=document.activeElement,l=s instanceof HTMLElement&&null!==r&&r.contains(s);ii.current=!l&&s instanceof HTMLElement&&s!==document.body?s:null,lC(e,i,l?s:null)},[rH,i0,lC,rW]),lE=(0,u.useMemo)(()=>({sessions:G,uiState:ih,runningIds:nd,awaitingIds:np,unreadIds:iN,selectedSessionId:j}),[G,ih,nd,np,iN,j]),lM=(0,u.useCallback)((e,t)=>{let n=eY(lE,e.key,6048e5,Date.now()).length;rq({kind:"group",project:e,olderCount:n,anchor:iF(t,"end"),opener:t})},[lE]),l$=(0,u.useCallback)(e=>{ls(eY(lE,e.key,6048e5,Date.now()).flatMap(e=>{let t=sj.get(e);return t?[t]:[]}))},[ls,sj,lE]),lI=(0,u.useCallback)((e,t)=>{rq(n=>n?.kind==="group"&&n.project.key===e?{...n,askDelete:t}:n)},[]),lT=(0,u.useRef)(new Set),lR=(0,u.useCallback)(async(e,t,n)=>{if(rq(null),0===t.length)return!0;if(lT.current.has(e))return!1;lT.current.add(e),r6(Z("sidebar.deletingSessions"));try{let e=await tk(t,fetch);for(let t of e.deleted)U(t),L?.(t);if(await i0(),ip(n),null!==e.error)return r6(Z("sidebar.deleteFailed",{error:e.error})),!1;let r=e.deletedRoots.length,i=[1===r?Z("sidebar.deletedOneToast"):Z("sidebar.deletedManyToast",{count:r})];return e.running.length>0&&i.push(Z("sidebar.keptRunningToast",{count:e.running.length})),r6(i.join(" \xb7 ")),t.every(t=>e.deletedRoots.includes(t))}finally{lT.current.delete(e)}},[ip,i0,L,r6,Z]);sv.current=async e=>{let t=[...new Set(e)],n=t.flatMap(e=>{let t=sj.get(e);return t?[t]:[]}),r=n.filter(e=>ez(e,ih,nd)),i=r.map(e=>e.root.id),s=await lR(1===t.length?`archive-session:${t[0]}`:"archive-clear",i,()=>null);return await iw(),s&&r.length===n.length},sx.current=e=>sv.current([e]);let lA=(0,u.useCallback)(e=>{let{ids:t}=eG(lE,e.key);lR(`project:${e.key}`,t,()=>s0(e.key))},[lR,s0,lE]),lL=(0,u.useCallback)(e=>{let t=null===e?null:CSS.escape(`archive:${e}`),n=null===t?null:ri.current?.querySelector(`[data-row-key="${t}"] .session-tree-group-toggle`);if(n&&n.getClientRects().length>0)return n;let r=s6.current;return r&&r.getClientRects().length>0?r:sX()},[sX]),lP=(0,u.useCallback)(e=>e.flatMap(e=>{let t=sj.get(e);return t?[t]:[]}),[sj]),lz=(0,u.useCallback)((e,t)=>{rq({kind:"archive-group",project:e,anchor:iF(t,"end"),opener:t})},[]),lO=(0,u.useCallback)(e=>{rq(t=>t?.kind==="archive"?null:{kind:"archive",anchor:iF(e,"end"),opener:e})},[]),lW=(0,u.useCallback)(e=>{rq(t=>t?.kind==="archive"?{...t,askDelete:e}:t?.kind==="archive-group"?{...t,askDelete:void 0!==e}:t)},[]),lF=(0,u.useCallback)(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[];for(let r of y(e.sessions))if((void 0===t.projectKey||eB(r)===t.projectKey)&&ez(r,e.uiState,e.runningIds)){if(void 0!==t.archivedBefore){let n=eI(e$(e.uiState,r.root.id)?.archivedAt);if(null===n||n>=t.archivedBefore)continue}n.push(r.root.id)}return n})(lE,"all"===e?{}:"old"===e?{archivedBefore:Date.now()-2592e6}:e),[lE]),lD=(0,u.useCallback)(e=>{let t=lF(e);lR("string"==typeof e?`archive:${e}`:`archive-project:${e.projectKey}`,t,()=>"string"==typeof e?lL(null):lL(e.projectKey))},[lF,lL,lR]),l_=(0,u.useCallback)(e=>{rS(e),tb(e)},[]),lB=(0,u.useCallback)(e=>{let t=sD.map(e=>e.project.key),n=rk.filter(e=>!t.includes(e));l_(e?n:[...n,...t])},[rk,sD,l_]),lH=(0,u.useCallback)((e,t)=>{let n=rk.includes(e);if(t)return void lB(n);let r=rk.filter(t=>t!==e);l_(n?r:[...r,e])},[rk,l_,lB]),lU=(0,u.useCallback)(e=>{rq(null),sm(tN(e,ev))},[ev,sm]),lK=(0,u.useCallback)(()=>rq(null),[]);(0,u.useEffect)(()=>{if(null!==rK)return;let e=ii.current;if(ii.current=null,!e?.isConnected)return;let t=document.activeElement;t&&t!==document.body||e.focus({preventScroll:!0})},[rK]);let lq=rC?sF:sP.rows;(0,u.useEffect)(()=>{rK?.kind!=="row"||lq.some(e=>e.key===rK.row.key)||rq(null),rK?.kind!=="archive-group"||lq.some(e=>e.key===`archive:${rK.project.key}`)||rq(null)},[rK,lq]);let lV=rK?.kind==="row"?lq.find(e=>"session"===e.kind&&e.key===rK.row.key)??rK.row:null,lZ=(0,u.useCallback)(e=>{sh(e.root)},[sh]),lJ=(0,u.useCallback)(e=>{let t={...rc};for(let n of sP.projects)delete t[n.key],t[n.key]=e(n);sG(t,null)},[rc,sP.projects,sG]),lY=(0,u.useCallback)((e,t)=>{let n=s_.get(e);if(!n)return;let r=!eF(n,sL);if(t)return void lJ(()=>r);let i={...rc};delete i[e],i[e]=r,sG(i,[e])},[rc,s_,sG,lJ,sL]),lG=(0,u.useCallback)(e=>{let t=sP.rows.find(t=>"group-more"===t.kind&&t.projectKey===e||"pinned-more"===t.kind&&e===eM);(t?.kind==="group-more"||t?.kind==="pinned-more")&&rm(n=>{var r;return r=t.nextShown,{...n,[e]:Math.max(eV(n,e),Math.floor(r))}})},[sP.rows]),lX=(0,u.useCallback)(e=>{rm(t=>eZ(t,e))},[]),lQ=(0,u.useCallback)(e=>{ie.current=e,ir(e=>e+1),nF?s4(!1):s2("files")},[s4,nF,s2]),l0=nW||(nF?rz.open:"files"===nD);(0,u.useEffect)(()=>{let e=ie.current;e&&l0&&(ie.current=null,"file-search"===e?document.getElementById("file-search-input")?.focus({preventScroll:!0}):tC.current?.button("project")?.focus({preventScroll:!0}))},[l0,it]);let l1=e=>{let{heading:t,headingTitle:n,notes:r,count:i,onConfirm:s,onCancel:l}=e;return(0,d.jsxs)("div",{className:"sidebar-menu-question",children:[(0,d.jsx)("div",{className:"sidebar-menu-header",title:n,children:t}),r.map(e=>(0,d.jsx)("p",{className:"sidebar-menu-question-text",children:e},e)),(0,d.jsxs)("div",{className:"sidebar-menu-question-buttons",children:[(0,d.jsx)("button",{type:"button",className:"sidebar-menu-question-confirm",disabled:0===i,onClick:s,children:Z("sidebar.deleteCount",{count:i})}),!Y&&(0,d.jsx)("button",{type:"button",className:"sidebar-menu-question-cancel","data-sidebar-menu-autofocus":"",onClick:l,children:Z("sidebar.cancel")})]})]})},l2=(e,t)=>l1({heading:t?Z("sidebar.deleteArchivedInProjectHeading",{name:t.name}):Z("old"===e?"sidebar.deleteOldArchivedHeading":"sidebar.deleteAllArchivedHeading"),headingTitle:t?.root,notes:[Z("sidebar.deleteArchivedMessage")],count:lF(e).length,onConfirm:()=>lD(e),onCancel:()=>lW(void 0)}),l4="",l3=null;if(rK?.kind==="row"&&lV)c=io(lV.family.root),l4=Z("sidebar.sessionActions"),h=(function(e,t){if(t.transient)return[];let n={kind:"action",id:"open-new-tab",shortcut:"T"};return"archive"===e?[{kind:"action",id:"unarchive",shortcut:"A"},{kind:"action",id:"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]:[{kind:"action",id:"pinned"===e?"unpin":"pin",shortcut:"P"},{kind:"action",id:"rename",shortcut:"R"},{kind:"action",id:"fork",shortcut:"F"},{kind:"action",id:t.unread?"mark-read":"mark-unread",shortcut:"U"},t.running?{kind:"action",id:"archive",shortcut:"A",disabledReason:"running"}:{kind:"action",id:"archive",shortcut:"A"},n,{kind:"separator"},{kind:"action",id:"delete",shortcut:"D"}]})(lV.context,lV.status).map((e,t)=>{if("separator"===e.kind)return{type:"separator",id:`separator-${t}`};let n=Z(iA[e.id]);return{type:"item",id:e.id,label:"delete"===e.id?`${n}…`:n,icon:function(e){switch(e){case"open-new-tab":return(0,d.jsx)(nY,{});case"pin":return(0,d.jsx)(nK,{});case"unpin":return(0,d.jsx)(nq,{});case"rename":return(0,d.jsx)(nX,{});case"fork":return(0,d.jsx)(nJ,{});case"mark-read":return(0,d.jsx)(n0,{});case"mark-unread":return(0,d.jsx)(nQ,{});case"archive":return(0,d.jsx)(nH,{});case"unarchive":return(0,d.jsx)(nU,{});case"delete":return(0,d.jsx)(nG,{})}}(e.id),shortcut:e.shortcut,danger:"delete"===e.id,disabled:void 0!==e.disabledReason,disabledReason:"running"===e.disabledReason?Z("sidebar.cannotArchiveRunning"):void 0,onSelect:t=>{let{shiftKey:n}=t;return((e,t,n)=>{let{family:r}=t;switch(e){case"open-new-tab":lS(r);break;case"pin":ln(r,!0);break;case"unpin":ln(r,!1);break;case"rename":lc(r);break;case"fork":lk(t);break;case"mark-read":lr(r,!0);break;case"mark-unread":lr(r,!1);break;case"archive":ll(r);break;case"unarchive":lo(r);break;case"delete":lf(r,n)}})(e.id,lV,n)}}});else if(rK?.kind==="group"){let e,t,i,s,l,a=s_.get(rK.project.key)??rK.project;c=a.name,l4=Z("sidebar.projectActions",{name:a.name}),n=a,r=rK.olderCount,e=sS.countByProject.get(n.key)??0,t=eG(lE,n.key),i=eX(sP.projects,n.key,"up"),s=eX(sP.projects,n.key,"down"),l=(null===n.customName?["rename-project"]:["rename-project","reset-project-name"]).map(e=>"rename-project"===e?{type:"item",id:e,label:Z("sidebar.renameProject"),icon:(0,d.jsx)(nX,{}),onSelect:()=>lu(n)}:{type:"item",id:e,label:Z("sidebar.resetProjectName"),icon:(0,d.jsx)(nU,{}),onSelect:()=>{ij({action:"rename-project",projectKey:n.key,name:null})}}),h=[{type:"item",id:"remove-project",label:Z("sidebar.removeProject"),title:Z("sidebar.removeProjectHint"),icon:(0,d.jsx)(nq,{}),onSelect:()=>{ij({action:"remove-project",projectKey:n.key})}},...l,{type:"item",id:"open-in-files",label:Z("sidebar.openInFilesTab"),icon:(0,d.jsx)(n3,{}),onSelect:()=>{n.current||eb(n.root),lQ("project-button")}},{type:"item",id:"open-new-tab",label:Z("sidebar.openInNewTab"),icon:(0,d.jsx)(nY,{}),shortcut:"T",onSelect:()=>(e=>{let{cwd:t}=tN(e,ev);window.open(`?cwd=${encodeURIComponent(t)}`,"_blank","noopener,noreferrer")})(n)},{type:"separator",id:"separator-layout"},{type:"item",id:"move-up",label:Z("sidebar.moveProjectUp"),icon:(0,d.jsx)(nV,{className:"sidebar-icon-up"}),disabled:null===i,onSelect:()=>{i&&s1(n.key,i.anchorKey,i.position)}},{type:"item",id:"move-down",label:Z("sidebar.moveProjectDown"),icon:(0,d.jsx)(nV,{className:"sidebar-icon-down"}),disabled:null===s,onSelect:()=>{s&&s1(n.key,s.anchorKey,s.position)}},{type:"item",id:"collapse-others",label:Z("sidebar.collapseOtherGroups"),icon:(0,d.jsx)(nV,{}),disabled:sP.projects.every(e=>eF(e,sL)===(e.key===n.key)),onSelect:()=>lJ(e=>e.key===n.key)},{type:"item",id:"expand-all",label:Z("sidebar.expandAllGroups"),icon:(0,d.jsx)(nV,{className:"sidebar-icon-down"}),disabled:sP.projects.every(e=>eF(e,sL)),onSelect:()=>lJ(()=>!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"archive-older",label:Z("sidebar.archiveOlderThanWeek",{count:r}),icon:(0,d.jsx)(nH,{}),disabled:0===r,onSelect:()=>l$(n)},{type:"item",id:"view-archived",label:Z("sidebar.viewArchived",{count:e}),icon:(0,d.jsx)(nH,{}),disabled:0===e,onSelect:()=>s8(n.key)},{type:"item",id:"delete-all",label:Z("sidebar.deleteProjectSessions",{count:t.ids.length}),icon:(0,d.jsx)(nG,{}),danger:!0,disabled:0===t.ids.length,onSelect:e=>{let{keepOpen:t}=e;t(),lI(n.key,!0)}}],rK.askDelete&&(l3=(e=>{let{ids:t,running:n}=eG(lE,e.key);return l1({heading:Z("sidebar.deleteProjectSessionsHeading",{name:e.name}),headingTitle:e.root,notes:[Z("sidebar.deleteProjectSessionsMessage"),...n>0?[Z("sidebar.deleteProjectSessionsRunning",{count:n})]:[]],count:t.length,onConfirm:()=>lA(e),onCancel:()=>lI(e.key,!1)})})(a)),p=264}else if(rK?.kind==="archive-group"){let e,t=sD.find(e=>e.project.key===rK.project.key)?.project??rK.project;c=t.name,l4=Z("sidebar.archivedProjectActions",{name:t.name}),h=[{type:"item",id:"restore-all",label:Z("sidebar.restoreAllArchived",{count:(e=lF({projectKey:t.key})).length}),icon:(0,d.jsx)(nU,{}),disabled:0===e.length,onSelect:()=>la(lP(e))},{type:"separator",id:"separator-delete"},{type:"item",id:"delete-all",label:Z("sidebar.deleteAllArchived",{count:e.length}),icon:(0,d.jsx)(nG,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),lW("all")}}],rK.askDelete&&(l3=l2({projectKey:t.key},t)),p=248}else if(rK?.kind==="archive"){let e,t,n;c=Z("sidebar.archived"),l4=Z("sidebar.archiveActions"),e=lF("all"),t=lF("old"),n=sD.filter(e=>!e.expanded).length,h=[{type:"item",id:"collapse-all",label:Z("sidebar.collapseAllGroups"),icon:(0,d.jsx)(nV,{}),disabled:n===sD.length,onSelect:()=>lB(!1)},{type:"item",id:"expand-all",label:Z("sidebar.expandAllGroups"),icon:(0,d.jsx)(nV,{className:"sidebar-icon-down"}),disabled:0===n,onSelect:()=>lB(!0)},{type:"separator",id:"separator-sessions"},{type:"item",id:"restore-all",label:Z("sidebar.restoreAllArchived",{count:e.length}),icon:(0,d.jsx)(nU,{}),disabled:0===e.length,onSelect:()=>la(lP(e))},{type:"item",id:"delete-old",label:Z("sidebar.deleteOldArchived",{count:t.length}),icon:(0,d.jsx)(nG,{}),danger:!0,disabled:0===t.length,onSelect:e=>{let{keepOpen:t}=e;t(),lW("old")}},{type:"item",id:"delete-all",label:Z("sidebar.deleteAllArchived",{count:e.length}),icon:(0,d.jsx)(nG,{}),danger:!0,disabled:0===e.length,onSelect:e=>{let{keepOpen:t}=e;t(),lW("all")}}],rK.askDelete&&(l3=l2(rK.askDelete,null)),p=280}let l8={layout:Y?"mobile":"desktop",loading:es||!im,error:ec,renamingRootId:rW,renamingProjectKey:r_,confirmDeleteRootId:rH,activeMenuRowKey:rK?.kind==="row"?rK.row.key:rK?.kind==="group"?`group:${rK.project.key}`:rK?.kind==="archive-group"?`archive:${rK.project.key}`:null,onSelectFamily:lZ,onSelectSubagent:sh,onToggleGroup:lY,onShowMore:lG,onShowLess:lX,onTogglePinned:()=>{let e=!rf;rg(e),ty(e),e&&rm(e=>eZ(e,eM))},onToggleRecents:()=>{let e=!rx;rv(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(tc,String(e))}catch{}}(e)},onToggleSubagents:()=>{let e=!rb;ry(e),tr(td,e)},onArchiveFamily:ll,onRestoreFamily:lo,onOpenRowMenu:lC,onRowContextMenu:lN,onRenameCommit:(e,t)=>{ld(e,t)},onRenameCancel:()=>rF(null),onRenameProjectCommit:lh,onRenameProjectCancel:()=>{r_&&lp(r_)},onDeleteConfirm:e=>{lm(e)},onDeleteCancel:()=>{rU(null),rH&&ip(()=>sQ(rH))},onGroupNew:lU,onGroupMenu:lM,onPinEmptyGroup:e=>{ij({action:"pin-project",projectKey:e.key,root:e.root,pinned:!0}),ip(()=>s0(e.key))},onToggleArchiveGroup:lH,onArchiveGroupMenu:lz,onOpenOtherProject:()=>{e7(!0)},onOpenArchive:()=>s8(),onMoveGroup:s1},l6=ev??P??null,l5=l6&&tY>0?Z("sidebar.changedFiles",{count:tY}):void 0,l9=(0,u.useRef)(null),l7=!l6||0===tY;(0,u.useLayoutEffect)(()=>{let e=l9.current;if(l7&&e&&s7.current===e){var t,n;let r;t=document,n=sX(),(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}):t_(t,r)}},[l7,sX]);let ae=nW||nF||"sessions"===nD,at=!nW&&!nF&&"files"===nD&&null!==l6;t=(nF?["below",Z("sidebar.new")]:["tabs",Z("sidebar.tabSessions"),Z("sidebar.tabFiles"),Z("sidebar.new"),l6&&tY>0?tY:"",nD]).join("\n"),o=(0,u.useCallback)(()=>{let e=iB.current;if(e){for(let t of["0","1","2"])if(e.dataset.fit=t,e.scrollWidth<=e.clientWidth)return}},[iB]),(0,u.useLayoutEffect)(()=>{let e=iB.current;if(!e)return;o();let t=new ResizeObserver(o);return t.observe(e),()=>t.disconnect()},[iB,o,t]);let an=sP.archivedCount,ar=nF?13:14,ai=(0,d.jsx)(iT,{onClick:()=>{l6&&W?.(l6)},disabled:!l6||!W,title:Z("terminal.open"),children:(0,d.jsx)(n5,{size:ar})}),as=(0,d.jsx)(iT,{onClick:()=>{i2().then(e=>{e&&nF&&s4(!1)})},disabled:!l6||i3,title:i3?Z(nl?.reason==="remote"?"sidebar.openInExplorerRemoteOnly":"sidebar.openInExplorerUnsupported"):i4,children:(0,d.jsx)(n3,{size:ar})}),al=(0,d.jsx)(iT,{onClick:()=>{nF&&nZ&&s4(!1),nP.current?.openUploadPicker()},disabled:!l6||tB,title:Z("sidebar.uploadFilesTitle"),children:(0,d.jsx)(n7,{size:ar})}),aa=(0,d.jsx)(iT,{onClick:()=>{D?D():tD(e=>e+1),nr(!0),nL.current&&clearTimeout(nL.current),nL.current=setTimeout(()=>nr(!1),2e3)},disabled:!l6,title:Z("sidebar.refreshExplorer"),done:nn,children:nn?(0,d.jsx)(n1,{size:ar}):(0,d.jsx)(re,{size:ar})}),ao=e=>(0,d.jsx)(iT,{onClick:()=>{let e=!t6;t7(e),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tg();if(t)try{t.setItem(tu,String(e))}catch{}}(e)},disabled:!l6,title:Z("sidebar.showIgnoredFiles"),pressed:t6,className:e,children:(0,d.jsx)(rn,{size:ar})}),ac=(0,d.jsx)(iT,{ref:l9,onClick:()=>{if(nF&&nZ){s4(!1),t0(!1);return}t0(e=>!e)},disabled:l7,title:Z("sidebar.changedFiles",{count:tY}),pressed:!l7&&!tQ,children:(0,d.jsx)(rt,{size:ar})});return(0,d.jsxs)("div",{ref:iX,className:`session-sidebar${nF?" is-files-below":""}${nF&&nZ?" is-files-collapsed":""}${nF&&rz.moving?" is-files-folding":""}${m&&ae?" has-archive-footer":""}${r1?" has-toast":""}`,style:{"--sidebar-files-height":`${iY.width}px`},onFocus:e=>{s7.current=e.target},onBlur:e=>{(null!==e.relatedTarget||document.hasFocus())&&(e.currentTarget.contains(e.relatedTarget)||(s7.current=null))},children:[e9&&(0,d.jsx)(ra,{projects:tE(sV??{project:null,projects:sq,worktrees:null,currentWorktreePath:null}),initialPath:e1||ev||void 0,onCancel:()=>e7(!1),onCreate:async(e,t)=>!!e.projectKey&&!!e.projectRoot&&!!await ij({action:"create-project",projectKey:e.projectKey,root:e.projectRoot,name:t})&&(iP(e.cwd),e4(e.cwd),th({cwd:e.cwd,root:e.projectRoot,key:e.projectKey}),eb(e.cwd),e7(!1),!0)}),eQ&&(0,d.jsx)(nO,{initialPath:e1,busy:e6,error:e3,onCancel:()=>{let e=il.current;is.current=null,il.current=null,e0(!1),e8(null),e&&ip(()=>e.isConnected?e:null)},onSelect:e=>void ss(e)}),(0,d.jsxs)("div",{ref:iB,className:"sidebar-header",children:[(nF||nW)&&(0,d.jsx)(r8,{canCreate:!!ev,onNewSession:sb,onOpenProject:sl,onOpenSettings:N}),!nF&&!nW&&(0,d.jsxs)("div",{className:"sidebar-tabs-list",role:"tablist","aria-label":Z("sidebar.tabsLabel"),children:[(0,d.jsxs)("button",{ref:n4,type:"button",role:"tab",id:"session-sidebar-tab-sessions","aria-selected":"sessions"===nD,"aria-controls":"session-sidebar-panel-sessions",tabIndex:"sessions"===nD?0:-1,className:`sidebar-tab${"sessions"===nD?" is-selected":""}`,onClick:()=>s2("sessions"),onKeyDown:lt,children:[(0,d.jsx)(rr,{size:13,className:"sidebar-tab-icon"}),(0,d.jsx)("span",{className:"sidebar-tab-label",children:Z("sidebar.tabSessions")})]}),(0,d.jsxs)("button",{ref:n6,type:"button",role:"tab",id:"session-sidebar-tab-files","aria-selected":"files"===nD,"aria-controls":"session-sidebar-panel-files",tabIndex:"files"===nD?0:-1,title:l5,className:`sidebar-tab${"files"===nD?" is-selected":""}`,onClick:()=>s2("files"),onKeyDown:lt,children:[(0,d.jsx)(n3,{size:13,className:"sidebar-tab-icon"}),(0,d.jsx)("span",{className:"sidebar-tab-label",children:Z("sidebar.tabFiles")}),l6&&tY>0&&(0,d.jsx)("span",{className:"sidebar-tab-count","aria-hidden":"true",children:tY})]})]}),(0,d.jsx)("span",{className:"sidebar-header-spacer"}),(0,d.jsxs)("button",{type:"button",className:"sidebar-new-button",onClick:sb,disabled:!ev,title:ev?Z("sidebar.newSessionTitle",{path:ev}):Z("sidebar.selectProject"),children:[(0,d.jsx)(n8,{size:15}),(0,d.jsx)("span",{className:"sidebar-new-label",children:Z("sidebar.newChat")})]}),(0,d.jsx)("button",{ref:iU,type:"button",onClick:()=>{if(at)return void tK(e=>!e);if(!ae){s2("sessions"),tV(!0);return}tV(e=>!e)},title:at?Z("sidebar.searchFiles"):Z("sidebar.toggleSessionSearch"),"aria-label":at?Z("sidebar.searchFiles"):Z("sidebar.toggleSessionSearch"),"aria-expanded":at?tU:tq,"aria-controls":at?"file-search-input":"session-search-input",className:`sidebar-search-toggle${(at?tU:tq)?" is-active":""}`,children:(0,d.jsx)(n9,{size:16})})]}),(0,d.jsxs)("div",{ref:ri,id:"session-sidebar-panel-sessions",role:nF||nW?"region":"tabpanel","aria-label":nF||nW?Z("sidebar.tabSessions"):void 0,"aria-labelledby":nF||nW?void 0:"session-sidebar-tab-sessions",hidden:!nW&&!nF&&"sessions"!==nD,className:"sidebar-panel sidebar-sessions-panel",onScrollCapture:s3,children:[tq&&(0,d.jsx)("div",{className:"sidebar-search",children:(0,d.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tZ,maxLength:200,"aria-label":Z("sidebar.searchSessions"),placeholder:Z("sidebar.searchSessions"),onChange:e=>tJ(e.target.value),onKeyDown:e=>{if(!e.nativeEvent.isComposing&&229!==e.keyCode){if("Escape"===e.key)e.preventDefault(),e.stopPropagation(),tZ?tJ(""):(tV(!1),iU.current?.focus({preventScroll:!0}));else if("ArrowDown"===e.key||"ArrowUp"===e.key||"Enter"===e.key){let t=ri.current?.querySelectorAll("[data-session-search-result]");if(!t?.length)return;e.preventDefault();let n=t["ArrowUp"===e.key?t.length-1:0];"Enter"===e.key?n.click():n.focus()}}},className:"sidebar-search-input"})}),(0,d.jsx)(iE,{open:tq,query:tZ,selectedSessionId:j,onSelectSession:sh,onSelectSideChat:S,sessions:G,archivedSessionIds:sS.ids,projectNames:sK,children:(0,d.jsxs)("div",{className:"sidebar-sessions-views",children:[(0,d.jsx)("div",{className:"sidebar-sessions-view",hidden:rO.mainHidden,inert:rO.mainInert,children:(0,d.jsx)(id,{...l8,rows:sz,emptyLabel:Z("sidebar.noSessions"),reveal:rV,onRevealHandled:rY})}),rO.archiveMounted&&(0,d.jsxs)("div",{className:`sidebar-sessions-view sidebar-archive-view${rO.archiveClass?` ${rO.archiveClass}`:""}`,inert:rO.archiveInert,onAnimationEnd:e=>{e.target===e.currentTarget&&rR()},children:[(0,d.jsxs)("div",{className:"sidebar-archive-bar",children:[(0,d.jsxs)("button",{ref:s6,type:"button",className:"sidebar-archive-back",title:Z("sidebar.backToSessions"),"aria-label":`${Z("sidebar.backToSessions")}: ${Z("sidebar.archivedCount",{count:an})}`,onClick:()=>rP(!1),children:[(0,d.jsx)(nV,{size:13,className:"sidebar-icon-back"}),(0,d.jsx)("span",{children:Z("sidebar.archived")}),(0,d.jsxs)("span",{className:"sidebar-archive-count",children:["\xb7 ",an]})]}),(0,d.jsx)("button",{type:"button",className:`sidebar-archive-menu-button${rK?.kind==="archive"?" is-active":""}`,title:Z("sidebar.archiveActions"),"aria-label":Z("sidebar.archiveActions"),"aria-haspopup":"menu","aria-expanded":rK?.kind==="archive",disabled:0===sD.length,onClick:e=>lO(e.currentTarget),children:(0,d.jsx)(nB,{size:13})})]}),(0,d.jsx)(id,{...l8,rows:sF,emptyLabel:Z("sidebar.noArchived"),reveal:rG,onRevealHandled:rQ})]})]})}),m&&(0,d.jsxs)("button",{type:"button",className:"sidebar-archive-entry","data-archive-entry":"","aria-label":Z("sidebar.archivedCount",{count:an}),"aria-current":g?"page":void 0,onClick:()=>s8(),children:[(0,d.jsx)(nH,{size:15}),(0,d.jsx)("span",{children:Z("sidebar.archived")}),(0,d.jsx)("span",{className:"sidebar-archive-entry-count","aria-hidden":"true",children:an})]})]}),nF&&rz.open&&(0,d.jsx)("div",{...iY.separatorProps,"aria-controls":"session-sidebar-panel-files",className:`panel-resize-handle sidebar-files-resize-handle${iY.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-files",title:`${Z("sidebar.resizeFiles")}: ${Z("sidebar.resizeFilesHint")}`}),(0,d.jsx)(i_,{target:b,children:(0,d.jsxs)("div",{ref:rs,id:"session-sidebar-panel-files",role:nF||nW?"region":"tabpanel","aria-label":nF||nW?Z("sidebar.tabFiles"):void 0,"aria-labelledby":nF||nW?void 0:"session-sidebar-tab-files",hidden:!nW&&!nF&&"files"!==nD,className:"sidebar-panel sidebar-files-panel",onScrollCapture:s3,onTransitionEnd:e=>{e.target===e.currentTarget&&"height"===e.propertyName&&r$()},children:[nF&&(0,d.jsxs)("div",{className:"sidebar-files-section",children:[(0,d.jsxs)("button",{type:"button",className:"sidebar-files-section-toggle","aria-expanded":!nZ,"aria-controls":"session-sidebar-files-body",title:l5,onClick:()=>s4(!nZ),children:[(0,d.jsx)(nV,{size:12,strokeWidth:3,className:`session-tree-chevron${nZ?"":" is-open"}`}),(0,d.jsx)("span",{className:"sidebar-files-section-label",children:Z("sidebar.tabFiles")}),l5&&(0,d.jsxs)("span",{className:"sidebar-files-section-count","aria-hidden":"true",children:["\xb7 ",tY]})]}),(0,d.jsxs)("div",{className:"sidebar-files-keys",role:"group","aria-label":Z("sidebar.fileActions"),children:[ai,as,al,aa,ao(),ac,(0,d.jsx)(iT,{onClick:()=>{if(nZ){tK(!0),lQ("file-search");return}tK(e=>!e)},disabled:!l6,title:Z("sidebar.searchFiles"),expanded:tU,controls:"file-search-input",children:(0,d.jsx)(n9,{size:13})})]})]}),(0,d.jsxs)("div",{id:"session-sidebar-files-body",className:"sidebar-files-body",hidden:nF&&rz.bodyHidden,inert:nF&&rz.bodyInert,children:[(0,d.jsxs)("div",{className:"sidebar-files-head",children:[(0,d.jsx)(iC,{handleRef:tC,layout:nF?"row":"stacked",context:sV??{project:null,worktrees:null,currentWorktreePath:null,projects:sq},mobile:Y,label:Z("sidebar.projectAndWorktree"),placeholder:$&&!i6.current?"":Z("sidebar.selectProject"),homeDir:eE,projectActivity:sC,worktreeHint:s$,newWorktreeTitle:Z("sidebar.createWorktreeTitle"),onPick:sp,onUseDefaultDirectory:()=>{sa()},onOpenFolder:sl,onRefreshWorktrees:su,onCreateWorktree:sc,onRemoveWorktree:sd}),!nF&&l6&&(0,d.jsxs)("div",{className:"sidebar-files-actions",role:"group","aria-label":Z("sidebar.fileActions"),children:[W&&ai,as,al,aa,ao("sidebar-files-views-start"),ac]})]}),l6&&i8&&(0,d.jsxs)("div",{role:"alert",className:"sidebar-files-error",children:[(0,d.jsx)("span",{className:"sidebar-files-error-text",children:i8}),(0,d.jsx)(ro,{onClick:()=>nc(null),title:Z("files.dismissError")})]}),(0,d.jsx)("div",{ref:iH,className:"sidebar-files-scroll scrollbar-subtle",children:l6&&(0,d.jsx)(rD,{ref:nP,cwd:l6,onOpenFile:O??(()=>{}),refreshKey:tF,onAtMention:_,onAtMentions:B,onUploadBusyChange:tH,changesCollapsed:tQ,onChangesCountChange:tG,fileSearchOpen:tU,searchAlwaysVisible:nW,onFileSearchOpenChange:tK,showHidden:t6})})]})]})}),(0,d.jsx)(r4,{open:null!==rK,anchor:rK?.anchor??null,sheet:Y,ariaLabel:l4,title:c,items:h,cancelLabel:Z("sidebar.cancel"),focusCancel:null!==l3,onClose:lK,returnFocusTo:rK?.opener??null,width:p,children:l3}),(0,d.jsx)(i$,{toast:r1,onDismiss:()=>r2(null),dismissLabel:Z("sidebar.dismiss")})]})}function i_(e){let{target:t,children:n}=e;return t?(0,g.createPortal)(n,t):n}let iB=/\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g,iH=/^\x1B(?:\][^\x07\x1B]*(?:\x07|\x1B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/,iU=/\x1B_pi:[^\x07\x1B\n]*(?:\x07|\x1B\\)/g;function iK(e){return e.includes("\x1b")?e.replace(iU,"").replace(iB,""):e}function iq(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(iH);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 iV(e,t){let n=iq(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function iZ(e){return iq(e)[0]?.char}let iJ=/[▀-▟]/,iY=/https?:\/\/(?:\[[0-9A-Fa-f:.]+\])?[^\s<>"'`\]}。,、;:!?)」』】]*/gi,iG=/^[.,;:!?]$/,iX={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:""},iQ={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},i0="\x1b[200~",i1="\x1b[201~";function i2(e){return"custom"===e.role&&!e.display}function i4(e){return"user"===e.role||"custom"===e.role&&!i2(e)&&("compaction"===e.customType||"pi-web:subagent-notification"===e.customType||"subagent-notification"===e.customType)}function i3(e){return"user"===e.role||"assistant"===e.role||"toolResult"===e.role}function i8(e,t){return"assistant"===e.role||t&&!i2(e)}function i6(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function i5(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(e.content??[]).filter(e=>!i6(e,t))}function i9(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function i7(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"aborted"===e.stopReason}function se(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.isStreaming&&"length"===e.stopReason}function st(e){return(e.content??[]).some(e=>"text"===e.type?e.text.trim().length>0:"image"===e.type||"toolCall"===e.type)}function sn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i5(e,t),r=n.findLastIndex(e=>"text"!==e.type&&"image"!==e.type);return -1===r?{answerBlocks:n,processBlocks:[]}:{answerBlocks:n.slice(r+1),processBlocks:n.slice(0,r+1)}}function sr(e){return!!e&&"object"==typeof e&&"pi-web-subagent"===e.kind&&"string"==typeof e.sessionId&&e.sessionId.length>0}function si(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function ss(e){try{return decodeURIComponent(e)}catch{return e}}function sl(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function sa(e){return!!e&&(/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"))}let so=/^\/(?:mnt\/|cygdrive\/)?([a-zA-Z])(?:\/(.*))?$/;function sc(e){if(!e.startsWith("/")||e.startsWith("//"))return e;let t=e.match(so);if(!t)return e;let[,n,r]=t;return`${n.toUpperCase()}:/${r??""}`}function sd(e){let t=sl(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=n?1:2*!!r,l=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){l.length>s&&".."!==l[l.length-1]?l.pop():i||n||r||l.push(e);continue}l.push(e)}let a=l.join("/");return n?1===l.length?`${a}/`:a:r?`//${a}`:i?`/${a}`:a}function su(e,t){let n,r,i,s,l,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)return null;let o=e.split("#",1)[0].split("?",1)[0].trim();if(!o)return null;let c=null,d=null,u=ss(o),p=u.startsWith("\\\\"),h=sl(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=ss(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(o))?"absolute":null:/^[a-zA-Z]:\//.test(h)?(c=h,d="absolute"):h.startsWith("/")?(c=sa(t)?sc(h):h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${sl(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let f=sd(c).replace(/:\d+(?:(?::|-)\d+)?$/,"");return"relative"===d&&a&&(n=sd(f).replace(/\/+$/,""),r=sd(a).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(r))?n.toLowerCase():n,!(s===(l=i?r.toLowerCase():r)||s.startsWith(`${l}/`)))?null:f}let sp=/^page=(\d+)$/i;function sh(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(sp);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function sm(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function sf(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function sg(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function sx(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function sv(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sb(e){if(!sv(e)||!sv(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function sy(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let s=0;s<i;s++)e.push({type:"line",left:t[s]??r(),right:n[s]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},gap(){i(),e.length>0&&"gap"!==e[e.length-1].type&&e.push({type:"gap",count:null})},finish(){i(),e.length>0&&"gap"===e[e.length-1].type&&e.pop()}}}function sw(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let s of e.split(/\r?\n/)){let e=s.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let s=e[1]?.toLowerCase()??"update",l=(e[2]??"").trim();n?.finish(),i=s,r={oldPath:"add"===s?void 0:l,newPath:"delete"===s?void 0:l,rows:(n=sy()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(s)){let e=s.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let l=n;if(!s.startsWith("*** ")){if("update"===i&&s.startsWith("@@")){l.gap();continue}if("update"===i){let e=s[0],t=s.slice(1);"+"===e?l.added(t,null):"-"===e?l.removed(t,null):" "===e?l.context(t,null):""!==s&&l.context(s,null)}else if("add"===i){if(""===s)continue;n.added(s.startsWith("+")?s.slice(1):s,null)}else if("delete"===i){if(""===s)continue;n.removed(s.startsWith("-")?s.slice(1):s,null)}}}n?.finish();let s=t.filter(e=>e.rows.length>0);return s.length>0?s:null}function sj(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=sy();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,s]=e,l=Number(i);"+"===r?t.added(s,l):"-"===r?t.removed(s,l):t.context(s,l)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function sk(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function sS(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}function sC(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function sN(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m ${r}s`}var sE=n(32316);let sM="pi-web:clipboard-failure";async function s$(e){let t=null,n=null;try{if(navigator.clipboard?.writeText)return void await navigator.clipboard.writeText(e);if(t=document.activeElement,(n=document.createElement("textarea")).value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),!document.execCommand("copy"))throw Error("Clipboard copy failed")}catch(e){throw window.dispatchEvent(new Event(sM)),e}finally{n?.remove(),t?.isConnected&&t instanceof HTMLElement&&t.focus({preventScroll:!0})}}let sI={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},sT={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},sR={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function sA(e){let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function sL(e){let t;return null!==(Object.hasOwn(sT,t=sA(e))?sT[t]:null)}function sP(e){let t;return null!==(Object.hasOwn(sR,t=sA(e))?sR[t]:null)}var sz=n(88374),sO=n(5924),sW=n(94764),sF=n(63835),sD=n(54152),s_=n(31678),sB=n(6796),sH=n(98164);let sU=["obsidian","logseq","notion","vscode","vscode-insiders","cursor","zed","jetbrains","zoommtg","zoomus","msteams","slack"],sK=RegExp(`^(?:${sU.join("|")}):`,"i"),sq=sW.j.clobberPrefix??"user-content-",sV={...sW.j,clobberPrefix:sq,attributes:{...sW.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...sW.j.protocols,href:[...sW.j.protocols?.href??[],"file",...sU]},strip:[...sW.j.strip||[],"iframe","object","style","form"]};function sZ(e){return sK.test(e)?e:(0,sE.Lv)(e)}function sJ(e){return/^file:/i.test(e)?e:sZ(e)}function sY(e){return!!(e&&/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(e))}function sG(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("href");if(!t?.startsWith("#"))return;e.preventDefault();let n=t.slice(1);if(!n)return;try{n=decodeURIComponent(n)}catch{}let r=CSS.escape(n);e.currentTarget.closest(".markdown-body")?.querySelector(`[id="${r}"], a[name="${r}"]`)?.scrollIntoView({block:"start"})}function sX(e,t,n,r,i){let s="",l=0;for(let a=e.indexOf(t);-1!==a;a=e.indexOf(t,a+1)){if(a>0&&n.includes(e[a-1]))continue;r.lastIndex=a;let t=r.exec(e);t&&(s+=e.slice(l,a)+i(t),a=(l=r.lastIndex)-1)}return s+e.slice(l)}let sQ=/`((?:[^`\n]|\\`)*?[^\\`\n])`(?!`)/y;function s0(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,l=null,a=new Map;for(let e=0;e<n.length;e++){var o,c;let t=n[e];if(l){r.push(t),RegExp(`</${l}\\s*>`,"i").test(t)&&(l=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],n=d[1].length;i?e===i.marker&&n>=i.size&&/^[ \t]*$/.test(t.slice(d[0].length))&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let u=t.match(/<(code|pre|script|style)\b/i);if(u){let e=u[1].toLowerCase(),n=t.slice((u.index??0)+u[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(l=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||(t=sX(t,"`","\\`",sQ,e=>{let[t,n]=e,r=n.replace(/\\`/g,"`");if(r===n)return t;let i="`".repeat(Math.max(...r.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${i}${r}${i}`})),s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let h=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(h){let e=h[2].trim();if(o=e,/\\[A-Za-z]+/.test(o)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(o)){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(m){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${m[1]}$$`,...n.slice(e+1,t).map(e=>s2(e,m[1])),`${m[1]}$$`),e=t;continue}}let f=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(f){let e=f[2].trim();if(e){r.push(`${f[1]}$$`,`${f[1]}${e}`,`${f[1]}$$`);continue}}let g=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(g){let t=g[1],i=g[2].trimEnd();if(i&&!i.includes("$$")){let s=s1(n,e+1,t,a);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(s2(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let x=t.match(/^([ \t]{0,3})\$\$\s*$/);if(x){let t=x[1],i=s1(n,e+1,t,a);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(s2(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((c=t,/^\s{0,3}\[[^\]]+\]:/.test(c)||/]\s*\(/.test(c)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(c)||/\b(?:https?|file|mailto):/i.test(c)||/\b[A-Za-z]:\\/.test(c)?c:sX(c,"\\(","\\",s4,e=>{let[t,n]=e;return n.trim()?`$${n}$`:t})))}return r.join(t)}function s1(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,l,a,o;let t=e[i];if(s=t,""===(l=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(l)&&/^\$\$\s*$/.test(s.slice(l.length)))return{index:i,content:"",glued:!1};if(a=t,/^ {0,3}(`{3,}|~{3,})/.test(a)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(a)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(a)||/^ {0,3}>/.test(a)||/<(code|pre|script|style)\b/i.test(a)||(o=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(o)))return r.set(n,i),null;let c=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==c)return{index:i,content:c,glued:!0}}return r.set(n,e.length),null}function s2(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let s4=/\\\(([^`\r\n$]*?[^`\r\n$\\])\\\)/y,s3={singleTilde:!1},s8=/[\u3001\u3002\u3008-\u3011\u3014-\u301B\uFF01\uFF08\uFF09\uFF0C\uFF1A\uFF1B\uFF1F\u2018\u2019\u201C\u201D\u2013\u2014\u2026\u00B7\uFF5E\u301C]/;function s6(){return(e,t)=>{var n;let r;n="string"==typeof t.value?t.value:"",(r=e=>{let t=e.children;for(let e=0;e<t.length;e++){let i=t[e];"link"===i.type&&function(e,t,n,r){if(null!=n.title||1!==n.children.length)return;let i=n.children[0];if("text"!==i.type)return;let s=n.position?.start,l=n.position?.end;if(s?.offset==null||l?.offset==null||r.slice(s.offset,l.offset)!==i.value)return;let a=i.value,o=a.search(s8);if(o<=0||!n.url.endsWith(a))return;let c=a.slice(0,o),d={line:s.line,column:s.column+o,offset:s.offset+o};n.url=n.url.slice(0,n.url.length-a.length)+c,i.value=c,n.position={start:s,end:d},e.splice(t+1,0,{type:"text",value:a.slice(o),position:{start:d,end:l}})}(t,e,i,n);let s=t[e];"children"in s&&Array.isArray(s.children)&&r(s)}})(e)}}let s5=function(){sH.A.call(this);let e=this.data(),t=e.micromarkExtensions?.at(-1),n=t?.text?.[36];for(let e of Array.isArray(n)?n:n?[n]:[]){if("mathText"!==e.name)continue;let t=e.tokenize;e.tokenize=function(e,n,r){let i=this.now();return t.call(this,e,e=>{let t=this.sliceSerialize({start:i,end:this.now()});if(t.startsWith("$")&&!t.startsWith("$$")){let n=t.slice(1,-1),i=/^\s*[+-]?(?:\d|\.\d)/.test(n),s=null!==e&&e>=48&&e<=57,l=/^\s/.test(n)!==/\s$/.test(n);if(i&&(s||l))return r(e)}return n(e)},r)}}};function s9(){return e=>{let t=e=>{("link"===e.type||"definition"===e.type)&&/^\/?[A-Za-z]:\//.test(e.url)&&(e.url=`file:///${e.url.replace(/^\//,"")}`),"children"in e&&e.children.forEach(t)};t(e)}}let s7=[[sD.A,["yaml"]],[s_.A,s3],sB.A,s6,s5,s9],le=/[ \t]*(?:\r\n|\r|\n)[ \t]*/,lt=new Set(["root","blockquote","listItem","footnoteDefinition"]);function ln(){return{type:"lineBreak",data:{hName:"br"}}}function lr(e){if(!e.children)return;let t=lt.has(e.type);e.children=e.children.map(e=>{if("html"!==e.type)return lr(e),e;let n={type:"text",value:e.value??""};return t?{type:"paragraph",children:[n]}:n})}function li(e){e.children&&(e.children=e.children.flatMap(e=>"break"===e.type?[ln()]:"text"===e.type&&e.value?e.value.split(le).flatMap((e,t)=>[...t>0?[ln()]:[],...e?[{type:"text",value:e}]:[]]):(li(e),[e])))}let ls=[...s7??[],function(){return e=>{lr(e),li(e)}}],ll=[...s7??[],function(){return(e,t)=>{lr(e),li(e);let n=String(t.value).split(/\r\n|\r|\n/);for(let t of e.children??[])"paragraph"===t.type&&function(e,t){if(!e.position)return;let n=e.position.start.line-1,r=()=>{let e=/^[ \t]*/.exec(t[n]??"")?.[0];return e?[{type:"text",value:e}]:[]},i=r(),s=e=>{e.children=e.children?.flatMap(e=>"lineBreak"===e.type?(n+=1,[e,...r()]):(e.children?s(e):e.position&&(n+=e.position.end.line-e.position.start.line),[e]))};s(e),e.children=[...i,...e.children??[]]}(t,n)}}],la=[[sD.A,["yaml"]],[s_.A,s3],sB.A,s6,s5,s9];function lo(){return e=>{let t=e=>{if(!e||"object"!=typeof e)return;let n=e.properties?.href;for(let r of("element"===e.type&&"string"==typeof n&&n.startsWith("#")&&n.length>1&&(e.properties.href=`#${sq}${n.slice(1)}`),e.children??[]))t(r)};t(e)}}function lc(e){return"text"===e.type?e.value:"element"===e.type?e.children.map(lc).join(""):""}function ld(){return e=>{let t=e=>{e.children=e.children.map(e=>{if("element"!==e.type)return e;let n="pre"===e.tagName&&1===e.children.length?e.children[0]:null,r=n?.type==="element"&&"code"===n.tagName?n.properties.className:null;return Array.isArray(r)&&r.includes("language-math")?{type:"element",tagName:"div",properties:{className:["markdown-math-display"],dataMathSource:lc(e).replace(/\n$/,"")},children:[e]}:(t(e),e)})};t(e)}}let lu=[sO.A,[sF.A,sV],lo,ld,[sz.A,{throwOnError:!1,strict:!1}]],lp=[sO.A,[sF.A,sV],function(){return e=>{let t=new Map,n=e=>e.children.forEach(e=>{if("element"===e.type){if(/^h[1-6]$/.test(e.tagName)){let n=lc(e).toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\- ]/gu,"").replace(/ /g,"-"),r=n;for(;t.has(r);)t.set(n,t.get(n)+1),r=`${n}-${t.get(n)}`;t.set(r,0),e.properties.dataHeadingAnchor=r}n(e)}});n(e)}},ld,[sz.A,{throwOnError:!1,strict:!1}]],lh=[sO.A,[sF.A,sV],lo,[sz.A,{throwOnError:!1,strict:!1}]],lm=/^ {0,3}(`{3,}|~{3,})/,lf=/^(?:[*+-]|\d{1,9}[.)])(?:[ \t]|$)/,lg=/<[A-Za-z!/?]/,lx=/`[^`]*`/g,lv=/^ {0,3}\[[^\]]+\]:/,lb=/^(`{3,}|~{3,})[ \t]*([^`\s]*)[^`]*$/;function ly(e){return"plantuml"===e||"puml"===e}let lw="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";async function lj(e){if("u"<typeof CompressionStream)return null;try{let t=new Blob([e]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}catch{return null}}async function lk(e){let t=new TextEncoder().encode(e),n=await lj(t);return n?function(e){let t="";for(let n=0;n<e.length;n+=3){let r=e[n],i=e[n+1]??0,s=e[n+2]??0;t+=lw[r>>2]+lw[(3&r)<<4|i>>4]+lw[(15&i)<<2|s>>6]+lw[63&s]}return t}(n):function(e){let t="~h";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}(t)}async function lS(e){let t="https://www.plantuml.com/plantuml/svg/"+await lk(e);return t.length<=6e3?t:null}function lC(e){let{src:t,alt:n="",children:r,className:i,style:s}=e,{t:l}=(0,ns.s)(),a=l("chat.previewImage"),o=n.trim()?`${a}: ${n}`:a,[c,p]=(0,u.useState)(!1),h=(0,u.useRef)(null),m=(0,u.useRef)(null),f=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(!c)return;let e=m.current;if(!e)return;let t=h.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),f.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[c]);let g=()=>{m.current?.open&&m.current.close(),p(!1)};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{ref:h,type:"button",className:i,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...s},onClick:()=>p(!0),"aria-label":o,"aria-haspopup":"dialog","aria-expanded":c,title:a,children:r}),c&&(0,d.jsxs)("dialog",{ref:m,className:"image-preview-dialog","aria-label":l("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),g()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),g())},onClick:e=>{e.target===e.currentTarget&&g()},children:[(0,d.jsx)("img",{className:"image-preview-image",src:t,alt:n}),(0,d.jsx)("button",{ref:f,type:"button",className:"image-preview-close",onClick:g,"aria-label":l("chat.close"),title:l("chat.close"),children:(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}var lN=n(50640),lE=n(55961),lM=n(7644);let l$="pi-theme",lI={preference:"auto",theme:"light"},lT=new Set,lR=null,lA=!1;function lL(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function lP(e){return"auto"===e?lL():e}function lz(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",ir(e)))}function lO(){if(lR)return lR;let e=function(){try{let e=localStorage.getItem(l$);if(r6.some(t=>t.id===e))return e}catch{}return"auto"}(),t=lP(e);return lz(t),lR={preference:e,theme:t}}function lW(e,t,n){if(lz(t),n)try{localStorage.setItem(l$,e)}catch{}lR={preference:e,theme:t},lT.forEach(e=>e())}function lF(){let e=lO();if("auto"!==e.preference)return;let t=lL();t!==e.theme&&lW("auto",t,!1)}function lD(e){return lT.add(e),lO(),lA||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",lF),window.addEventListener("focus",lF),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&lF()}),lA=!0),lF(),()=>{lT.delete(e)}}function l_(){return lO()}function lB(){return lI}function lH(){let e=(0,u.useSyncExternalStore)(lD,l_,lB),t=(0,u.useCallback)((e,t)=>{if(lO().preference===e)return;let n=lP(e),r=()=>{lW(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,l=t?.y??window.innerHeight/2,a=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(l,window.innerHeight-l));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${l}px)`,`circle(${a}px at ${s}px ${l}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]);return{theme:e.theme,preference:e.preference,setThemePreference:t,isDark:ir(e.theme)}}let lU=!1,lK=null;function lq(){return lU}function lV(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0],[t,r]=(0,u.useState)(lq);return(0,u.useEffect)(()=>{if(t||!e)return;let i=!0;return(lK??=n.e(1326).then(n.bind(n,61326)).then(()=>{lU=!0},e=>{throw lK=null,e})).then(()=>{i&&r(!0)},()=>{}),()=>{i=!1}},[e,t]),t}let lZ=2e3,lJ=!1,lY=[],lG=!1;function lX(){lG=!1,lY.pop()?.(),lY.length>0&&lQ()}function lQ(){!lG&&(lG=!0,"function"==typeof window.requestIdleCallback?window.requestIdleCallback(lX,{timeout:500}):setTimeout(lX,50))}function l0(e,t){let n=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),r=document.createElement("a");r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),0)}function l1(e){let{code:t,isStreaming:r,defaultPreview:i=!1}=e,{isDark:s}=lH(),{t:l}=(0,ns.s)(),[a,o]=(0,u.useState)(i),[c,p]=(0,u.useState)(null),[h,m]=(0,u.useState)(!1),f=(0,u.useRef)(null),g=`${s?"dark":"light"}
|
|
6
|
+
${t}`,x=a&&!r;(0,u.useEffect)(()=>{if(!x)return;let e=!1;return p({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:s?"dark":"default"}),!await r.parse(t,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=await r.render(i,t);e||p({key:g,status:"ready",svg:l.svg})})().catch(()=>{e||p({key:g,status:"error"})}),()=>{e=!0}},[t,g,s,x]);let v=(0,u.useMemo)(()=>(0,d.jsx)(l2,{isStreaming:r,previewVisible:x,onToggle:()=>o(e=>!e),title:x?l("i18n.showMermaidSource"):l("i18n.previewMermaid")}),[r,x,l]);if(!x)return(0,d.jsx)(ae,{code:t,lang:"mermaid",headerAction:v,isStreaming:r});let b=c?.key===g&&"error"===c.status?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-error",children:l("i18n.invalidMermaid")}):c?.key!==g||"ready"!==c.status?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":l("i18n.renderingMermaid")}):(0,d.jsxs)(d.Fragment,{children:[!h&&(0,d.jsx)("button",{ref:f,type:"button",className:"mermaid-block mermaid-preview-button",title:l("i18n.openMermaidViewer"),"aria-label":l("i18n.openMermaidViewer"),onClick:()=>m(!0),dangerouslySetInnerHTML:{__html:c.svg}}),h&&(0,d.jsx)(l8,{title:l("i18n.mermaidDiagram"),label:l("i18n.mermaidViewer"),onClose:()=>m(!1),children:(0,d.jsx)("div",{dangerouslySetInnerHTML:{__html:c.svg}})})]});return(0,d.jsx)(l3,{lang:"mermaid",actions:(0,d.jsxs)(d.Fragment,{children:[c?.key===g&&"ready"===c.status&&(0,d.jsx)(l4,{onClick:()=>{let e=f.current?.querySelector("svg");e&&l0(new XMLSerializer().serializeToString(e),"mermaid-diagram.svg")}}),v]}),children:b})}function l2(e){let{isStreaming:t,previewVisible:n,onToggle:r,title:i,previewLabel:s}=e,{t:l}=(0,ns.s)();return(0,d.jsx)("button",{type:"button",onClick:r,disabled:t,title:t?l("i18n.previewAfterStreaming"):i,className:["markdown-code-action",n?"is-active":""].filter(Boolean).join(" "),children:n?l("i18n.source"):s??l("i18n.preview")})}function l4(e){let{onClick:t}=e,{t:n}=(0,ns.s)();return(0,d.jsx)("button",{type:"button",className:"markdown-code-action",title:`${n("i18n.downloadFile")} (SVG)`,"aria-label":`${n("i18n.downloadFile")} (SVG)`,onClick:t,children:"SVG"})}function l3(e){let{lang:t,actions:n,children:r}=e;return(0,d.jsxs)("div",{className:"markdown-code-block",children:[(0,d.jsxs)("div",{className:"markdown-code-header",children:[(0,d.jsx)("span",{className:"markdown-code-lang",children:t}),(0,d.jsx)("div",{className:"markdown-code-actions",children:n})]}),r]})}function l8(e){let{title:t,label:n,onClose:r,children:i}=e,{t:s}=(0,ns.s)(),l=(0,u.useRef)(null),[a,o]=(0,u.useState)(1);return(0,u.useEffect)(()=>{let e=l.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,d.jsx)("dialog",{ref:l,className:"mermaid-zoom-dialog","aria-label":n,onCancel:e=>{e.preventDefault(),r()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),r())},children:(0,d.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,d.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,d.jsx)("span",{className:"mermaid-zoom-title",children:t}),(0,d.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,d.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,d.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:a<=.5,title:s("i18n.zoomOut"),"aria-label":s("i18n.zoomOut"),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M5 12h14"})})}),(0,d.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*a),"%"]}),(0,d.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:a>=3,title:s("i18n.zoomIn"),"aria-label":s("i18n.zoomIn"),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,d.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:s("i18n.fitToWidth"),"aria-label":s("i18n.fitToWidth"),children:(0,d.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,d.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,d.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:r,title:s("i18n.close"),"aria-label":s("i18n.close"),children:(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,d.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&r()},children:(0,d.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*a}%`},children:i})})]})})}let l6={...lM.xJ,'pre[class*="language-"]':{...lM.xJ['pre[class*="language-"]']}};function l5(e){let{rows:t,stylesheet:n,useInlineStyles:r}=e;return t.map((e,t)=>{let i=e.children??[],s=i[0]?.properties?.className.includes("react-syntax-highlighter-line-number")?i[0]:null,l={...e,properties:{...e.properties,className:[...e.properties?.className??[],"markdown-code-line-text"]},children:s?i.slice(1):i};return(0,d.jsxs)("span",{className:"markdown-code-line",children:[s&&(0,d.jsx)("span",{className:"markdown-code-line-number","data-line-number":t+1,"aria-hidden":"true",style:s.properties?.style}),(0,lN.Ay)({node:l,stylesheet:n,useInlineStyles:r,key:"text"})]},t)})}delete l6['pre[class*="language-"]'].background;let l9=(0,u.memo)(function(e){let{text:t}=e;return(0,d.jsx)("span",{className:"markdown-code-stream-chunk is-frozen",children:t})});function l7(e){let{code:t}=e,n=[],r=0,i=0;for(let e=t.indexOf("\n");-1!==e;e=t.indexOf("\n",e+1))64===(i+=1)&&(n.push(t.slice(r,e)),r=e+1,i=0);let s=t.slice(r);return(0,d.jsxs)(d.Fragment,{children:[n.map((e,t)=>(0,d.jsx)(l9,{text:e},t)),(0,d.jsx)("span",{className:"markdown-code-stream-chunk",children:s})]})}let ae=(0,u.memo)(function(e){let{code:t,lang:n,headerAction:r,isStreaming:i}=e,{isDark:s}=lH(),{t:l}=(0,ns.s)(),[a,o]=(0,u.useState)(!1),c=lV(),[p,h]=(0,u.useState)(()=>{var e;return!i&&lq()&&(e=t.length,lJ||(lJ=!0,setTimeout(()=>{lZ=2e3,lJ=!1},0)),!(e>lZ)&&(lZ-=e,!0))});return(0,u.useEffect)(()=>{if(!i&&!p&&c){var e;return e=()=>h(!0),lY.push(e),lQ(),()=>{let t=lY.indexOf(e);-1!==t&&lY.splice(t,1)}}},[i,p,c]),(0,d.jsxs)("div",{className:"markdown-code-block",children:[(0,d.jsxs)("div",{className:"markdown-code-header",children:[(0,d.jsx)("span",{className:"markdown-code-lang",children:n||"text"}),(0,d.jsxs)("div",{className:"markdown-code-actions",children:[r,(0,d.jsx)("button",{onClick:()=>{o(!1),s$(t).then(()=>{o(!0),setTimeout(()=>o(!1),1500)},()=>{})},className:"markdown-code-action",children:l(a?"i18n.copied":"i18n.copy")})]})]}),i?(0,d.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,whiteSpace:"pre-wrap",overflowWrap:"anywhere",backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,d.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:(0,d.jsx)(l7,{code:t})})}):(0,d.jsx)(lE.A,{language:p&&n||"text",style:s?l6:lM.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",flexShrink:0},renderer:l5,customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,fontWeight:"var(--font-mono-weight)",border:"none",borderRadius:0,backgroundColor:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t})]})}),at=new Set;function an(e){let{code:t,lang:n,isStreaming:r}=e,{t:i}=(0,ns.s)(),s=""!==t.trim(),[l,a]=(0,u.useState)(()=>at.has(t)?t:null),[o,c]=(0,u.useState)(null),p=s&&l===t&&!r,h=o?.code===t?o:void 0;(0,u.useEffect)(()=>{if(!p||h)return;let e=!1;return lS(t).then(n=>{e||c(n?{code:t,status:"ready",url:n}:{code:t,status:"tooLong"})},()=>{e||c({code:t,status:"failed"})}),()=>{e=!0}},[t,h,p]);let m=(0,u.useMemo)(()=>(0,d.jsx)(l2,{isStreaming:r,previewVisible:p,onToggle:()=>{if(p)a(null);else at.add(t),a(t)},title:p?i("i18n.showPlantUmlSource"):i("i18n.renderOnPlantUml"),previewLabel:i("i18n.renderOnPlantUml")}),[t,r,p,i]);return p?(0,d.jsx)(l3,{lang:n,actions:m,children:(0,d.jsx)(ar,{result:h})}):(0,d.jsx)(ae,{code:t,lang:n,headerAction:s?m:void 0,isStreaming:r})}function ar(e){let{result:t}=e,{t:n}=(0,ns.s)();return t?"tooLong"===t.status?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-error",children:n("i18n.plantUmlTooLong")}):"failed"===t.status?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-error",children:n("i18n.plantUmlLoadFailed")}):(0,d.jsx)(ai,{url:t.url},t.url):(0,d.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":n("i18n.renderingPlantUml")})}function ai(e){let{url:t}=e,{t:n}=(0,ns.s)(),[r,i]=(0,u.useState)(!1),[s,l]=(0,u.useState)(!1),[a,o]=(0,u.useState)(!1);if(s)return(0,d.jsx)("div",{className:"mermaid-block mermaid-block-error",children:n("i18n.plantUmlLoadFailed")});let c=e=>(0,d.jsx)("img",{src:t,alt:n("i18n.plantUmlDiagram"),className:e,referrerPolicy:"no-referrer",onLoad:()=>i(!0),onError:()=>l(!0)});return(0,d.jsxs)(d.Fragment,{children:[!r&&(0,d.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":n("i18n.renderingPlantUml")}),!a&&(0,d.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:n("i18n.openPlantUmlViewer"),"aria-label":n("i18n.openPlantUmlViewer"),hidden:!r,onClick:()=>o(!0),children:c("svg-block-image")}),a&&(0,d.jsx)(l8,{title:n("i18n.plantUmlDiagram"),label:n("i18n.plantUmlViewer"),onClose:()=>o(!1),children:c("svg-zoom-image")})]})}let as="http://www.w3.org/2000/svg";function al(e,t){let n=t.parseFromString(e,"image/svg+xml");return n.getElementsByTagName("parsererror").length>0?null:n.documentElement}function aa(e){let{code:t,isStreaming:n}=e,{t:r}=(0,ns.s)(),[i,s]=(0,u.useState)(!0),[l,a]=(0,u.useState)(!1),[o,c]=(0,u.useState)(null),[p,h]=(0,u.useState)(null),m=i&&!n,f=(0,u.useMemo)(()=>{var e;let n,r;return m&&"u">typeof DOMParser?(e=new DOMParser,r=al(n=t,e),r?.localName!=="svg"||null!==r.namespaceURI||r.hasAttribute("xmlns")||(r=al(n=t.replace(/<svg(?=[\s/>])/,`<svg xmlns="${as}"`),e)),r?.localName==="svg"&&r.namespaceURI===as?n:null):void 0},[t,m]),g=(0,u.useMemo)(()=>f?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(f)}`:null,[f]),x=(0,u.useMemo)(()=>(0,d.jsx)(l2,{isStreaming:n,previewVisible:m,onToggle:()=>s(e=>!e),title:m?r("i18n.showSvgSource"):r("i18n.previewSvg")}),[n,m,r]);if(!m)return(0,d.jsx)(ae,{code:t,lang:"svg",headerAction:x,isStreaming:n});let v=null!==g&&o!==g,b=e=>(0,d.jsx)("img",{src:g??void 0,alt:r("i18n.svgImage"),className:[e,p===g?"is-unsized":""].filter(Boolean).join(" "),onLoad:e=>{let{naturalWidth:t,naturalHeight:n}=e.currentTarget;t&&n||h(g)},onError:()=>c(g)});return(0,d.jsx)(l3,{lang:"svg",actions:(0,d.jsxs)(d.Fragment,{children:[v&&f&&(0,d.jsx)(l4,{onClick:()=>l0(f,"image.svg")}),x]}),children:void 0===f?(0,d.jsx)("div",{className:"mermaid-block mermaid-block-loading"}):v?(0,d.jsxs)(d.Fragment,{children:[!l&&(0,d.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:r("i18n.openSvgViewer"),"aria-label":r("i18n.openSvgViewer"),onClick:()=>a(!0),children:b("svg-block-image")}),l&&(0,d.jsx)(l8,{title:r("i18n.svgImage"),label:r("i18n.svgViewer"),onClose:()=>a(!1),children:b("svg-zoom-image")})]}):(0,d.jsx)("div",{className:"mermaid-block mermaid-block-error",children:r("i18n.invalidSvg")})})}let ao=(0,u.createContext)(!1);function ac(e){let{src:t,alt:n,cwd:r,...i}=e,s=(0,u.useContext)(ao);delete i.node;let l="string"==typeof t?t:void 0,a=l?su(l,r):null,o=a?`/api/files/${e1(a)}?type=read`:l,c=a??l?.split(/[?#]/,1)[0]??"",p=n?.trim()?n:void 0;if(sL(c))return(0,d.jsx)("audio",{controls:!0,preload:"metadata",src:o,"aria-label":p});if(sP(c))return(0,d.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:o,"aria-label":p});let h=(0,d.jsx)("img",{src:o,alt:n??"",loading:"lazy",...i});return!o||s?h:(0,d.jsx)(lC,{src:o,alt:n??"",className:"markdown-image",children:h})}function ad(e){let{source:t,children:n}=e,{t:r}=(0,ns.s)(),[i,s]=(0,u.useState)(!1);return(0,d.jsxs)("div",{className:"markdown-math-display",children:[n,(0,d.jsx)("button",{type:"button",onClick:()=>{s(!1),s$(t).then(()=>{s(!0),setTimeout(()=>s(!1),1500)},()=>{})},className:"markdown-code-action markdown-math-copy",children:r(i?"i18n.copied":"i18n.copy")})]})}let au=(0,u.memo)(function(e){let{markdown:t,remarkPlugins:n,urlTransform:r,rehypePlugins:i,components:s}=e;return(0,d.jsx)(sE.oz,{remarkPlugins:n,rehypePlugins:i,urlTransform:r,components:s,children:t})});function ap(e,t,n){return"mermaid"===e?(0,d.jsx)(l1,{code:t,isStreaming:n,defaultPreview:!0}):"svg"===e?(0,d.jsx)(aa,{code:t,isStreaming:n}):ly(e)?(0,d.jsx)(an,{code:t,lang:e,isStreaming:n}):(0,d.jsx)(ae,{code:t,lang:e,isStreaming:n})}let ah=(0,u.memo)(function(e){let{children:t,className:n,isStreaming:r,cwd:i,onOpenFile:s,onNavigateLink:l,keepLineBreaks:a,keepTextLayout:o}=e,c=(0,u.useMemo)(()=>s0(t),[t]),p=(0,u.useMemo)(()=>r?function(e){let t=e.split("\n");if(/^---[ \t]*\r?$/.test(t[0]))return[e];let n=[],r=[],i=null,s=!1,l=!1,a=!1;for(let o of t){let t=""===o.trim();!a||t||i||s||l||!(r.length>0)||/^[ \t]/.test(o)||lf.test(o)||(n.push(r.join("\n")+"\n"),r=[]),r.push(o);let c=o.match(lm);if(c){let e=c[1][0],t=c[1].length;i?e===i.marker&&t>=i.size&&/^[ \t]*\r?$/.test(o.slice(c[0].length))&&(i=null):i={marker:e,size:t}}else if(!i){if(lv.test(o))return[e];let t=o.replace(lx,"");lg.test(t)&&(l=!0),(t.match(/\$\$/g)?.length??0)%2==1&&(s=!s)}a=t}return n.push(r.join("\n")),n}(c):[c],[r,c]),h=(0,u.useMemo)(()=>({code(e){let{className:t,children:n,...i}=e,s=t?.replace("language-","").toLowerCase()??"",l=String(n);return t?.includes("language-")||l.includes("\n")?ap(s,l.replace(/\n$/,""),r):(0,d.jsx)("code",{className:"markdown-inline-code",...i,children:n})},pre(e){let{children:t}=e;return(0,d.jsx)(d.Fragment,{children:t})},a(e){let{href:t,children:n,...r}=e;if(delete r.node,l&&t&&!sY(t)){let e=()=>l(t);return(0,d.jsx)(ao.Provider,{value:!0,children:(0,d.jsx)("a",{...r,role:"link",tabIndex:0,onClick:e,onKeyDown:t=>{"Enter"===t.key&&e()},children:n})})}if(t?.startsWith("#"))return(0,d.jsx)(ao.Provider,{value:!0,children:(0,d.jsx)("a",{href:t,...r,onClick:sG,children:n})});let a=s?su(t,i):null;return a&&s?(0,d.jsx)(ao.Provider,{value:!0,children:(0,d.jsx)("a",{href:t,...r,onClick:e=>{if(!si(e))return;let n=e.currentTarget.getAttribute("target");n&&"_self"!==n||(e.preventDefault(),s(a,sh(t)??void 0))},children:n})}):(0,d.jsx)(ao.Provider,{value:!0,children:(0,d.jsx)("a",{href:t,...r,target:"_blank",rel:"noopener noreferrer",children:n})})},img:e=>(0,d.jsx)(ac,{cwd:i,...e}),ol(e){let{node:t,start:n,style:r,...i}=e,s=String(Math.abs((n??1)+Math.max(t?.children.filter(e=>"element"===e.type&&"li"===e.tagName).length??0,1)-1)).length;return(0,d.jsx)("ol",{start:n,style:{...r,"--ol-marker-digits":Math.max(s,2)},...i})},div(e){let{node:t,children:n,...r}=e,i=t?.properties?.dataMathSource;return"string"==typeof i?(0,d.jsx)(ad,{source:i,children:n}):(0,d.jsx)("div",{...r,children:n})},table(e){let{children:t}=e;return(0,d.jsx)("div",{className:"markdown-table-frame",children:(0,d.jsx)("div",{className:"markdown-table-wrap",children:(0,d.jsx)("table",{children:t})})})}}),[i,r,s,l]);return(0,d.jsx)("div",{className:["markdown-body",n].filter(Boolean).join(" "),children:p.map((e,t)=>{let n=r?function(e){if(e.includes("\r"))return null;let t=e.split("\n"),n=t[0].match(lb);if(!n||/[\\&]/.test(n[2]))return null;let r=n[1][0],i=n[1].length,s=-1;for(let e=1;e<t.length;e+=1){let n=t[e].match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);if(n&&n[1][0]===r&&n[1].length>=i){s=e;break}}if(-1!==s&&t.slice(s+1).some(e=>""!==e.trim()))return null;let l=n[2].toLowerCase();if("math"===l)return null;let a=-1!==s?s:t.length>1&&""===t[t.length-1]?t.length-1:t.length;return{lang:l,code:t.slice(1,a).join("\n")}}(e):null;return n?(0,d.jsx)(u.Fragment,{children:ap(n.lang,n.code,!0)},t):(0,d.jsx)(au,{markdown:e,remarkPlugins:o?ll:a?ls:s7,urlTransform:s?sJ:sZ,rehypePlugins:l?lp:lu,components:h},t)})})});function am(e){let{active:t,size:n=14}=e;return(0,d.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,d.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z",stroke:t?"#d4a017":void 0,fill:t?"rgba(250, 204, 21, 0.18)":"none",style:{filter:t?"drop-shadow(0 0 2px rgba(250, 204, 21, 0.35))":"none"}}),(0,d.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,d.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]})}let af=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,ag=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/,ax=new Map;function av(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}function ab(e,t,n){let r=t.toolCallId;if("string"!=typeof r||"string"==typeof t.parentToolCallId&&""!==t.parentToolCallId)return e;if("tool_execution_start"===t.type){if(e.has(r))return e;let i=new Map(e);return i.set(r,{startedAt:n-(av(t.elapsedMs)??0)}),i}if("tool_execution_end"===t.type){let n=av(t.durationMs);if(void 0===n)return ay(e,r);let i=new Map(e);return i.set(r,{durationMs:n}),i}return e}function ay(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function aw(e){let t=new Map([...e].filter(e=>{let[,t]=e;return"durationMs"in t}));return t.size===e.size?e:t.size?t:ax}function aj(e){let t,n=[],r=null,i=0,s=0,l=0,a=0,o=null,c=[],d=[],u=[],p=()=>({lineNo:null,text:"",type:"empty"}),h=()=>{if(!r){c=[],d=[],u=[];return}let e=Math.max(c.length,d.length);for(let t=0;t<e;t++){let e=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"removed"}:p(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:p();r.rows.push({type:"line",left:e,right:n})}for(let e of u)r.rows.push({type:"hunk",text:e});c=[],d=[],u=[]};for(let p of e.split(/\r?\n/)){if(!(l>0||a>0)){if(p.startsWith("--- ")){h(),t=aC(p.slice(4));continue}if(p.startsWith("+++ ")){h(),r={oldPath:t,newPath:aC(p.slice(4)),rows:[]},n.push(r),o=null;continue}}let e=p.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),h(),i=Number(e[1]),s=Number(e[3]),l=void 0===e[2]?1:Number(e[2]),a=void 0===e[4]?1:Number(e[4]);let t=0===l?i+1:i,c=0===a?s+1:s;if(o){let e=t-o.old,n=c-o.new;(e>0||n>0)&&r.rows.push({type:"gap",count:e===n?e:null})}o={old:t+l,new:c+a},r.rows.push({type:"hunk",text:p});continue}if(!r)continue;if(p.startsWith("\\ ")){c.length||d.length?u.push(p):r.rows.push({type:"hunk",text:p});continue}let m=p[0],f=p.slice(1);" "===m?(h(),r.rows.push({type:"line",left:{lineNo:i++,text:f,type:"context"},right:{lineNo:s++,text:f,type:"context"}}),l>0&&l--,a>0&&a--):"-"===m?(c.push({lineNo:i++,text:f}),l>0&&l--):"+"===m?(d.push({lineNo:s++,text:f}),a>0&&a--):""!==p&&(h(),r.rows.push({type:"hunk",text:p}))}h();let m=n.filter(e=>e.rows.some(e=>"line"===e.type));return m.length>0?m:null}function ak(e){let t=[];for(let n of e.rows)if("hunk"!==n.type){if("gap"===n.type){t.push(n);continue}if("context"===n.left.type&&"context"===n.right.type){t.push({type:"context",text:n.right.text,oldLineNo:n.left.lineNo,newLineNo:n.right.lineNo});continue}"empty"!==n.left.type&&t.push({type:"removed",text:n.left.text,oldLineNo:n.left.lineNo,newLineNo:null}),"empty"!==n.right.type&&t.push({type:"added",text:n.right.text,oldLineNo:null,newLineNo:n.right.lineNo})}return t}function aS(e,t){return 1===e?t("diff.unchangedLine"):t("diff.unchangedLines",{count:e})}function aC(e){return e.split(" ")[0].trim()}function aN(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.oldText&&"string"==typeof e.newText}function aE(e){if(""===e)return{lines:[],lastEnded:!1};let t=e.split(/\r\n|\r|\n/),n=t.length>1&&""===t[t.length-1];return n&&t.pop(),{lines:t,lastEnded:n}}function aM(e,t,n,r){return e.lines[t]===n.lines[r]&&(t<e.lines.length-1||e.lastEnded)===(r<n.lines.length-1||n.lastEnded)}function a$(e){if(e.length<=4e3)return e;let t=4e3,n=e.charCodeAt(t-1);return n>=55296&&n<=56319&&t--,`${e.slice(0,t)}…`}let aI=()=>({lineNo:null,text:"",type:"empty"}),aT=new Set,aR="pi-thinking-expanded",aA="pi-thinking-expanded-changed";function aL(){try{return"true"===window.localStorage.getItem(aR)}catch{return!1}}function aP(e){let{files:t,onOpenFile:n}=e,{t:r}=(0,ns.s)();return 0===t.length?null:(0,d.jsx)("div",{"aria-label":r("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:t.map(e=>{let{filePath:t}=e,i=e2(t);return(0,d.jsxs)("button",{type:"button",title:t,"aria-label":r("chat.openWrittenFile",{name:i}),onClick:()=>n?.(t),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[rm(i,12),(0,d.jsx)("span",{children:i})]},t)})})}let az="codemode",aO=new Set(["running","ok","error","cancelled"]);function aW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aF(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function aD(e){if(!aW(e)||!Array.isArray(e.calls))return{calls:[],omitted:0};let t=e.calls.flatMap(e=>{let t=function(e){if(!aW(e)||"string"!=typeof e.name)return null;let t="string"==typeof e.status&&aO.has(e.status)?e.status:"ok",n=aF(e.durationMs),r=aF(e.cost);return{id:"string"==typeof e.id?e.id:"",name:e.name,args:"string"==typeof e.args?e.args:"",status:t,...void 0!==n?{durationMs:n}:{},..."string"==typeof e.error&&e.error?{error:e.error}:{},...void 0!==r&&r>0?{cost:r}:{}}}(e);return t?[t]:[]}),n=aF(e.omittedCalls);return{calls:t,omitted:void 0!==n&&n>0?Math.floor(n):0}}let a_=/^Script (completed|failed)\nWall time ([\d.]+) seconds\nOutput:\n$/;function aB(e){return`$${e>=.01?e.toFixed(2):e.toPrecision(2)}`}let aH={running:{icon:"…",color:"#d97706"},ok:{icon:"✓",color:"#16a34a"},error:{icon:"✗",color:"#f87171"},cancelled:{icon:"⊘",color:"var(--text-dim)"}};function aU(e){var t;let{call:n}=e,{t:r}=(0,ns.s)(),i=aH[n.status],s=void 0===(t=n.durationMs)?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`;return(0,d.jsxs)("li",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6,minWidth:0},children:[(0,d.jsx)("span",{role:"img","aria-label":r(`codemode.status.${n.status}`),title:r(`codemode.status.${n.status}`),style:{color:i.color,width:12,flexShrink:0,textAlign:"center"},children:i.icon}),(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontWeight:600,flexShrink:0},children:n.name}),n.args&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n.args}),s&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,marginLeft:"auto",fontVariantNumeric:"tabular-nums"},children:s}),void 0!==n.cost&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:aB(n.cost)})]}),n.error&&(0,d.jsx)("div",{style:{color:"#f87171",paddingLeft:18,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.error})]})}function aK(e){let t,{calls:n,omitted:r,isError:i}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(!1);if(0===n.length&&0===r)return null;let o=l?0:Math.max(0,n.length-20),c=o>0?n.slice(o):n,p=(t=n.filter(e=>void 0!==e.cost)).length>1?t.reduce((e,t)=>e+(t.cost??0),0):null;return(0,d.jsxs)("div",{style:{borderTop:i?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",background:"var(--bg-subtle)",padding:"6px 10px",fontFamily:"var(--font-mono)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"inherit",fontSize:11},children:s("codemode.calls")}),r>0&&(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:s("codemode.omittedCalls",{count:r})}),o>0&&(0,d.jsx)("button",{type:"button",onClick:()=>a(!0),style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",color:"var(--accent)",cursor:"pointer",font:"inherit"},children:s("codemode.showEarlierCalls",{count:o})}),(0,d.jsx)("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:3,minWidth:0},children:c.map((e,t)=>(0,d.jsx)(aU,{call:e},e.id||`${o+t}`))}),null!==p&&(0,d.jsx)("div",{style:{color:"var(--text-dim)"},children:s("codemode.modelCost",{cost:aB(p)})})]})}function aq(e){return"string"==typeof e?e.trim()?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function aV(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:", ";if(!Array.isArray(e))return aq(e);if(0===e.length||!e.every(e=>null===e||"object"!=typeof e))return null;let n=e.map(aq).filter(e=>null!==e);return n.length>0?n.join(t):null}var aZ=n(9701);let aJ=new Map;function aY(e){return"number"!=typeof e.timestamp?null:`${e.provider??""}/${e.model??""}@${e.timestamp}`}let aG="transcriptNotices";function aX(e){if("object"!=typeof e||null===e)return[];let t=e[aG];return Array.isArray(t)?t:[]}function aQ(e){return e<1e3?e.toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${Math.round(e/1e3)}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${Math.round(e/1e6)}M`}let a0="#d97706";function a1(e,t){let n=t>=.01?`$${t.toFixed(2)}`:void 0;return n?e("transcriptNotice.costSuffix",{cost:n}):""}function a2(e,t){switch(t.kind){case"cache_miss":{let n={tokens:aQ(t.missedTokens),cost:a1(e,t.missedCost)};if(t.modelChanged)return e("transcriptNotice.cacheMissModelSwitch",n);if(void 0!==t.idleMinutes)return e("transcriptNotice.cacheMissIdle",{...n,minutes:t.idleMinutes});return e("transcriptNotice.cacheMiss",n)}case"cache_warm":var n;return e("transcriptNotice.cacheWarmed",{note:t.note?e("transcriptNotice.cacheWarmedNote",{note:t.note}):"",cost:(n=t.cost,`$${n.toFixed(6).replace(/(\.\d{3}\d*?)0+$/,"$1")}`)});case"summary_cost":return e("compaction"===t.source?"transcriptNotice.compactionCost":"transcriptNotice.branchSummaryCost",{tokens:aQ(t.tokens),cost:a1(e,t.cost)});case"reasoning_dropped":{let n="openai"===t.provider?"reasoningItemsDropped":"thinkingDropped";return e(`transcriptNotice.${n}${1===t.count?"One":""}`,{count:t.count,reasons:t.reasons?.length?e("transcriptNotice.droppedReasons",{reasons:t.reasons.join(", ")}):""})}}}let a4=(0,u.memo)(function(e){let{notices:t}=e,{t:n}=(0,ns.s)(),r=t.filter(e=>"summary_cost"!==e.kind||"compaction"!==e.source);return 0===r.length?null:(0,d.jsx)("div",{className:"transcript-notices",style:{display:"flex",flexDirection:"column",gap:2,margin:"-6px 0 12px"},children:r.map((e,t)=>{let r="cache_warm"!==e.kind;return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:12,lineHeight:1.5,color:r?a0:"var(--text-dim)",overflowWrap:"anywhere"},children:[r&&(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:3},children:[(0,d.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,d.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,d.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,d.jsx)("span",{children:a2(n,e)})]},t)})})}),a3=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function a8(e){let t=0,n=0;for(let r of e)a3.test(r)?t++:n++;return t+n/4}let a6=new Map;function a5(e){let{children:t,className:n,...r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)(!1);if(t.length<=1e5)return(0,d.jsx)(ah,{className:n,...r,children:t});if(!s){var a;return(0,d.jsxs)("button",{onClick:()=>l(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",i("i18n.largeMessageReveal",{size:(a=t.length)>=1e6?`${(a/1e6).toFixed(1)} MB`:a>=1e3?`${Math.round(a/1e3)} KB`:`${a} B`})]})}return(0,d.jsx)("div",{className:n,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,d.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:t})})}function a9(e,t,n){let r=e.toLowerCase(),i=t.toLowerCase(),s=Object.entries(n??{}).flatMap(e=>{let[t,n]=e,i=t.indexOf(":");return i>0&&t.slice(0,i).toLowerCase()===r?[{id:t.slice(i+1).toLowerCase(),name:n}]:[]});return s.find(e=>e.id===i)?.name??s.find(e=>i.endsWith(`/${e.id}`))?.name??Object.entries(n??{}).find(e=>{let[t]=e;return t.toLowerCase()===i})?.[1]??`${e}/${t}`}function a7(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}function oe(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}let ot=(0,u.memo)(function(e){let{message:t,isStreaming:n,toolResults:r,toolClocks:i,modelNames:s,cwd:l,onOpenFile:a,onOpenSubagent:o,entryId:c,searchBlock:u,onFork:p,forkEntryId:h,forking:m,onEditContent:f,onCancelEdit:g,isEditing:x,hideAssistantHeader:v,showTimestamp:b,prevTimestamp:y,sessionId:w,writtenFiles:j,turnDurationMs:k,onCompact:S,isCompacting:C,compactError:N}=e;return"user"===t.role?(0,d.jsx)(on,{message:t,cwd:l,onOpenFile:a,entryId:c,onFork:p,forkEntryId:c??h,forking:m,onEditContent:f,onCancelEdit:g,isEditing:x}):"assistant"===t.role?(0,d.jsx)(os,{message:t,isStreaming:n,toolResults:r,toolClocks:i,modelNames:s,cwd:l,onOpenFile:a,onOpenSubagent:o,hideAssistantHeader:v,showTimestamp:b,prevTimestamp:y,sessionId:w,entryId:c,searchBlock:u,writtenFiles:j,turnDurationMs:k,onCompact:S,isCompacting:C,compactError:N}):"toolResult"===t.role?null:"custom"===t.role?"compaction"===t.customType?(0,d.jsx)(oM,{message:t}):(0,d.jsx)(oR,{message:t,cwd:l,onOpenFile:a}):"bashExecution"===t.role?(0,d.jsx)(oU,{message:t,sessionId:w}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&oe(e.message,e.toolResults,t.toolResults)&&oe(e.message,e.toolClocks,t.toolClocks)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSubagent===t.onOpenSubagent&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forkEntryId===t.forkEntryId&&e.forking===t.forking&&e.onEditContent===t.onEditContent&&e.onCancelEdit===t.onCancelEdit&&e.isEditing===t.isEditing&&e.hideAssistantHeader===t.hideAssistantHeader&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.writtenFiles===t.writtenFiles&&e.turnDurationMs===t.turnDurationMs&&e.sessionId===t.sessionId&&e.onCompact===t.onCompact&&e.isCompacting===t.isCompacting&&e.compactError===t.compactError);function on(e){let{message:t,cwd:n,onOpenFile:r,entryId:i,onFork:s,forkEntryId:l,forking:a,onEditContent:o,onCancelEdit:c,isEditing:p}=e,{t:h}=(0,ns.s)(),[m,f]=(0,u.useState)(!1),[g,x]=(0,u.useState)(!1),[v,b]=(0,u.useState)(!1),y=("string"==typeof t.content?t.content:t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")).replace(/\r\n?/g,"\n"),w="string"==typeof t.content?[]:t.content.filter(e=>"image"===e.type),j=e5(y),k=j?.search(/\s/)??-1,S=j?-1===k?j:j.slice(0,k):"",C=j&&-1!==k?j.slice(k+1):"",N=a7(t.timestamp),E=!!l&&!!s,M=j??y,$=j?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(t,j):t,I=w.length>0&&(0,d.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!y},children:w.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,d.jsx)(lC,{src:n,children:(0,d.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:8,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t)})}),T=!!i&&!!o,R=!!p&&!!c;return(0,d.jsxs)("div",{className:"user-message",style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[(0,d.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,d.jsx)("div",{className:"user-message-bubble","data-editing":p||void 0,style:{flex:1,minWidth:0,background:p?"color-mix(in srgb, var(--accent) 14%, var(--user-bg))":"var(--user-bg)",border:p?"1px solid color-mix(in srgb, var(--accent) 62%, var(--user-bg))":"1px solid var(--border)",boxShadow:p?"0 0 0 2px color-mix(in srgb, var(--accent) 16%, transparent)":void 0,borderRadius:12,padding:"8px 12px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:j?(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[I,(0,d.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,d.jsxs)("button",{onClick:()=>b(e=>!e),title:h(v?"i18n.collapse":"i18n.expand"),"aria-expanded":v,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:v?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),C&&(0,d.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:C})]}),v&&(0,d.jsx)(ah,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:r,children:function(e){let t=e.match(e6);if(!t)return null;let n=t[4],r=void 0===n?9:11+n.length;return e.slice(e.indexOf("\n")+1,e.length-r)}(y)??y})]}):(0,d.jsxs)(d.Fragment,{children:[I,y&&(0,d.jsx)(a5,{className:"markdown-user-message",keepLineBreaks:!0,cwd:n,onOpenFile:r,children:y})]})})}),(0,d.jsxs)("div",{className:"user-message-actions-row",style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,d.jsx)("div",{className:"message-hover-actions","data-visible":m,style:{display:"flex",gap:3},children:(0,d.jsxs)("button",{onClick:()=>{x(!1),s$(M).then(()=>{x(!0),setTimeout(()=>x(!1),1500)},()=>{})},title:h("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:g?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{g||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{g||(e.currentTarget.style.color="var(--text-dim)")},children:[g?(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,d.jsx)("span",{className:"message-action-label",children:h(g?"i18n.copied":"i18n.copy")})]})}),(E||T||R)&&(0,d.jsxs)("div",{className:"message-hover-actions","data-visible":m||a||R,style:{display:"flex",gap:3},children:[T&&!R&&(0,d.jsxs)("button",{onClick:()=>o($,i),title:h("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,d.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),(0,d.jsx)("span",{className:"message-action-label",children:h("i18n.editFromHere")})]}),R&&(0,d.jsxs)("button",{type:"button",onClick:c,title:h("i18n.cancel"),"aria-label":h("i18n.cancel"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:500,whiteSpace:"nowrap"},children:[(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})}),(0,d.jsx)("span",{className:"message-action-label",children:h("i18n.cancel")})]}),E&&(0,d.jsxs)("button",{onClick:()=>{s(l,$)},disabled:a,title:h(a?"i18n.creatingSession":"i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-dim)",cursor:a?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{a||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,d.jsx)("span",{className:"message-action-label",children:h(a?"i18n.creating":"i18n.newSession")})]})]}),N&&(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:N})]})]})}function or(e){let{modelName:t,estimatedTokens:n=0,tps:r=null}=e,{t:i}=(0,ns.s)(),s=null!==r?r>=50?"#53b3cb":r>=30?"#9bc53d":r>=15?"#f9c22e":"#e01a4f":void 0;return(0,d.jsxs)("div",{style:{fontSize:11,lineHeight:1.5,minHeight:"calc(1.5em + 2px)",color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6,fontVariantNumeric:"tabular-nums"},children:[t&&(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n>0&&(0,d.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0,whiteSpace:"nowrap",color:"var(--text)"},title:i("i18n.estimatedTokens"),children:[(0,d.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,d.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,d.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),(0,d.jsx)("span",{children:n})]}),null!==r&&(0,d.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",minWidth:"calc(8ch + 1px)",boxSizing:"content-box",textAlign:"center",borderRadius:4,background:s,color:"#fff",fontSize:11,fontWeight:400},children:[r.toFixed(1)," t/s"]})]})]})}function oi(e){let{message:t,modelNames:n,children:r}=e,{t:i}=(0,ns.s)();return(0,d.jsxs)("div",{className:"assistant-reply-group",style:r7(`${t.provider??""}/${t.model??""}`),children:[(0,d.jsx)(or,{modelName:t.provider?a9(t.provider,t.model,n):i("session.assistant")}),r]})}function os(e){var t,n,r;let i,{message:s,isStreaming:l,toolResults:a,toolClocks:o,modelNames:c,cwd:p,onOpenFile:h,onOpenSubagent:m,hideAssistantHeader:f,showTimestamp:g,prevTimestamp:x,sessionId:v,entryId:b,searchBlock:y,writtenFiles:w,turnDurationMs:j,onCompact:k,isCompacting:S,compactError:C}=e,{t:N}=(0,ns.s)(),E=g?a7(s.timestamp):null,M=(0,u.useMemo)(()=>r7(`${s.provider??""}/${s.model??""}`),[s.provider,s.model]),$=(0,u.useMemo)(()=>(s.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(e=>{let{block:t}=e;return!i6(t,{isStreaming:l})}),[s.content,l]),I=(0,u.useMemo)(()=>$.map(e=>{let{block:t}=e;return t}),[$]),T=i9(s,{isStreaming:l}),R=i7(s,{isStreaming:l}),A=se(s,{isStreaming:l}),L=A&&!st(s),[P,z]=(0,u.useState)(!1),[O,W]=(0,u.useState)(!1),F=(0,u.useRef)(null),D=aY(s),_=(0,u.useRef)(D);_.current=D;let[B,H]=(0,u.useState)(null),U=(0,u.useRef)($);U.current=$;let K=(0,u.useRef)(new Map),q=(0,u.useMemo)(()=>{if(!l)return K.current=new Map,0;let e=new Map,t=0;for(let{block:n,originalIndex:r}of $){let i="text"===n.type?n.text:"thinking"===n.type?n.thinking:"toolCall"===n.type?n.rawInput??JSON.stringify(n.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return a8(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=.25,s--),i+a8(t.slice(s))}(K.current.get(r),i);e.set(r,{text:i,tokens:s}),t+=s}return K.current=e,t},[$,l]),V=(0,u.useRef)(q);V.current=q;let Z=(0,u.useRef)(new Map),[J,Y]=(0,u.useState)(new Map),G="assistant"===s.role?od(s.durationMs):void 0,X=(0,u.useMemo)(()=>{let e=G??(s.timestamp&&x?s.timestamp-x:void 0);if(void 0===e)return;let t=Math.round(e/1e3);return t>0?t:void 0},[G,s.timestamp,x]),Q=(0,u.useMemo)(()=>{let e=new Map;if(!a)return e;for(let[t,n]of a){let r=od(n.durationMs)??(n.timestamp&&s.timestamp?n.timestamp-s.timestamp:void 0);void 0!==r&&r>=ou&&e.set(t,r)}return e},[a,s.timestamp]),ee=I.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),et=s.usage?(t=s.usage,i=[],t.input&&i.push({icon:"up",before:"↑",text:aQ(t.input)}),t.output&&i.push({icon:"down",before:"↓",text:aQ(t.output)}),t.cacheRead&&i.push({text:`R${aQ(t.cacheRead)}`}),t.cacheWrite&&i.push({text:`W${aQ(t.cacheWrite)}`}),t.cost?.total&&i.push({text:`$${t.cost.total.toFixed(4)}`}),i):[];if(R&&et.unshift({text:N("chat.operationAborted")},...et.length>0?[{text:"\xb7"}]:[]),void 0!==j){let e;et.length>0&&et.push({text:"\xb7"});let t=sN(j);et.push((n=N("chat.turnDuration",{time:t}),r=t,(e=n.indexOf(r))<0?{text:n}:{icon:"clock",before:n.slice(0,e),text:r,after:n.slice(e+r.length)}))}return((0,u.useEffect)(()=>{if(!l){let e=new Date().getTime();Y(t=>{let n=new Map(t);for(let[t,r]of Z.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),F.current=null,H(null);return}let e=setInterval(()=>{var e;let t,n=U.current,r=Date.now();n.forEach(e=>{let{originalIndex:t}=e;Z.current.has(t)||Z.current.set(t,r)}),Y(e=>{let t=!1,i=new Map(e);for(let e=0;e<n.length-1;e++){let s=n[e].originalIndex,l=n[e+1].originalIndex;if(!i.has(s)&&Z.current.has(s)){let e=Z.current.get(s),n=Z.current.get(l)??r;i.set(s,Math.round((n-e)/1e3)),t=!0}}return t?i:e});let i=V.current;if(0===i)return;F.current??=function(e,t,n){let r=null===e?void 0:aJ.get(e);if(r)return r;let i={at:n,tokens:t};return null!==e&&(aJ.set(e,i),aJ.size>32&&aJ.delete(aJ.keys().next().value)),i}(_.current,i,r);let s=(e=F.current,(t=(r-e.at)/1e3)>.5?(i-e.tokens)/t:null);null!==s&&H(s)},300);return()=>clearInterval(e)},[l]),0!==I.length||l||T||A||R)?(0,d.jsxs)("div",{"data-message-role":"assistant","data-entry-id":b,style:{marginBottom:16,...M},onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),children:[!f&&(0,d.jsx)(or,{modelName:s.provider?a9(s.provider,s.model,c):void 0,estimatedTokens:l?Math.round(q):0,tps:l?B:null}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:$.map(e=>{let{block:t,originalIndex:n}=e;return(0,d.jsx)(ol,{block:t,searchTarget:t===y,toolResults:a,toolsNotRun:R||null!==T,isStreaming:l,streamingDuration:J.get(n)??("thinking"===t.type?X:void 0),toolCallDurations:Q,toolClocks:o,cwd:p,onOpenFile:h,onOpenSubagent:m,sessionId:v,entryId:b,blockIndex:n},n)})}),T&&(0,d.jsxs)("div",{role:"alert",style:{marginTop:8*(I.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",T]}),A&&(0,d.jsxs)("div",{role:"alert",style:{marginTop:I.length>0||T?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[N(L?"chat.truncatedWithoutAnswer":"chat.truncatedByOutputLimit"),L&&k&&(0,d.jsx)("button",{type:"button",onClick:k,disabled:S,style:{display:"block",marginTop:8,padding:"3px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:S?"default":"pointer",font:"inherit"},children:N(S?"chat.compacting":"chat.compactContext")}),L&&C&&(0,d.jsx)("div",{style:{marginTop:8,color:"#ef4444",whiteSpace:"pre-wrap"},children:C})]}),w&&w.length>0&&(0,d.jsx)(aP,{files:w,onOpenFile:h}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[et.length>0&&!l&&(0,d.jsx)("div",{style:{display:"flex",flexWrap:"wrap",columnGap:7,fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:et.map((e,t)=>(0,d.jsxs)(u.Fragment,{children:[t>0&&" ",(0,d.jsx)(oH,{part:e})]},t))}),ee&&!l&&(0,d.jsxs)("button",{onClick:()=>{W(!1),s$(iK(ee)).then(()=>{W(!0),setTimeout(()=>W(!1),1500)},()=>{})},className:"message-hover-actions","data-visible":P,title:N("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:O?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap"},onMouseEnter:e=>{O||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{O||(e.currentTarget.style.color="var(--text-dim)")},children:[O?(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,d.jsx)("span",{className:"message-action-label",children:N(O?"i18n.copied":"i18n.copy")})]}),E&&!l&&(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto",whiteSpace:"nowrap"},children:E})]})]}):null}function ol(e){let{block:t,searchTarget:n,toolResults:r,toolsNotRun:i,isStreaming:s,streamingDuration:l,toolCallDurations:a,toolClocks:o,cwd:c,onOpenFile:u,onOpenSubagent:p,sessionId:h,entryId:m,blockIndex:f}=e;if("text"===t.type)return(0,d.jsx)("div",{"data-message-text":!0,"data-search-target":n||void 0,children:(0,d.jsx)(oa,{block:t,isStreaming:s,cwd:c,onOpenFile:u})});if("thinking"===t.type)return(0,d.jsx)(oc,{block:t,duration:l,sessionId:h,entryId:m,blockIndex:f});if("toolCall"===t.type){let e=r?.get(t.toolCallId),n=a?.get(t.toolCallId);return(0,d.jsx)(om,{block:t,result:e,notRun:i,duration:n,clock:o?.get(t.toolCallId),onOpenSubagent:p})}return null}function oa(e){let{block:t,isStreaming:n,cwd:r,onOpenFile:i}=e;return(0,d.jsx)(a5,{isStreaming:n,cwd:r,onOpenFile:i,children:iK(t.text)})}function oo(e){let{text:t}=e,n=(0,u.useMemo)(()=>iK(t),[t]),r=(0,u.useMemo)(()=>(function(e){let t=[],n=0;for(;e.length-n>8e3;){let r=n+8e3,i=r+8e3,s=e.slice(r,i+1),l=s.indexOf("\n");for(;l>=0&&/\n\r?$/.test(e.slice(r+l-2,r+l));)l=s.indexOf("\n",l+1);if(l>=0){let i=r+l;if(i===e.length-1)break;t.push({text:e.slice(n,i),lineBreak:!0}),n=i+1}else if(e.length>i){let r=e.charCodeAt(i-1),s=r>=55296&&r<=56319?i-1:i;t.push({text:e.slice(n,s),lineBreak:!1}),n=s}else break}return t.push({text:e.slice(n),lineBreak:!1}),t})(n),[n]);return 1===r.length?n:r.map((e,t)=>(0,d.jsx)("div",{children:e.text},t))}function oc(e){let t,{block:n,duration:r,sessionId:i,entryId:s,blockIndex:l}=e,{t:a}=(0,ns.s)(),[o,c]=(0,u.useState)(aL),[p,h]=(0,u.useState)(null),[m,f]=(0,u.useState)(!1),[g,x]=(0,u.useState)(null),v=`${i}:${s}:${l}`,[b,y]=(0,u.useState)(v);b!==v&&(y(v),h(null),f(!1),x(null));let w=(0,u.useRef)(a);w.current=a;let j=(t=iK(n.thinking.trimStart().slice(0,4e3)).trimStart(),t.match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,u.useEffect)(()=>{let e=()=>c(aL());return window.addEventListener(aA,e),()=>window.removeEventListener(aA,e)},[]),(0,u.useEffect)(()=>{if(!o||!n.deferred||null!==p)return;if(!i||!s)return void x(w.current("i18n.thinkingUnavailable"));let e=!1;return f(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=a6.get(r);if(i)return a6.delete(r),a6.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw a6.delete(r),e});if(a6.set(r,s),a6.size>100){let e=a6.keys().next().value;e&&a6.delete(e)}return s})(i,s,l).then(t=>{e||(h(t),f(!1))}).catch(t=>{e||(x(t instanceof Error?t.message:String(t)),f(!1))}),()=>{e=!0}},[o,n.deferred,p,i,s,l]),(0,d.jsxs)("div",{className:"thinking-step",style:{border:"1px solid var(--border)",background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:[(0,d.jsxs)("button",{type:"button","aria-expanded":o,"aria-label":`${a("i18n.thinking")}${j?`: ${j}`:""}`,title:a("i18n.thinking"),className:"thinking-step-toggle",onClick:()=>c(e=>!e),style:{padding:0,background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,d.jsx)(am,{active:o}),(0,d.jsxs)("svg",{className:"thinking-pixel-icon",width:"36",height:"24",viewBox:"0 0 24 24",shapeRendering:"crispEdges","aria-hidden":"true",children:[(0,d.jsx)("path",{fill:"#453627",d:"M2 0h20v2h2v20h-2v2H2v-2H0V2h2z"}),(0,d.jsx)("path",{fill:"#d39c50",d:"M2 1h20v1h1v20h-1v1H2v-1H1V2h1z"}),(0,d.jsx)("path",{fill:"#f7e5b5",d:"M2 2h20v19H2z"}),(0,d.jsx)("path",{fill:"#c08337",d:"M11 3h2v2h-2zM4 6h2v2H4zm14 0h2v2h-2zM3 11h2v1H3zm16 0h2v1h-2z"}),(0,d.jsx)("path",{fill:"#453627",d:"M9 6h6v1h2v2h1v4h-1v2h-2v4H9v-4H7v-2H6V9h1V7h2zm1 14h4v2h-4z"}),(0,d.jsx)("path",{fill:"#ffc649",d:"M9 7h6v1h1v1h1v4h-1v1h-2v2h-4v-2H8v-1H7V9h1V8h1z"}),(0,d.jsx)("path",{fill:"#fff6d6",d:"M9 9h3v1h-2v2H9z"}),(0,d.jsx)("path",{fill:"#d6964b",d:"M10 17h4v1h-4z"})]}),!o&&(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j?(0,d.jsx)(sE.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:j}):"..."})]}),o&&(0,d.jsx)("div",{className:"thinking-step-text",style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:m?a("i18n.loadingThinking"):g??(0,d.jsx)(oo,{text:(n.deferred?p:n.thinking)??""})}),void 0!==r&&(0,d.jsxs)("span",{className:"thinking-step-time",style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[r,"s"]})]})}function od(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0}let ou=100;function op(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t),r=Math.floor(n/60),i=n%60;return r<60?`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m ${i}s`}function oh(e){let{clock:t}=e,n="startedAt"in t,[r,i]=(0,u.useState)(()=>performance.now());(0,u.useEffect)(()=>{if(!n)return;let e=window.setInterval(()=>i(performance.now()),1e3);return()=>window.clearInterval(e)},[n]);let s="durationMs"in t?t.durationMs:Math.max(0,r-t.startedAt);return s<ou?null:(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:op(s)})}function om(e){var t,n,r;let i,{block:s,result:l,notRun:a,duration:o,clock:c,onOpenSubagent:p,resultFooter:h}=e,{t:m}=(0,ns.s)(),[f,g]=(0,u.useState)(()=>{var e;return void 0!==(e=s.toolCallId)&&aT.has(e)}),x=function(e){if(void 0!==e.rawInput||!sm(e.toolName))return null;let{content:t}=e.input;return"string"!=typeof t||""===t?null:Object.keys(e.input).every(e=>oz.has(e))?t:null}(s),v=x??(n=s).rawInput??JSON.stringify(n.input,null,2),b=void 0!==s.rawInput,y=sf(s.toolName),w=l&&!l.isError?function(e){let t=e.details;if(!oC(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(l):null,j=w?.text,k=(0,u.useMemo)(()=>(function(e){if(!e)return null;let t=aj(e);return t?.length===1&&oy(t[0])||null})(j),[j]),S=function(e,t){if(!sg(e.toolName))return null;let n=sw(sx(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(oC(r)){let e=sj(r.preview);if(e)return e}return null}(s,l),C=!f||!y||b||l||a?null:s.input,N=(0,u.useMemo)(()=>{let e=null===C?null:function(e){let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.edits;if("string"==typeof t)try{let e=JSON.parse(t);t=aN(e)?[e]:e}catch{}else aN(t)&&(t=[t]);let n=Array.isArray(t)?[...t]:[];return("string"==typeof e.oldText&&"string"==typeof e.newText&&n.push({oldText:e.oldText,newText:e.newText}),0!==n.length&&n.every(aN))?n:null}(e);if(!t)return null;let n="string"==typeof e.path?e.path:"string"==typeof e.file_path?e.file_path:void 0,r=[],i=0,s=!1,l=e=>{let t=r[r.length-1];t?.type==="gap"?t.count=null===t.count||null===e?null:t.count+e:r.push({type:"gap",count:e})},a=(e,t)=>i>=1e3?(s||l(null),s=!0,!1):(r.push({type:"line",left:e,right:t}),i++,!0),o=e=>{let t={lineNo:null,text:a$(e),type:"context"};return a(t,{...t})};for(let[e,n]of t.entries()){if(s)break;e>0&&l(null);let t=aE(n.oldText),r=aE(n.newText),i=t.lines,c=r.lines,d=0;for(;d<i.length&&d<c.length&&aM(t,d,r,d);)d++;let u=i.length,p=c.length;for(;u>d&&p>d&&aM(t,u-1,r,p-1);)u--,p--;let h=Math.max(0,d-4);h>0&&l(h);for(let e=h;e<d&&o(i[e]);e++);let m=Math.max(u-d,p-d);for(let e=0;e<m;e++){let t=d+e<u?i[d+e]:null,n=d+e<p?c[d+e]:null;if(!a(null===t?aI():{lineNo:null,text:a$(t),type:"removed"},null===n?aI():{lineNo:null,text:a$(n),type:"added"}))break}let f=i.length-u,g=Math.min(f,4);for(let e=0;e<g&&o(i[u+e]);e++);!s&&f>g&&l(f-g)}return r.some(e=>"line"===e.type)?{oldPath:n,newPath:n,rows:r}:null}(C);return e?[e]:null},[C]),E=sg(s.toolName)?0===(i=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(sx((r=s).input,r.rawInput))).length?null:i.join(", ").slice(0,120):null,M=s.toolName!==az||b?null:aW(t=s.input)&&"string"==typeof t.code?t.code:null,$=null===M?null:{code:M,...aD(l?.details)},I=null!==$&&void 0!==l&&0===l.content.length,T=function(e,t){if(!e.startsWith("mcp__")||!("object"==typeof t&&null!==t&&!Array.isArray(t)))return null;let{server:n,tool:r}=t;return"string"==typeof n&&"string"==typeof r&&n&&r?{server:n,tool:r}:null}(s.toolName,l?.details),R=l?$?function(e){let[t,...n]=e;return t?.type==="text"&&"string"==typeof t.text&&a_.test(t.text)?n:[...e]}(l.content):l.content:[],A=l?R.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,L=T&&null!==A?function(e){let t=e.trim();if(t.length>2e5||!/^[[{]/.test(t))return e;try{let n=!1,r=JSON.parse(t,(e,t)=>("number"==typeof t&&(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))&&(n=!0),t));return n?e:JSON.stringify(r,null,2)}catch{return e}}(A):A,P=oL(R),z=null!==L&&("(no output)"===L.trim()||""===L.trim()),O=(l?.isError??!1)||sg(s.toolName)&&sb(l?.details),W=sr(l?.details)?l.details:null,F="Agent"===s.toolName&&"string"==typeof W?.description?W.description.trim():"",D=F||(E??($?function(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(e&&!e.startsWith("// @options:"))return e}return""}($.code):function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2?arguments[2]:void 0;if(!e||"object"!=typeof e||Array.isArray(e))return"";let r=e=>{if(e.length<=120)return e;let t=e.charCodeAt(119);return e.slice(0,t>=55296&&t<=56319?119:120)};if("grep"===n||"find"===n){let t=aV(e.pattern);if(null!==t)return r(t)}for(let t of["command","path","file_path"]){let n=aV(e[t],"command"===t?" ":", ");if(null!==n)return r(n)}if(t)return r(t);for(let t of["pattern","query"]){let n=aV(e[t]);if(null!==n)return r(n)}let i=Object.values(e);for(let e of i){let t=aV(e);if(null!==t)return r(t)}for(let e of i){let t=function e(t){if(Array.isArray(t)){let n=t.map(t=>aq(t)??e(t)).filter(e=>null!==e);return n.length>0?n.join(", "):null}if(t&&"object"==typeof t)for(let n of Object.values(t)){let t=aV(n)??e(n);if(null!==t)return t}return null}(e);if(null!==t)return r(t)}return""}(s.input,k,s.toolName))),_=$?$.calls.length+$.omitted:0;return(0,d.jsxs)("div",{style:{borderRadius:9,overflow:"hidden",fontSize:12,border:O?"1px solid rgba(248,113,113,0.45)":"1px solid var(--border)",background:O?"rgba(248,113,113,0.05)":"var(--bg-subtle)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[W&&p&&(0,d.jsx)("button",{type:"button",className:"tool-call-subagent-open",onClick:()=>p(W.sessionId,W.description||W.profile),title:m("subagent.openTab"),"aria-label":m("subagent.openTab"),style:ie(W.sessionId),children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,d.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,d.jsxs)("button",{type:"button",className:"tool-call-toggle","aria-expanded":f,onClick:()=>{var e;let t=!f;e=s.toolCallId,e&&(t?aT.add(e):aT.delete(e)),g(t)},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,paddingBlock:"var(--tool-call-block-padding, 6px)",paddingInline:"var(--tool-call-start-padding, 10px) 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[("bash"===s.toolName||"bash (local)"===s.toolName)&&(0,d.jsxs)("svg",{className:"tool-call-bash-icon",width:"36",height:"22",viewBox:"0 0 16 16",shapeRendering:"crispEdges","aria-hidden":"true",children:[(0,d.jsx)("path",{fill:"#262d28",d:"M1 1h14v1h1v12h-1v1H1v-1H0V2h1z"}),(0,d.jsx)("path",{fill:"#9ca892",d:"M1 2h14v12H1z"}),(0,d.jsx)("path",{fill:"#26352e",d:"M2 5h12v8H2z"}),(0,d.jsx)("path",{fill:"#e6f0d0",d:"M2 3h2v1H2zm3 0h1v1H5z"}),(0,d.jsx)("path",{fill:"#b4e378",d:"M3 6h1v1h1v1h1v1H5v1H4v1H3V9h1V8H3zm4 4h4v1H7z"})]}),(0,d.jsx)("span",{title:T?s.toolName:void 0,style:{color:O?"#f87171":"color-mix(in srgb, #16a34a 72%, var(--text))",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:T?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{fontWeight:500,opacity:.75},children:[T.server,"/"]}),T.tool]}):s.toolName}),(0,d.jsx)("span",{title:F||void 0,style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:b?m("chat.generatingToolInput"):D}),_>0&&(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:1===_?m("codemode.callCountOne"):m("codemode.callCount",{count:_})}),void 0!==o?(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:op(o)}):c&&(0,d.jsx)(oh,{clock:c},"startedAt"in c?c.startedAt:"ended"),(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:f?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})]}),(0,d.jsx)(rf,{open:f,children:()=>{let e=null===x&&null===$&&null===S?function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let t=Object.entries(e);if(0===t.length)return null;let n=[];for(let[e,r]of t){if(null!==r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)return null;let t=null===r?"null":String(r);n.push({key:e,value:""===t?"(empty)":t,multiline:t.includes("\n")})}return n}(b?(0,aZ.o2)(s.rawInput):s.input):null;return(0,d.jsxs)(d.Fragment,{children:[(b||!y||!l&&!a&&!N)&&!S&&(e?(0,d.jsx)("div",{style:{padding:"6px 10px 8px",background:"var(--bg-subtle)",borderTop:O?"1px solid rgba(248,113,113,0.25)":"1px solid var(--border)"},children:(0,d.jsx)(oD,{fields:e})}):(0,d.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg-subtle)",borderTop:O?"1px solid rgba(248,113,113,0.25)":"1px solid var(--border)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:$?$.code.replace(/\r/g,"").trimEnd():v})),$&&(0,d.jsx)(aK,{calls:$.calls,omitted:$.omitted,isError:O})]})}}),P.length>0&&(0,d.jsx)(oN,{images:P,isError:O}),(0,d.jsxs)(rf,{open:f,children:[N&&(0,d.jsx)("div",{style:{borderTop:"1px solid var(--border)",background:"var(--bg)"},children:(0,d.jsx)(ox,{files:N})}),S&&(0,d.jsx)("div",{style:{borderTop:"1px solid var(--border)",background:"var(--bg)"},children:(0,d.jsx)(ox,{files:S})}),l&&S&&O&&(0,d.jsx)(oE,{text:L??"",isEmpty:z,isError:O}),l&&!S&&!I&&(w?(0,d.jsx)(of,{diff:w}):(!z||0===P.length)&&(0,d.jsx)(oE,{text:L??"",isEmpty:z,isError:O})),l&&h]})]})}function of(e){let{diff:t}=e;return(0,d.jsx)("div",{style:{borderTop:"1px solid var(--border)",background:"var(--bg)"},children:(0,d.jsx)(og,{text:t.text})})}function og(e){let{text:t}=e,n=(0,u.useMemo)(()=>aj(t),[t]);return n?(0,d.jsx)(ox,{files:n}):(0,d.jsx)(oS,{text:t})}function ox(e){let{files:t}=e,n=nf()?"stacked":"split";return(0,d.jsx)(ov,{files:t,layout:n})}function ov(e){let{files:t,layout:n}=e,{t:r}=(0,ns.s)(),i=t.length>1;return(0,d.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:t.map((e,t)=>(0,d.jsxs)("div",{style:{minWidth:0,borderTop:0===t?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[i&&"split"===n&&(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)(oj,{title:e.oldPath||r("i18n.before"),side:"left"}),(0,d.jsx)(oj,{title:e.newPath||r("i18n.after"),side:"right"})]}),i&&"stacked"===n&&oy(e)&&(0,d.jsx)("div",{title:oy(e),style:{position:"sticky",top:0,zIndex:1,padding:"5px 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:oy(e)}),"split"===n&&(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:"gap"===e.type?(0,d.jsx)(ob,{gap:e},t):(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)(ok,{cell:e.left,side:"left"}),(0,d.jsx)(ok,{cell:e.right,side:"right"})]},t))}),"stacked"===n&&ak(e).map((e,t)=>"gap"===e.type?(0,d.jsx)(ob,{gap:e},t):(0,d.jsx)(ow,{line:e},t))]},t))})}function ob(e){let{gap:t}=e,{t:n}=(0,ns.s)();return(0,d.jsx)("div",{style:{gridColumn:"1 / -1",padding:"0 10px",color:"var(--text-dim)",background:"var(--bg-panel)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",userSelect:"none"},children:null===t.count?"⋯":`⋯ ${aS(t.count,n)}`})}function oy(e){return e.newPath&&"/dev/null"!==e.newPath?e.newPath:e.oldPath||e.newPath||""}function ow(e){let{line:t}=e;return(0,d.jsx)(ok,{side:"right",cell:{lineNo:"removed"===t.type?t.oldLineNo:t.newLineNo,text:t.text,type:t.type}})}function oj(e){let{title:t,side:n}=e;return(0,d.jsx)("div",{title:t,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===n?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})}function ok(e){let{cell:t,side:n}=e,r="added"===t.type?"rgba(34,197,94,0.12)":"removed"===t.type?"rgba(248,113,113,0.13)":"empty"===t.type?"var(--bg-subtle)":"transparent",i="added"===t.type?"+":"removed"===t.type?"-":" ",s="added"===t.type?"#22c55e":"removed"===t.type?"#f87171":"var(--text-dim)";return(0,d.jsxs)("div",{style:{display:"flex",minWidth:0,background:r,borderRight:"left"===n?"1px solid var(--border)":"none"},children:[(0,d.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:t.lineNo??""}),(0,d.jsx)("span",{style:{width:18,padding:"0 5px",color:s,userSelect:"none",fontWeight:"context"===t.type||"empty"===t.type?400:700,flexShrink:0},children:i}),(0,d.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===t.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.text||"\xa0"})]})}function oS(e){let{text:t}=e,n=t.split(/\r?\n/);return(0,d.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:n.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,d.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,d.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,d.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function oC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oN(e){let{images:t,isError:n}=e;return(0,d.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)",borderTop:`1px solid ${n?"rgba(248,113,113,0.3)":"var(--border)"}`},children:t.map((e,t)=>{let n=oP(e);return n?(0,d.jsx)(lC,{src:n,style:{maxWidth:"100%"},children:(0,d.jsx)("img",{src:n,alt:"",loading:"lazy",style:{display:"block",maxWidth:"min(100%, 720px)",maxHeight:520,borderRadius:6,objectFit:"contain",border:"1px solid var(--border)"}})},`${n}-${t}`):null})})}function oE(e){let{text:t,isEmpty:n,isError:r}=e,{t:i}=(0,ns.s)();return(0,d.jsx)("div",{style:{borderTop:`1px solid ${r?"rgba(248,113,113,0.3)":"var(--border)"}`,background:r?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,d.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:r?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?i("i18n.noOutput"):t})})}function oM(e){let{message:t}=e,{t:n}=(0,ns.s)(),[r,i]=(0,u.useState)(!1),s=oA(t.content),l=a7(t.timestamp),a=t.details?.tokensBefore,o=aX(t).find(e=>"summary_cost"===e.kind&&"compaction"===e.source);return(0,d.jsx)("div",{style:{marginBottom:16},children:(0,d.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),l&&(0,d.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:l})]}),(0,d.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,d.jsxs)("button",{type:"button","aria-expanded":r,title:n(r?"i18n.collapse":"i18n.expand"),onClick:()=>i(e=>!e),style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:0,border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:4,color:"var(--text-muted)",transform:r?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,d.jsxs)("span",{style:{minWidth:0},children:[(0,d.jsx)("span",{style:{display:"block",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:n("i18n.conversationCompacted")}),"number"==typeof a&&Number.isFinite(a)&&(0,d.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:n("i18n.compactedFromTokens",{tokens:a.toLocaleString()})}),o&&(0,d.jsx)("span",{style:{display:"block",marginTop:2,color:a0,fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:a2(n,o)})]})]}),(0,d.jsx)(rf,{open:r,children:(0,d.jsx)(o$,{summary:s})})]})]})})}function o$(e){let{summary:t}=e,{t:n}=(0,ns.s)(),r=(0,u.useMemo)(()=>{let e,n,r,i,s;return e=[],n=[],r=t.match(ag),i=r?.[1]??"",s=r?.index===void 0?t:t.slice(0,r.index),i.replace(af,(t,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):n.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:n}},[t]);return(0,d.jsxs)("div",{style:{marginTop:10},children:[r.body?(0,d.jsx)(ah,{className:"markdown-compaction-message",children:r.body}):(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:n("i18n.noSummary")}),(0,d.jsx)(oI,{readFiles:r.readFiles,modifiedFiles:r.modifiedFiles})]})}function oI(e){let{readFiles:t,modifiedFiles:n}=e,{t:r}=(0,ns.s)();if(0===t.length+n.length)return null;let i=[];return t.length>0&&i.push(`${t.length} read`),n.length>0&&i.push(`${n.length} modified`),(0,d.jsxs)("details",{className:"compaction-file-details",children:[(0,d.jsx)("summary",{children:r("i18n.fileContext",{details:i.join(", ")})}),n.length>0&&(0,d.jsx)(oT,{title:r("i18n.modifiedFiles"),files:n}),t.length>0&&(0,d.jsx)(oT,{title:r("i18n.readFiles"),files:t})]})}function oT(e){let{title:t,files:n}=e;return(0,d.jsxs)("div",{className:"compaction-file-section",children:[(0,d.jsx)("div",{className:"compaction-file-title",children:t}),(0,d.jsx)("ul",{className:"compaction-file-list",children:n.map(e=>(0,d.jsx)("li",{children:e},e))})]})}function oR(e){let{message:t,cwd:n,onOpenFile:r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)(!0),[a,o]=(0,u.useState)(!1),[c,p]=(0,u.useState)(!1),h=oA(t.content),m=oL(t.content),f=void 0!==t.details,g=f?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(t.details):"",x=t.customType||"extension",v=a7(t.timestamp);return(0,d.jsx)("div",{style:{marginBottom:16},children:(0,d.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,d.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:s?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:(0,d.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),className:"custom-message-toggle","aria-expanded":s,title:i(s?"i18n.collapse":"i18n.expand"),style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1,padding:0,border:"none",background:"none",color:"inherit",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650,flexShrink:0},children:x}),!s&&h&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:h.slice(0,300).replace(/\s+/g," ").trim()}),v&&(0,d.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,flexShrink:0},children:v}),(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:s?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),(0,d.jsx)(rf,{open:s,children:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{style:{padding:"6px 9px"},children:[m.length>0&&(0,d.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!h},children:m.map((e,t)=>{let n=oP(e);return n?(0,d.jsx)(lC,{src:n,children:(0,d.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),h?(0,d.jsx)(ah,{className:"markdown-custom-message",keepTextLayout:!0,cwd:n,onOpenFile:r,children:h}):(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:i("i18n.noMessage")})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[h||g?(0,d.jsx)("button",{onClick:()=>{p(!1),s$(h||g).then(()=>{p(!0),setTimeout(()=>p(!1),1500)},()=>{})},style:{padding:"3px 7px",border:"none",background:"none",color:c?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:i(c?"i18n.copied":"i18n.copy")}):null,f&&(0,d.jsx)("button",{onClick:()=>o(e=>!e),className:"custom-message-details-toggle","aria-expanded":a,style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:i(a?"i18n.hideDetails":"i18n.showDetails")})]}),f&&(0,d.jsx)(rf,{open:a,children:(0,d.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:g})})]})})]})})}function oA(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function oL(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function oP(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}let oz=new Set(["path","file_path","content"]),oO={padding:"4px 12px 4px 0",color:"var(--text-dim)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",whiteSpace:"nowrap",verticalAlign:"top"},oW={padding:"4px 0",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},oF={margin:0,padding:"8px 10px",maxHeight:260,overflow:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",font:"inherit",lineHeight:1.5,whiteSpace:"pre-wrap"};function oD(e){let{fields:t}=e;return(0,d.jsx)("table",{style:{borderCollapse:"collapse"},children:(0,d.jsx)("tbody",{children:t.map(e=>(0,d.jsxs)("tr",{children:[(0,d.jsx)("td",{style:oO,children:e.key}),(0,d.jsx)("td",{style:oW,children:e.multiline?(0,d.jsx)("pre",{style:oF,children:e.value}):e.value})]},e.key))})})}let o_={up:"M6 10.5V1.5M2.5 5 6 1.5 9.5 5",down:"M6 1.5v9M2.5 7 6 10.5 9.5 7",clock:"M6 1.25a4.75 4.75 0 1 0 0 9.5 4.75 4.75 0 1 0 0-9.5M6 3.5V6l1.75 1"},oB={fontSize:0};function oH(e){let{part:t}=e;return t.icon?(0,d.jsxs)("span",{children:[t.before&&(0,d.jsx)("span",{style:oB,children:t.before}),(0,d.jsx)("svg",{width:"clock"===t.icon?10:9,height:"clock"===t.icon?10:9,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,style:{display:"inline",verticalAlign:"clock"===t.icon?"-0.1em":"-0.05em",marginRight:"clock"===t.icon?3:1},children:(0,d.jsx)("path",{d:o_[t.icon]})}),t.text,t.after&&(0,d.jsx)("span",{style:oB,children:t.after})]}):(0,d.jsx)("span",{children:t.text})}function oU(e){let{message:t,sessionId:n}=e,{t:r}=(0,ns.s)(),[i,s]=(0,u.useState)(null),[l,a]=(0,u.useState)(!1),[o,c]=(0,u.useState)(null),p=!t.output&&void 0===t.exitCode&&!t.cancelled,h=t.cancelled||void 0!==t.exitCode&&0!==t.exitCode,m=n&&t.fullOutputPath?`/api/agent/${encodeURIComponent(n)}/bash-output?path=${encodeURIComponent(t.fullOutputPath)}`:null,f=null!==i,g=i??t.output;async function x(){if(m){a(!0),c(null);try{let e=await fetch(m),t=await e.json().catch(()=>null);t?.success?s(t.data?.output??""):c(r(413===e.status?"chat.fullOutputTooLarge":"chat.fullOutputUnavailable"))}catch{c(r("chat.fullOutputUnavailable"))}finally{a(!1)}}}let v=t.excludeFromContext?"bash (local)":"bash",b={type:"toolCall",toolCallId:`bash-${t.timestamp??""}`,toolName:v,input:{command:t.command}},y=p?void 0:{role:"toolResult",toolCallId:b.toolCallId,toolName:v,content:g?[{type:"text",text:g}]:[],isError:h,timestamp:t.timestamp},w={color:"var(--accent)",fontSize:11,textDecoration:"underline"},j=t.truncated&&m?(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"baseline",gap:"2px 10px",padding:"5px 10px",fontSize:11,color:"var(--text-dim)",borderTop:`1px solid ${h?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:[(0,d.jsx)("span",{role:"status",children:o??r(f?"chat.fullOutputShown":"chat.outputTruncated")}),!f&&(0,d.jsx)("button",{type:"button",onClick:x,disabled:l,style:{...w,background:"none",border:"none",cursor:l?"default":"pointer",padding:0},children:l?r("chat.loadingFullOutput"):r("chat.viewFullOutput")}),(0,d.jsx)("a",{href:`${m}&download=1`,style:w,children:r("chat.downloadFullOutput")})]}):null;return(0,d.jsx)("div",{style:{margin:"6px 0"},children:(0,d.jsx)(om,{block:b,result:y,resultFooter:j})})}let oK=/^([ \t]*)([-*+])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,oq=/^([ \t]*)(\d{1,9})([.)])([ \t]+)(\[[ xX]\](?:[ \t]+|$))?/,oV=/^([ \t]*)(\d{1,3})(、)([ \t]*)/,oZ=/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/,oJ=/^[ \t]{0,3}(`{3,}|~{3,})/;function oY(e){let t=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
7
|
+
|
|
8
|
+
`}function oG(e){return!e.trim()||e.endsWith("\n\n")?"":e.endsWith("\n")?"\n":"\n\n"}function oX(e){return"mcp"===e.name&&e.sourceInfo?.path==="builtin:mcp"}function oQ(e){return"/mcp"===e.trim()}function o0(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.length,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(t!==n||e.trimStart().startsWith("!"))return null;let r=e.slice(0,t),i=/(^|[\s\u3400-\u9fff,。!?;:、()【】《》“”‘’])\/([^\s/\\]*)$/.exec(r);if(!i)return null;let s=t-i[2].length-1,l=s;for(;l>0&&!/\s/.test(e[l-1]);)l--;let a=e.slice(l,s);if(/[\/\\]/.test(a))return null;let o=/^[^\s/\\]*/.exec(e.slice(t))?.[0]??"",c=i[2]+o;return"/"===e[t+o.length]||"\\"===e[t+o.length]||c.includes(":")&&!c.toLowerCase().startsWith("skill:")?null:{start:s,end:t+o.length,query:i[2].toLowerCase(),inline:e.slice(0,s).trim().length>0}}let o1="enter",o2=nn("pi-enter-send-mode",e=>"ctrlEnter"===e?"ctrlEnter":o1,o1),o4="pi-chat-content-width",o3="pi-chat-content-font-size",o8={width:820,fontSize:14},o6=null,o5=new Set;function o9(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function o7(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function ce(e){try{return window.localStorage.getItem(e)}catch{return null}}function ct(e){let{width:t,fontSize:n}=e;"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${t}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${n}px`))}function cn(){return o6||ct(o6={width:o9(ce(o4)),fontSize:o7(ce(o3))}),o6}function cr(e){return o5.add(e),()=>{o5.delete(e)}}function ci(e,t){let n="width"===e?o9(t):o7(t);ct(o6={...cn(),[e]:n});try{window.localStorage.setItem("width"===e?o4:o3,String(n))}catch{}o5.forEach(e=>e())}let cs=e=>ci("width",e),cl=e=>ci("fontSize",e);function ca(){return{...(0,u.useSyncExternalStore)(cr,cn,()=>o8),setWidth:cs,setFontSize:cl}}let co=[{value:100,label:"settings.fontWeightThin"},{value:200,label:"settings.fontWeightExtraLight"},{value:300,label:"settings.fontWeightLight"},{value:400,label:"settings.fontWeightRegular"},{value:500,label:"settings.fontWeightMedium"},{value:600,label:"settings.fontWeightSemiBold"}],cc={ui:"pi-ui-font-family",mono:"pi-mono-font-family",uiWeight:"pi-ui-font-weight",monoWeight:"pi-mono-font-weight"},cd={ui:"",mono:"",uiWeight:400,monoWeight:400};function cu(e){let t="string"==typeof e?Number(e):e;return co.find(e=>e.value===t)?.value??400}function cp(e){return"string"==typeof e&&e.length<=500?e:""}let ch=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded"]),cm=["ui","mono"],cf=Object.keys(cc),cg=null,cx=new Set;function cv(){let e={...cd};for(let t of cm)try{e[t]=cp(window.localStorage.getItem(cc[t]));let n=`${t}Weight`;e[n]=cu(window.localStorage.getItem(cc[n]))}catch{}return e}function cb(e){for(let t of cm){let n=`--font-${t}`,r=function(e,t){let n=cp(t).split(",").flatMap(e=>{let t=e.trim().replace(/\s+/g," "),n=t.length>=2&&('"'===t[0]||"'"===t[0])&&t.endsWith(t[0]);return(n&&(t=t.slice(1,-1).trim()),t)?[!n&&ch.has(t.toLowerCase())?t.toLowerCase():JSON.stringify(t)]:[]}).join(", ");return n?`${n}, var(--font-${e}-default)`:""}(t,e[t]);r?document.documentElement.style.setProperty(n,r):document.documentElement.style.removeProperty(n);let i=e[`${t}Weight`];400===i?document.documentElement.style.removeProperty(`${n}-weight`):document.documentElement.style.setProperty(`${n}-weight`,String(i))}}function cy(){return cg||cb(cg=cv()),cg}function cw(){cx.forEach(e=>e())}function cj(e){if(null!==e.key&&!Object.values(cc).includes(e.key))return;let t=cv(),n=cy();cf.every(e=>t[e]===n[e])||(cg=t,cb(t),cw())}function ck(e){return 0===cx.size&&window.addEventListener("storage",cj),cx.add(e),cy(),()=>{cx.delete(e),0===cx.size&&window.removeEventListener("storage",cj)}}function cS(e){let t=cy(),n=cf.filter(n=>t[n]!==e[n]);if(n.length){for(let t of(cg=e,cb(e),n))try{e[t]===cd[t]?window.localStorage.removeItem(cc[t]):window.localStorage.setItem(cc[t],String(e[t]))}catch{}cw()}}function cC(e,t){cS({...cy(),[e]:cp(t)})}function cN(e,t){cS({...cy(),[`${e}Weight`]:cu(t)})}function cE(e){cS({...cy(),[e]:"",[`${e}Weight`]:400})}function cM(){return{...(0,u.useSyncExternalStore)(ck,cy,()=>cd),setFontPreference:cC,setFontWeight:cN,resetFontPreference:cE}}function c$(e){let{filled:t,size:n}=e;return(0,d.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,d.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 cI(e){let{active:t,onSelect:n,star:r,gutter:i=!!r,className:s,children:l}=e,a=nf(),[o,c]=(0,u.useState)(!1),[p,h]=(0,u.useState)(!1),m=!!(r&&!r.isDefault),f=m&&(o||p||a);return(0,d.jsxs)("div",{className:["selector-row",s].filter(Boolean).join(" "),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>h(!0),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||h(!1)},style:{position:"relative",background:t?"var(--bg-selected)":o?"var(--bg-hover)":"transparent",transition:"background 0.1s"},children:[(0,d.jsxs)("button",{type:"button",role:"option","aria-selected":t,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0,padding:i?"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,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),l]}),r?.isDefault&&(0,d.jsx)("span",{role:"img","aria-label":r.defaultLabel,title:r.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,d.jsx)(c$,{filled:!0,size:10})}),r&&m&&(0,d.jsx)("button",{type:"button",title:r.saveLabel,"aria-label":r.saveLabel,tabIndex:f?0:-1,onClick:e=>{e.stopPropagation(),r.onSave()},style:{position:"absolute",top:"50%",right:6,transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",opacity:+!!f,pointerEvents:f?"auto":"none",transition:"opacity 0.1s, background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,d.jsx)(c$,{filled:!1,size:12})})]})}function cT(e){var t;let n,r,i,s,l,a,o,c,p,h,m,{options:f,value:g,onChange:x,onReselect:v,onClear:b,emptyLabel:y,selectedLabel:w,disabled:j=!1,busy:k=!1,isAutoSelection:S=!1,ariaLabel:C,variant:N="toolbar",placement:E="up",defaultValue:M,onSetDefault:$,allOptions:I,onShowAll:T}=e,{t:R}=(0,ns.s)(),A=nf(),L=(0,u.useRef)(null),P=(0,u.useRef)(null),z=(0,u.useId)(),[O,W]=(0,u.useState)(!1),[F,D]=(0,u.useState)(null),[_,B]=(0,u.useState)(""),[H,U]=(0,u.useState)(!1),K=j||k,q=H?I:f,V=(t=q??[],(n=_.trim().toLocaleLowerCase())?t.filter(e=>`${e.name} ${e.providerName??""} ${e.modelId} ${e.provider}/${e.modelId}`.toLocaleLowerCase().includes(n)):t),Z=!!T||f.length>8,J=(e,t)=>e?.find(e=>e.modelId===t.modelId&&e.provider===t.provider),Y=()=>{H||T?.(),U(!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}(V),X=w??(g?(J(f,g)??J(I,g))?.name??g.modelId:y??(f.length>0?R("chat.selectModel"):R("chat.noModels"))),Q=()=>{W(!1),B(""),L.current?.querySelector("button")?.focus({preventScroll:!0})};(0,u.useEffect)(()=>{if(!O)return;let e=P.current?.querySelector('[role="option"][aria-selected="true"]')??P.current?.querySelector('[role="option"]');e?.scrollIntoView({block:"nearest"}),Z||A||e?.focus({preventScroll:!0})},[O,Z,A]),(0,u.useEffect)(()=>{let e=e=>{L.current&&!L.current.contains(e.target)&&P.current&&!P.current.contains(e.target)&&(W(!1),B(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,u.useEffect)(()=>{if(!O)return;let e=()=>{let e=L.current?.querySelector("button")?.getBoundingClientRect();e?.height&&D({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)}},[O]),(0,u.useEffect)(()=>{K&&(W(!1),B(""))},[K]);let ee="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:K?"var(--bg-panel)":"var(--bg)",color:K?"var(--text-dim)":"var(--text)",cursor:K?"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:O?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:K?"not-allowed":"pointer",fontSize:12,opacity:K?.5:1,transition:"background 0.12s, color 0.12s"};return(0,d.jsxs)("div",{ref:L,className:`model-selector is-${N}${K?" 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=>{if(e.nativeEvent.isComposing||229===e.keyCode){O&&e.stopPropagation();return}if(!O){K||"ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),L.current?.querySelector("button")?.click());return}if("Escape"===e.key){e.preventDefault(),e.stopPropagation(),Q();return}let t=Array.from(P.current?.querySelectorAll('[role="option"]')??[]),n=t.indexOf(e.target),r=e.target instanceof HTMLInputElement,i="ArrowDown"===e.key||"ArrowUp"===e.key,s=!r&&("Home"===e.key||"End"===e.key);if((i||s)&&t.length){e.preventDefault(),e.stopPropagation();let r="Home"===e.key?0:"End"===e.key?t.length-1:n<0?"ArrowUp"===e.key?t.length-1:0:(n+("ArrowUp"===e.key?-1:1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})}else r&&"Enter"===e.key&&t.length&&(e.preventDefault(),t[0].click())},onBlur:e=>{O&&e.relatedTarget&&!e.currentTarget.contains(e.relatedTarget)&&(W(!1),B(""))},children:[(0,d.jsxs)("button",{type:"button","aria-label":C,"aria-haspopup":"listbox","aria-expanded":O,"aria-controls":O?z:void 0,"aria-busy":k||void 0,disabled:K,title:k?R("chat.switchingModel"):K?X:f.length>0||b?R("chat.changeModel"):R("chat.noAvailableModels"),style:ee,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();D({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),W(e=>(e?B(""):U(!1),!e))},onMouseEnter:e=>{K||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(K){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=O?"var(--bg-hover)":"field"===N?"var(--bg)":"none",e.currentTarget.style.color="field"===N?"var(--text)":"var(--text-muted)"},children:[k?(0,d.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,d.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,d.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,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,d.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,d.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,d.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,d.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,d.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,d.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,d.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:X}),"field"===N&&(0,d.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,d.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),O&&F&&(r=window.visualViewport?.offsetTop??0,i=window.visualViewport?.height??window.innerHeight,s=window.visualViewport?.width??window.innerWidth,a=(l=Math.min(F.top-6,r+i-8))-r-8,o=r+i-F.bottom-6-8,p=Math.max(120,Math.min((c="up"===E||a>o)?a:o,.6*i)),h=c?{top:l,transform:"translateY(-100%)"}:{top:F.bottom+6},m=A?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:F.left,width:"max-content",minWidth:F.width,maxWidth:Math.max(F.width,s-F.left-8)},(0,d.jsxs)("div",{ref:P,id:z,className:"model-selector-panel",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:c?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[T&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px 0",fontSize:11},children:[[!1,!0].map(e=>(0,d.jsx)("button",{type:"button","aria-pressed":H===e,onClick:()=>{H!==e&&Y()},style:{padding:"2px 7px",border:"1px solid",borderColor:H===e?"var(--border)":"transparent",borderRadius:4,background:H===e?"var(--bg-hover)":"none",color:H===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11},children:R(e?"chat.modelScopeAll":"chat.modelScopeScoped")},String(e))),!A&&(0,d.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:"Tab"})]}),Z&&(0,d.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,d.jsx)("input",{value:_,onChange:e=>B(e.target.value),onKeyDown:e=>{!T||"Tab"!==e.key||e.shiftKey||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),Y())},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,d.jsxs)("div",{style:{minHeight:0,overflowY:"auto",overscrollBehavior:"contain"},children:[b&&!_.trim()&&(0,d.jsx)(cI,{active:!g,gutter:!!$,onSelect:()=>{Q(),b()},children:(0,d.jsx)(cR,{label:y??R("i18n.default")})}),0===G.length?(0,d.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:q?_.trim()?R("chat.noMatchingModels"):R("chat.noAvailableModels"):R("agents.modelsLoading")}):G.map((e,t)=>(0,d.jsxs)("div",{children:[G.length>1&&(0,d.jsx)("div",{title:e.providerName===e.provider?void 0:e.provider,style:{padding:"6px 12px 4px",borderTop:t>0||b?"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,d.jsx)(cI,{active:e.modelId===g?.modelId&&e.provider===g?.provider,onSelect:()=>{let t;return t=e.modelId===g?.modelId&&e.provider===g?.provider,void(Q(),!t||S?x(e.provider,e.modelId):v?.(e.provider,e.modelId))},star:$&&(!H||J(f,e))?{isDefault:e.modelId===M?.modelId&&e.provider===M?.provider,saveLabel:R("chat.saveDefaultModel"),defaultLabel:R("chat.defaultModel"),onSave:()=>{Q(),$?.(e.provider,e.modelId)}}:void 0,children:(0,d.jsx)(cR,{label:e.name})},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function cR(e){let{label:t}=e;return(0,d.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})}let cA=["off","minimal","low","medium","high","xhigh","max"];function cL(e){let{options:t,allOptions:n,onShowAll:r,model:i,isAutoModelSelection:s,onModelChange:l,defaultModel:a,onSetDefaultModel:o,isStreaming:c,modelSwitching:p,thinkingLevel:h,isAutoThinkingSelection:m,availableThinkingLevels:f,thinkingLevelMap:x,onThinkingLevelChange:v,savedDefaultThinkingLevel:b,onSetDefaultThinkingLevel:y}=e,{t:w}=(0,ns.s)(),[j,k]=(0,u.useState)(!1),[S,C]=(0,u.useState)(null),[N,E]=(0,u.useState)(null),M=(0,u.useRef)(null),$=(0,u.useRef)(null),I=(0,u.useRef)(null),T=(0,u.useRef)(null),R=(0,u.useRef)(!!p),A=(0,u.useId)(),L=cA.filter(e=>"off"!==e&&(!f||f.includes(e))&&x?.[e]!==null),P=h&&"auto"!==h?h:null,z=m||"auto"===h||!h,O=e=>{let t="auto"!==e?x?.[e]:null;return null!=t&&t!==e?t:w(`chat.reasoningShort.${e}`)},W=O(P??"auto"),F=i?(t.find(e=>e.provider===i.provider&&e.modelId===i.modelId)??n?.find(e=>e.provider===i.provider&&e.modelId===i.modelId))?.name??i.modelId:t.length?w("chat.selectModel"):w("chat.noModels"),D=P?L.indexOf(P):-1,_=Math.max(0,D),B=`${i?.provider}:${i?.modelId}:${L.join(",")}`,H=N?.key===B,U=H?N.value:_,K=H?L[Math.round(U)]:null,q=H?Math.round(U):D,V=!!v&&!p,Z=!f||f.includes("off"),J=!!p,Y=(0,u.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];k(!1),E(null),e&&M.current?.focus({preventScroll:!0})},[]);(0,u.useEffect)(()=>{let e=R.current;R.current=!!p,j&&e&&!p&&document.activeElement===document.body&&I.current?.querySelector("button")?.focus({preventScroll:!0})},[j,p]),(0,u.useEffect)(()=>{if(!j)return;let e=e=>{M.current?.contains(e.target)||$.current?.contains(e.target)||Y()};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[j,Y]),(0,u.useLayoutEffect)(()=>{if(!j)return;let e=()=>{let e=M.current,t=$.current;if(!e||!t)return;let n=window.visualViewport,r=n?.offsetLeft??0,i=n?.offsetTop??0,s=n?.width??window.innerWidth,l=n?.height??window.innerHeight,a=e.getBoundingClientRect(),o=Math.min(332,s-16),c=Math.min(t.getBoundingClientRect().height,l-16),d=a.top-i-8,u=i+l-a.bottom-8,p=d>=c||d>=u?a.top-c-8:a.bottom+8,h={left:Math.max(r+8,Math.min(a.left,r+s-o-8)),top:Math.max(i+8,Math.min(p,i+l-c-8)),width:o,maxHeight:Math.max(0,l-16)};C(e=>JSON.stringify(e)===JSON.stringify(h)?e:h)};e();let t=new ResizeObserver(e);$.current&&t.observe($.current);let n=new MutationObserver(e);n.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-keyboard-open"]}),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),window.visualViewport?.addEventListener("resize",e),window.visualViewport?.addEventListener("scroll",e);let r=requestAnimationFrame(()=>{(T.current??$.current?.querySelector("button:not(:disabled)")??$.current)?.focus({preventScroll:!0})});return()=>{cancelAnimationFrame(r),t.disconnect(),n.disconnect(),window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0),window.visualViewport?.removeEventListener("resize",e),window.visualViewport?.removeEventListener("scroll",e)}},[j]);let G=e=>{V&&("auto"===e?!z:z||e!==P)&&v?.(e)},X=()=>I.current?.querySelector("button")?.focus({preventScroll:!0}),Q=P===b;return(0,d.jsxs)("div",{className:"model-reasoning-root",children:[(0,d.jsxs)("button",{ref:M,type:"button",className:"model-reasoning-trigger composer-model-trigger","aria-label":w("chat.modelReasoning"),"aria-haspopup":"dialog","aria-expanded":j,"aria-controls":j?A:void 0,"aria-busy":p||void 0,disabled:J,title:p?"Switching model":t.length||i?`${F}${v?` \xb7 ${W}`:""}`:"No available models",onClick:()=>{C(null),E(null),k(e=>!e)},children:[p&&(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}),(0,d.jsx)("span",{className:"model-reasoning-name",children:F}),v&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{"aria-hidden":"true",children:"\xb7"}),(0,d.jsx)("span",{className:"model-reasoning-level",children:W})]}),(0,d.jsx)("span",{className:"chat-composer-caret","aria-hidden":"true"})]}),j&&(0,g.createPortal)((0,d.jsxs)("div",{ref:$,id:A,role:"dialog","aria-label":w("chat.modelReasoning"),tabIndex:-1,className:"model-reasoning-card composer-model-card",style:{...S,visibility:S?"visible":"hidden"},onKeyDown:e=>{if("Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),Y(!0)),"Tab"===e.key){let t=[...e.currentTarget.querySelectorAll('button:not(:disabled), input:not(:disabled), [tabindex="0"]')].filter(e=>e.getClientRects().length>0),n=t[0],r=t.at(-1);e.shiftKey&&(document.activeElement===n||document.activeElement===$.current)?(e.preventDefault(),r?.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n?.focus())}},children:[(0,d.jsxs)("div",{className:"model-reasoning-heading",children:[(0,d.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m13 2-9 12h7l-1 8 10-13h-7l1-7Z"})}),(0,d.jsx)("strong",{children:v?O(K??P??"auto"):w("chat.selectModel")}),v&&(0,d.jsx)("button",{type:"button",className:"model-reasoning-reset","aria-label":w("chat.resetReasoning"),title:w("chat.resetReasoning"),disabled:!V||z,onClick:()=>G("auto"),children:(0,d.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M3 10a9 9 0 1 1 2.5 8M3 4v6h6"})})})]}),l&&(0,d.jsx)("div",{ref:I,className:"model-reasoning-model",children:(0,d.jsx)(cT,{options:t,allOptions:n,onShowAll:r,value:i,variant:"field",placement:"auto",ariaLabel:w("chat.selectModel"),isAutoSelection:s,busy:p,onChange:(e,t)=>{l(e,t),X()},onReselect:(e,t)=>{l(e,t),X()},defaultValue:a,onSetDefault:o?(e,t)=>{o(e,t),X()}:void 0})}),v&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"model-reasoning-modes",children:[(0,d.jsx)("button",{type:"button","aria-pressed":z,disabled:!V,onClick:()=>G("auto"),children:w("chat.reasoningShort.auto")}),Z&&(0,d.jsx)("button",{type:"button","aria-pressed":!z&&"off"===P,disabled:!V,onClick:()=>G("off"),children:w("chat.reasoningShort.off")})]}),L.length>1?(0,d.jsxs)("div",{className:"model-reasoning-sliderGroup","data-dragging":H,"data-inactive":!H&&"off"===P,children:[(0,d.jsxs)("div",{className:"model-reasoning-track",style:{"--reasoning-ratio":U/(L.length-1)},children:[(0,d.jsx)("div",{className:"model-reasoning-fill","aria-hidden":"true"}),(0,d.jsx)("div",{className:"model-reasoning-dots","aria-hidden":"true",children:L.map(e=>(0,d.jsx)("span",{},e))}),(0,d.jsx)("span",{className:"model-reasoning-thumb","aria-hidden":"true"}),(0,d.jsx)("input",{ref:T,type:"range",min:0,max:L.length-1,step:"any",value:U,disabled:!V,"aria-label":w("chat.reasoningMenuTitle"),"aria-valuetext":q<0?W:`${O(L[Math.max(0,q)])} (${L[Math.max(0,q)]})`,onPointerDown:e=>{V&&0===e.button&&(e.currentTarget.setPointerCapture(e.pointerId),E({key:B,value:Number(e.currentTarget.value)}))},onPointerUp:e=>{H&&(G(L[Math.round(Number(e.currentTarget.value))]),E(null))},onPointerCancel:()=>E(null),onLostPointerCapture:()=>E(null),onClick:e=>{0===e.detail&&G(L[Math.round(Number(e.currentTarget.value))])},onKeyDown:e=>{let t={ArrowRight:1,ArrowUp:1,PageUp:1,ArrowLeft:-1,ArrowDown:-1,PageDown:-1}[e.key];if(void 0===t&&"Home"!==e.key&&"End"!==e.key)return;e.preventDefault(),E(null);let n="Home"===e.key?0:"End"===e.key?L.length-1:D<0?0:Math.max(0,Math.min(L.length-1,D+(t??0)));G(L[n])},onChange:e=>{let t=Number(e.target.value);H?E({key:B,value:t}):G(L[Math.round(t)])}})]}),(0,d.jsx)("div",{className:"model-reasoning-scale",style:{gridTemplateColumns:`repeat(${L.length}, minmax(0, 1fr))`},"aria-hidden":"true",children:L.map((e,t)=>(0,d.jsx)("span",{title:O(e),"data-active":t===q,children:O(e)},e))})]}):1===L.length?(0,d.jsx)("div",{className:"model-reasoning-single",children:(0,d.jsx)("button",{type:"button","aria-pressed":!z&&P===L[0],disabled:!V,onClick:()=>G(L[0]),children:O(L[0])})}):(0,d.jsx)("p",{className:"model-reasoning-hint",children:w("chat.reasoningUnavailable")}),P&&x?.[P]!=null&&x[P]!==P&&(0,d.jsxs)("p",{className:"model-reasoning-hint",children:[x[P]," \xb7 ",P]}),c&&(0,d.jsx)("p",{className:"model-reasoning-hint",children:w("chat.reasoningNextRequest")}),y&&P&&("off"===P?Z:L.includes(P))&&(0,d.jsxs)("button",{type:"button",className:"model-reasoning-saveDefault",disabled:!V||Q,onClick:()=>y(P),children:[(0,d.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:Q?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.7","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 3 3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1Z"})}),w(Q?"chat.defaultThinking":"chat.saveDefaultThinking")]})]})]}),document.body)]})}let cP=["configured","chat-only","read-only","default","full"],cz={configured:"configured","chat-only":"none","read-only":"read-only",default:"default",full:"full"},cO={configured:"chat.toolsConfigured","chat-only":"chat.chatOnly","read-only":"chat.toolsReadOnly",default:"chat.toolsStandard",full:"chat.toolsFull"},cW=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function cF(e,t,n){return t<=0?0:((e+n)%t+t)%t}function cD(e,t,n,r){e.setRangeText(r,t,n,"end"),e.dispatchEvent(new Event("input",{bubbles:!0}))}function c_(e,t,n,r){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:r.length,s=e.selectionStart,l=e.selectionEnd;if(e.focus(),s===l&&t<=s&&n>=l){let i=e.value.length-(n-t)+r.length;for(let n=s-t;n>0&&e.selectionStart>t&&document.execCommand("delete");n--);if(document.execCommand("insertText",!1,r))for(let t=n-l;t>0&&e.value.length>i&&document.execCommand("forwardDelete");t--);else cD(e,t,e.selectionStart+(n-l),r)}else e.setSelectionRange(t,n),document.execCommand("insertText",!1,r)||cD(e,t,n,r);i!==r.length&&e.setSelectionRange(t+i,t+i)}function cB(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 cH(e){e.selectionEnd===e.value.length&&(e.scrollTop=e.scrollHeight)}function cU(e,t){let n=null,r=()=>{n=null,t(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8;return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let s=e.parentElement,l=s?.parentElement,a="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&a?.observe(s),l&&a?.observe(l);let o=window.visualViewport;return o?.addEventListener("resize",i),o?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{a?.disconnect(),o?.removeEventListener("resize",i),o?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}function cK(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let cq=[{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 cV(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return cq.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let cZ=["builtin","extension","prompt","skill"],cJ={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},cY={builtin:0,extension:1,prompt:2,skill:3};function cG(e,t){return"builtin"===e.source?t(e.description):e.description??""}function cX(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function cQ(e){return{data:e.data,mimeType:e.mimeType}}function c0(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function c1(e){return(e??[]).filter(j).slice(0,10).map(c0)}function c2(e){return"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function c4(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 j(r)?[r]:[]})}function c3(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function c8(e){let{kind:t,text:n}=e;return(0,d.jsxs)("div",{title:n,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,d.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,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]})}function c6(e){let{tone:t,title:n,body:r,onClose:i,children:s}=e,{t:l}=(0,ns.s)(),a="error"===t?"239,68,68":"234,179,8";return(0,d.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(${a},0.3)`,borderRadius:6,background:`rgba(${a},0.07)`,color:`rgb(${a})`,fontSize:11,lineHeight:1.45},children:[(0,d.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,d.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,d.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,d.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,d.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("div",{style:{fontWeight:600},children:n}),(0,d.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:r}),s]}),i&&(0,d.jsx)("button",{type:"button",onClick:i,"aria-label":l("sidebar.dismiss"),style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function c5(e){let{cwd:t,onFork:n}=e,{t:r}=(0,ns.s)();return t?(0,d.jsx)(c6,{tone:"error",title:r("chat.cwdMissingTitle"),body:r("chat.cwdMissingBody",{cwd:t}),children:n&&(0,d.jsx)("button",{type:"button",onClick:n,style:{display:"block",marginTop:6,padding:"2px 8px",border:"1px solid currentColor",borderRadius:5,background:"transparent",color:"inherit",cursor:"pointer",font:"inherit"},children:r("chat.cwdMissingFork")})}):null}function c9(e){let{error:t}=e,{t:n}=(0,ns.s)();return t?(0,d.jsx)(c6,{tone:"error",title:n("chat.modelError"),body:t}):null}function c7(e){let{warnings:t}=e,{t:n}=(0,ns.s)();return t&&0!==t.length?(0,d.jsx)(c6,{tone:"warning",title:n(t.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:t.join("\n")}):null}let de=(0,u.memo)((0,u.forwardRef)(function(e,t){let n,r,i,s,{onSend:l,onAbort:a,onSteer:o,onSideChat:c,onFollowUp:p,isStreaming:h,model:m,isAutoModelSelection:f,modelNames:g,modelList:x,modelError:v,missingCwd:b,onForkMissingCwd:y,modelScopeWarnings:w,allModelList:j,onLoadAllModels:k,onModelChange:S,modelSwitching:C,defaultModel:N,onSetDefaultModel:E,onCompact:M,onAbortCompaction:$,isCompacting:I,compactError:T,onDismissCompactError:R,compactResult:A,toolPreset:L,onToolPresetChange:P,thinkingLevel:z,isAutoThinkingSelection:O=!1,onThinkingLevelChange:W,availableThinkingLevels:D,thinkingLevelMap:_,savedDefaultThinkingLevel:V,onSetDefaultThinkingLevel:J,retryInfo:Y,queuedMessages:G,inputHistory:X=[],onRecallQueue:Q,slashCommands:ee,slashCommandsLoading:et,onLoadSlashCommands:en,extensionUiOpen:er=!1,onBuiltinCommand:ei,soundEnabled:es,onSoundToggle:el,onAudioUnlock:ea,onPromptWithStreamingBehavior:eo,draftKey:ec,cwd:ed,onAttachFiles:eu,sessionStatsControl:ep,compact:eh=!1}=e,{t:em}=(0,ns.s)(),{fontSize:ef}=ca(),{ui:eg,uiWeight:ex}=cM(),ev=nf(),eb=ev?44:32,ey=o2.use(),[ew,ej]=(0,u.useState)(()=>ec?B(ec)?.value??"":""),[ek,eS]=(0,u.useState)(!1),[eC,eN]=(0,u.useState)(!1),[eE,eM]=(0,u.useState)(()=>ec?c1(B(ec)?.images):[]),e$=ew.trimStart(),eI=0===eE.length&&e$.startsWith("!"),eT=eI&&e$.startsWith("!!"),[eR,eA]=(0,u.useState)(!1),[eL,eP]=(0,u.useState)(null),[ez,eO]=(0,u.useState)(0),[eW,eF]=(0,u.useState)(null),[eD,e_]=(0,u.useState)(null),[eB,eH]=(0,u.useState)(!1),[eU,eK]=(0,u.useState)(null),[eq,eV]=(0,u.useState)(0),[eZ,eJ]=(0,u.useState)(!1),[eY,eG]=(0,u.useState)(!1),[eX,eQ]=(0,u.useState)(0),[e0,e1]=(0,u.useState)(!1),e2=(0,u.useRef)(!1),e4=(0,u.useRef)(null),[e3,e8]=(0,u.useState)(null),[e6,e5]=(0,u.useState)(!1),[e9,e7]=(0,u.useState)(null),[te,tt]=(0,u.useState)(null),tn=ed&&te?.cwd===ed?te.values:{},tr=(0,u.useRef)(null),ti=(0,u.useRef)(null),ts=(0,u.useRef)(null),tl=(0,u.useRef)(null),ta=(0,u.useRef)(null),to=(0,u.useRef)(!1),tc=(0,u.useRef)(0),td=(0,u.useRef)(null),tu=(0,u.useRef)(!1),tp=(0,u.useRef)(null),th=(0,u.useRef)([]),tm=(0,u.useRef)(null),tf=(0,u.useRef)([]),tg=(0,u.useRef)([]),tx=(0,u.useRef)(null),tv=(0,u.useRef)(null),tb=(0,u.useRef)(ec),ty=(0,u.useRef)(ew),tw=(0,u.useRef)(eE),tj=(0,u.useRef)(0);ty.current=ew,tw.current=eE,(0,u.useImperativeHandle)(t,()=>({async openSideChat(){if(!ei)return{handled:!1};if(e2.current)return{handled:!0};e2.current=!0,e1(!0);try{return await ei("/side")}finally{e2.current=!1,e1(!1)}},setText(e){let t=tr.current;if(!t){ty.current=e,ej(e);return}t.setSelectionRange(0,t.value.length),c_(t,0,t.value.length,e),e_(null),requestAnimationFrame(()=>cB(t))},pasteText(e){if(!e)return;let t=tr.current;t?(c_(t,t.selectionStart??t.value.length,t.selectionEnd??t.value.length,e),e_(null),requestAnimationFrame(()=>cB(t))):ej(t=>t+e)},insertIfEmpty(e){let t=tr.current;(t?t.value:ew).trim()||(ty.current=e,ej(e),e_(null),requestAnimationFrame(()=>{t&&(t.focus(),cB(t),cH(t))}))},replaceMessage(e){var t,n,r;let i=tr.current;if(t=i?i.value:ew,n=tw.current.length,r=tj.current,t.trim()||0!==n||0!==r)return;let s=c2(e),l=c1(c4(e));ty.current=s,tw.current=l,ej(s),e_(null),eG(!1),eM(e=>(e.forEach(c3),l)),requestAnimationFrame(()=>{i&&(i.focus(),cB(i),cH(i))})},prependText(e){if(!e.trim())return;let t=tr.current,n=[e,t?t.value:ew].filter(e=>e.trim()).join("\n\n");ty.current=n,ej(n),e_(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),cB(t),cH(t))})},rekeyDraft(e,t){if(e===t)return;if(tb.current!==e)return void Z(e,t);let n={value:ty.current,images:tw.current.map(cQ)},r=Z(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(tb.current=t,i)return;let s=c1(r.images);ty.current=r.value,tw.current=s,ej(r.value),eM(e=>(e.forEach(c3),s)),e_(null),eG(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tb.current,i=n??r,s=i===r,l=!s&&i?B(i):null,a=q(e,t,s?ty.current:l?.value??"",s?tw.current.map(cQ):l?.images??[]);if(i&&H(i,a),!s)return;let o=t?.length?[...c1(t).slice(0,Math.max(0,10-tw.current.length)),...tw.current].slice(0,10):tw.current;ty.current=a.value,tw.current=o,ej(t=>{let n=K(e,t);return ty.current=n,n}),e_(null),eG(!1),t?.length&&eM(e=>{let n=Math.max(0,10-e.length),r=c1(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tw.current=i,i}),requestAnimationFrame(()=>{let e=tr.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),cB(e),cH(e))})},focus(){let e=tr.current;e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},insertText(e){let t=tr.current;if(!t)return void ej(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n);c_(t,n,r,(i.length>0&&!i.endsWith(" ")?" ":"")+e),e_(null)},insertQuote(e){let t=tr.current;if(!t)return void ej(t=>t+oG(t)+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length;c_(t,n,r,oG(t.value.slice(0,n))+e),e_(null)},addImages(e){tk(e)}}));let tk=(0,u.useCallback)(async e=>{if(eh)return;let t=Math.max(0,10-tw.current.length-tj.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tj.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)}}));eM(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(c3);let r=[...t,...n];return tw.current=r,r})}finally{tj.current-=n.length}}},[eh]),tS=(0,u.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eu?eu(t):tk(t)},[eu,tk]),tC=(0,u.useCallback)(e=>{eM(t=>{let n=[...t],[r]=n.splice(e,1);return r&&c3(r),tw.current=n,n})},[]),tN=(0,u.useCallback)(()=>{tw.current=[],eM(e=>(e.forEach(c3),[]))},[]),tE=(0,u.useCallback)(()=>{ty.current="",ej(""),e_(null),eG(!1),ec&&U(ec),tb.current&&tb.current!==ec&&U(tb.current),tN(),tr.current&&(tr.current.style.height="auto")},[tN,ec]);(0,u.useEffect)(()=>{ec&&tb.current===ec&&H(ec,{value:ew,images:eE.map(cQ)})},[eE,ec,ew]),(0,u.useEffect)(()=>{let e=tb.current;if(e===ec)return;e&&H(e,{value:ty.current,images:tw.current.map(cQ)});let t=ec?B(ec):null;tb.current=ec;let n=t?.value??"",r=c1(t?.images);ty.current=n,tw.current=r,ej(n),e_(null),eG(!1),eM(e=>(e.forEach(c3),r))},[ec]);let tM=(0,u.useCallback)(()=>{let e=tr.current;e&&(e.value?cB(e):(e.style.height="auto",e.style.overflowY="hidden"))},[]);(0,u.useLayoutEffect)(tM,[ew,ef,eg,ex,tM]),(0,u.useEffect)(()=>{let e=tr.current;if(!e)return;let t=-1,n=new ResizeObserver(e=>{let[n]=e;n.contentRect.width!==t&&(t=n.contentRect.width,tM())});return n.observe(e),()=>n.disconnect()},[tM]),(0,u.useEffect)(()=>{let e=tr.current;if(!e)return;let t=t=>{if("insertLineBreak"!==t.inputType||t.isComposing)return;let n=function(e,t,n){let r;if(t!==n)return null;let i=e.lastIndexOf("\n",t-1)+1,s=e.indexOf("\n",t),l=-1===s?e.length:s,a=e.slice(i,l),o=function(e){if(oZ.test(e))return null;let t=oK.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=oq.exec(e)??oV.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}(a);return!o||t-i<o.length||function(e){let t=null;for(let n of e.split("\n")){let e=oJ.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:""===a.slice(o.length).trim()?{start:i,end:l,text:""}:{start:t,end:t,text:`
|
|
9
|
+
${r=null===o.number?o.marker:`${String(Number(o.number)+1).padStart(o.number.length,"0")}${o.delimiter}`,`${o.indent}${r}${o.spacing}${o.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,u.useEffect)(()=>()=>{tw.current.forEach(c3)},[]),(0,u.useLayoutEffect)(()=>{if(e0){let e=e=>{e.target!==e4.current&&(e4.current=null)};return document.addEventListener("pointerdown",e,!0),()=>document.removeEventListener("pointerdown",e,!0)}let e=e4.current;e4.current=null,e?.isConnected&&document.activeElement===document.body&&!document.querySelector('[aria-modal="true"]')&&e.focus({preventScroll:!0})},[e0]);let t$=(0,u.useCallback)(async e=>{if(eE.length||!e.startsWith("/")||!ei)return!1;if(e2.current)return!0;e4.current=document.activeElement===tr.current?tr.current:null,e2.current=!0,e1(!0);let t=tb.current?F(tb.current):null;try{var n,r;let t=await ei(e);if(!t.handled)return!1;return t.error||(n=ty.current,r=tw.current.length,0!==r||n.trim()!==e)||tE(),!0}finally{t?.(),e2.current=!1,e1(!1)}},[eE.length,tE,ei]),tI=(0,u.useCallback)(async()=>{var e;let t=ew.trim();(t||eE.length)&&(ea?.(),(!h||cV(e=t)||oQ(e))&&await t$(t)||(!h||t.startsWith("!")&&!eE.length)&&(tE(),l(t,eE.length?eE:void 0)))},[ew,eE,h,t$,l,tE,ea]),tT=eh?null:o0(ew,eL?.text===ew?eL.start:ew.length,eL?.text===ew?eL.end:ew.length),tR=tT?.query??null,tA=tT?.inline===!0,tL=tT?`${tT.start}:${tR}`:null,tP=(()=>{var e;let t,n;if(null===tR)return[];let r=h?cq.filter(e=>e.availableWhileStreaming):cq;return e=tA?(ee??[]).filter(e=>"skill"===e.source):[...r,...ee??[]],((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)===tR||t===tR?0:n.startsWith(tR)||t.startsWith(tR)?1:t.includes(tR)?2:3)}})).filter(e=>{let{rank:t}=e;return t<3})).length>0?n:t.filter(e=>{let{command:t}=e;return cG(t,em).toLowerCase().includes(tR)})).sort((e,t)=>e.rank-t.rank||cY[e.command.source]-cY[t.command.source]||cW.compare(e.command.name,t.command.name)).map(e=>{let{command:t}=e;return t})})(),{commands:tz,groups:tO}=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=0,i=cZ.map(i=>{let s=e.filter(e=>e.source===i),l="skill"!==i||n?s:[...s.filter(e=>!cX(e,t)),...s.filter(e=>cX(e,t))];return{source:i,items:l.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}}(tP,tn,tR??""),tW=1===tP.length?em(tR?"chat.match":"chat.command"):em(tR?"chat.matches":"chat.commands",{count:tP.length}),tF=!!ew.trim()||eE.length>0,tD=eh||ev&&h,t_=eE.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")}(m,x)&&!eZ;(0,u.useEffect)(()=>{0===eE.length&&eJ(!1)},[eE.length]);let tB=(0,u.useCallback)(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(eP({text:e,start:t??e.length,end:n??e.length}),!ed)return void e_(null);let r=t??e.length;e_(rg(e.slice(0,r)))},[ed]),tH=eD?.query??null,tU=u.useMemo(()=>null!==tH&&e3&&e3.cwd===ed?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:20,r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:rv(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:rv(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||rx(e.entry.path)-rx(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(e3.entries,tH):[],[tH,e3,ed]),tK=!!(tH&&e3?.truncated&&e3.cwd===ed);(0,u.useEffect)(()=>{if(!tK||!ed||!tH)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ed)}&q=${encodeURIComponent(tH)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e7({cwd:ed,query:tH,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tK,tH,ed]);let tq=tK&&null!==e9&&e9.cwd===ed&&e9.query===tH,tV=tq?e9.matches:tU,tZ=null===eD?null:`${eD.start}:${+!!eD.quoted}:${eD.query}`;(0,u.useEffect)(()=>{if(null===tZ){eH(!1),eV(0);return}eH(!0),eV(0)},[tZ]);let tJ=null!==eD;(0,u.useEffect)(()=>{if(!tJ||!ed)return;let e=tx.current;e&&e.cwd===ed&&Date.now()-e.fetchedAt<1e4||tv.current===ed||(tv.current=ed,e5(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ed)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{e8({cwd:ed,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>rx(e.path)-rx(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tx.current={cwd:ed,fetchedAt:Date.now()}}).catch(()=>{tx.current=null}).finally(()=>{tv.current=null,e5(!1)}))},[tJ,ed]);let tY=(0,u.useCallback)(e=>{if(!eD)return;let t=tr.current;if(!t)return;let n=t.selectionStart??t.value.length,r=n+(eD.quoted&&'"'===t.value[n]?1:0),i=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eD.quoted),s=eD.start+i.cursorOffset;c_(t,eD.start,r,i.text,i.cursorOffset),e_(rg(t.value.slice(0,s)))},[eD]);(0,u.useEffect)(()=>{eq>=tV.length&&eV(Math.max(0,tV.length-1))},[tV.length,eq]),(0,u.useEffect)(()=>{tf.current.length=tV.length},[tV.length]),(0,u.useEffect)(()=>{eB&&tf.current[eq]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eq,eB]),(0,u.useEffect)(()=>{eX>=X.length&&eQ(Math.max(0,X.length-1))},[X.length,eX]),(0,u.useEffect)(()=>{tg.current.length=X.length},[X.length]),(0,u.useEffect)(()=>{eY&&!er&&tg.current[eX]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eX,eY,er]);let tG=(0,u.useCallback)(e=>{ej(e),eG(!1),eQ(0),e_(null),requestAnimationFrame(()=>{let t=tr.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),cB(t),cH(t))})},[]),tX=(0,u.useCallback)(e=>{var t,n,r;let i,s=tr.current;if(!s)return;let l=o0(s.value,s.selectionStart,s.selectionEnd);if(!l)return;let a=(t=s.value,n=l,r=e,i=`/${r.name} `,n.inline?"skill"!==r.source?null:{text:i+t.slice(0,n.start)+t.slice(n.end),cursor:i.length+n.start}:{text:t.slice(0,n.start)+i+t.slice(n.end),cursor:n.start+i.length});a&&(s.setSelectionRange(0,s.value.length),c_(s,0,s.value.length,a.text,a.cursor),ty.current=s.value,ej(s.value),tB(s.value,a.cursor),eA(!1),eO(0),requestAnimationFrame(()=>{s.focus(),s.setSelectionRange(a.cursor,a.cursor),cB(s)}))},[tB]),tQ=(0,u.useCallback)(()=>{let e=ew.trim();e&&!eE.length&&c&&(tE(),c(e))},[ew,eE,c,tE]),t0=(0,u.useCallback)(e=>{let t=ew.trim();if(!t&&!eE.length)return;if(t.startsWith("!")&&!eE.length)return void tI();ea?.();let n=eE.length?eE:void 0,r=()=>{if(t.startsWith("/")&&eo){tE(),eo(t,"steer"===e?"steer":"followUp",n);return}tE(),"steer"===e&&o?o(t,n):"followup"===e&&p&&p(t,n)};!eE.length&&ei&&cV(t)?t$(t):!eE.length&&ei&&oQ(t)?t$(t).then(e=>{e||r()},()=>r()):r()},[ew,eE,ei,eo,o,p,tE,ea,t$,tI]),t1=(0,u.useCallback)(e=>{let t=tz.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,ez-1);if("right"===e)return Math.min(t,ez+1);let n=th.current[ez];if(!n)return"down"===e?Math.min(t,ez+1):Math.max(0,ez-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,l=-1,a=1/0;for(let n=0;n<=t;n+=1){if(n===ez)continue;let t=th.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-s;if("down"===e?o<=4:o>=-4)continue;let c=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);c<a&&(l=n,a=c)}return l>=0?l:"down"===e?Math.min(t,ez+1):Math.max(0,ez-1)},[tz.length,ez]),t2=(0,u.useCallback)(e=>{let t=e.nativeEvent,n="Enter"===e.key&&!e.shiftKey,r=ev||"ctrlEnter"===ey?n&&(e.ctrlKey||e.metaKey):n,i=ev?r:n,s=Date.now()-tc.current<100,l=to.current||t.isComposing||229===t.keyCode;if(i&&(l||s)){s&&e.preventDefault();return}if(eY&&!er&&!l){if("ArrowDown"===e.key){e.preventDefault(),eQ(e=>Math.min(Math.max(0,X.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eQ(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eG(!1);return}if(("Tab"===e.key||i)&&X[eX]){e.preventDefault(),tG(X[eX]);return}}if(eR&&null!==tR&&!l&&!er){if("ArrowDown"===e.key){e.preventDefault(),eO(t1("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eO(t1("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eO(t1("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eO(t1("left"));return}if("Escape"===e.key){e.preventDefault(),eA(!1);return}let t=tz[ez];if("Tab"===e.key&&t){e.preventDefault(),tX(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 oX(t)&&oQ(e)}(ew,t,h)?(eA(!1),tI()):tX(t);return}}if(eB&&null!==eD&&!er&&!l){if("ArrowDown"===e.key){e.preventDefault(),eV(e=>cF(e,tV.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eV(e=>cF(e,tV.length,-1));return}if("Escape"===e.key){e.preventDefault(),eH(!1);return}if(("Tab"===e.key||i)&&tV[eq]){e.preventDefault(),tY(tV[eq]);return}}if("ArrowUp"===e.key&&!l&&!h&&X.length>0&&0===ew.trim().length){e.preventDefault(),eA(!1),eH(!1),eQ(X.length-1),eG(!0);return}if("Escape"===e.key&&!l&&h&&a){e.preventDefault(),a();return}r&&(e.preventDefault(),h&&(o||p)?t0(e.altKey&&p||!o?"followup":"steer"):tI())},[ev,ey,h,o,p,a,er,eR,tR,tz,ez,tX,t0,tI,t1,eB,eD,tV,eq,tY,eY,X,eX,tG,ew]),t4=(0,u.useCallback)(()=>{td.current=null;let e=tr.current;e&&cB(e)},[]),t3=(0,u.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!eh&&t.length){e.preventDefault(),tk(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,l={};td.current=l,setTimeout(()=>{td.current===l&&(td.current=null,!n.defaultPrevented&&t.isConnected&&c_(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:l,occurrence:a}of t){if(!s||!l)continue;let t=0;for(let n=0;n<=a&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let o=s.replace(/([\\[\]])/g,"\\$1"),c=l.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${o}](${c})`,r=t+s.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===s)return;let l=e.currentTarget,a=l.selectionStart,o=l.value.slice(0,a)+s+l.value.slice(l.selectionEnd);e.preventDefault(),ty.current=o,ej(o),eG(!1),tB(o,a+s.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(a+s.length,a+s.length),cH(l)})},[eh,tk,tB]);(0,u.useEffect)(()=>{if(null===tR){eA(!1),eO(0),tu.current=!1;return}eA(!0),eO(0),!tu.current&&en&&(tu.current=!0,Promise.resolve(en()).catch(()=>{tu.current=!1}))},[tR,tL,en]),(0,u.useEffect)(()=>{if(!eR||!ed)return;let e=!1;return tt({cwd:ed,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ed)}`).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;tt({cwd:ed,values:n})}).catch(()=>{e||tt({cwd:ed,values:{}})}),()=>{e=!0}},[eR,ed]),(0,u.useEffect)(()=>{ez>=tz.length&&eO(Math.max(0,tz.length-1))},[tz.length,ez]),(0,u.useEffect)(()=>{th.current.length=tz.length},[tz.length]),(0,u.useEffect)(()=>{eR&&!er&&th.current[ez]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ez,eR,er]),(0,u.useLayoutEffect)(()=>{if(!eR||null===tR||er)return void eF(null);let e=tp.current;if(e)return cU(e,e=>{eF(t=>t===e?t:e)})},[eR,tR,er]),(0,u.useLayoutEffect)(()=>{if(!eB||null===eD||er)return void eK(null);let e=tm.current;if(e)return cU(e,e=>{eK(t=>t===e?t:e)})},[eB,eD,er]);let t8=x&&x.length>0?x.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})):Object.entries(g??{}).map(e=>{let[t,n]=e;return{provider:m?.provider??"unknown",modelId:t,name:n}}),t6=A?Math.max(0,A.tokensBefore-A.estimatedTokensAfter):0,t5=A?`${A.reason&&"manual"!==A.reason?`${A.reason[0].toUpperCase()}${A.reason.slice(1)} `:em("chat.compacted")} ${cK(A.tokensBefore)} -> ${cK(A.estimatedTokensAfter)} tokens (${em("chat.tokensSaved",{saved:cK(t6)})})`:null,t9=Object.entries(cz).find(e=>{let[,t]=e;return t===(L??"configured")})?.[0]??"configured",t7=em(cO[t9]);(0,u.useEffect)(()=>{let e=e=>{ti.current&&!ti.current.contains(e.target)&&eS(!1),ts.current&&!ts.current.contains(e.target)&&eN(!1),!tl.current||tl.current.contains(e.target)||tr.current?.contains(e.target)||eG(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,u.useEffect)(()=>{h&&eS(!1)},[h]);let ne=(0,u.useRef)(-1/0);(0,u.useLayoutEffect)(()=>{if(h)return()=>{ne.current=performance.now()}},[h]);let nt=e=>{var t,n;return t=e.detail,n=performance.now()-ne.current,t>0&&n<600};(0,u.useEffect)(()=>{ev||eN(!1)},[ev]);let nn=h&&!eI?(0,d.jsxs)("div",{className:"chat-composer-run-actions",children:[c&&(0,d.jsx)("button",{type:"button",className:"chat-composer-run-button chat-composer-side-chat",onClick:tQ,disabled:!ew.trim()||eE.length>0,title:em("chat.sideChatHint"),"aria-label":em("chat.sideChat"),children:(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M21 11.5a8.5 8.5 0 0 1-8.5 8.5H4l1.5-4A8.5 8.5 0 1 1 21 11.5Z"}),(0,d.jsx)("path",{d:"M12.5 7.5v8M8.5 11.5h8"})]})}),o&&(0,d.jsxs)("button",{type:"button",className:"chat-composer-run-button",onClick:()=>t0("steer"),disabled:!tF,title:em("chat.steerHint"),"aria-label":em("chat.steer"),children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M5 12h14m-6-6 6 6-6 6"})}),(0,d.jsx)("span",{className:"chat-composer-run-label",children:em("chat.steer")})]}),p&&(0,d.jsxs)("button",{type:"button",className:"chat-composer-run-button",onClick:()=>t0("followup"),disabled:!tF,title:`${em("chat.followUpHint")} (${ev?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":em("chat.followUp"),"aria-keyshortcuts":ev?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M4 6h16M4 12h10M4 18h7m7-3v6m-3-3h6"})}),(0,d.jsx)("span",{className:"chat-composer-run-label",children:em("chat.followUp")})]})]}):(0,d.jsxs)("button",{className:eh?void 0:"chat-composer-send",onClick:tI,disabled:!ew.trim()&&!eE.length,title:em("chat.send"),"aria-label":em("chat.send"),style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,...ev?{width:36,height:36,padding:0}:{padding:"7px 14px"},background:ew.trim()||eE.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ew.trim()||eE.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ew.trim()||eE.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ew.trim()||eE.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M7 12V2M3 6l4-4 4 4"})}),eh&&!ev&&em("chat.send")]});return(0,d.jsxs)("fieldset",{disabled:e0,"aria-busy":e0,className:eh?void 0:"chat-input-shell",style:{...eh?{flexShrink:0}:{display:"flex",flexDirection:"column",minHeight:0},minWidth:0,margin:0,border:0,background:"transparent",padding:eh?0:"0 16px 8px",paddingLeft:eh?0:ev?16:52,opacity:e0?.5:1,transition:"opacity 0.15s"},children:[!eh&&(0,d.jsx)("input",{ref:ta,type:"file",accept:eu?void 0:"image/*",multiple:!0,style:{display:"none"},onChange:tS}),(0,d.jsxs)("div",{style:{...eh?void 0:{display:"flex",flexDirection:"column",minHeight:0,width:"100%"},maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,d.jsx)(c5,{cwd:b,onFork:y}),(0,d.jsx)(c9,{error:v}),(0,d.jsx)(c7,{warnings:w}),t_&&(n=x?.find(e=>e.provider===m?.provider&&e.id===m?.modelId),(0,d.jsx)(c6,{tone:"warning",title:em("chat.imageNotSupportedTitle"),body:em("chat.imageNotSupportedBody",{model:n?.name||m?.modelId||""}),onClose:()=>eJ(!0)})),(G?.steering.length??0)+(G?.followUp.length??0)>0&&(0,d.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,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,d.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:em("chat.queued",{count:(G?.steering.length??0)+(G?.followUp.length??0)})}),Q&&(0,d.jsxs)("button",{onClick:Q,title:em("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,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,d.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),em("chat.recall")]})]}),(0,d.jsxs)("div",{style:{maxHeight:"min(180px, calc(var(--app-viewport-height, 100dvh) * 0.25))",overflowY:"auto",overscrollBehavior:"contain"},children:[G?.steering.map((e,t)=>(0,d.jsx)(c8,{kind:"steer",text:e},`steer-${t}`)),G?.followUp.map((e,t)=>(0,d.jsx)(c8,{kind:"follow-up",text:e},`followup-${t}`))]})]}),Y&&(0,d.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,d.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,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]}),em("chat.retrying",{attempt:Y.attempt,max:Y.maxAttempts}),Y.errorMessage&&(0,d.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",Y.errorMessage]})]}),t5&&(0,d.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,d.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,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),t5]}),T&&(0,d.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,d.jsx)("span",{style:{minWidth:0,flex:1,padding:R?"4px 0":0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:T}),R&&(0,d.jsx)(ro,{onClick:R,title:em("chat.dismissCompactError")})]}),(0,d.jsxs)("div",{className:eh?void 0:"chat-composer-card","data-bash":eI||void 0,"data-queuing":h&&!!(o||p)||void 0,children:[eE.length>0&&(0,d.jsx)("div",{className:"chat-composer-attachments",style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:eE.map((e,t)=>(0,d.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,d.jsx)(lC,{src:e.previewUrl,children:(0,d.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,d.jsx)("button",{type:"button",onClick:()=>tC(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,d.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,d.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,d.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,d.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eY&&!er&&X.length>0&&(0,d.jsxs)("div",{ref:tl,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,d.jsx)("div",{title:em("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,d.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,d.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,d.jsx)("path",{d:"M3 4v5h5"}),(0,d.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,d.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:X.map((e,t)=>{let n=t===eX;return(0,d.jsxs)("button",{ref:e=>{tg.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tG(e)},onMouseEnter:()=>eQ(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,d.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,d.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eR&&null!==tR&&!er&&(0,d.jsxs)("div",{ref:tp,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===eW?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eW}px)`},children:[(0,d.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,d.jsx)("span",{children:et?em("chat.loadingCommands"):em("chat.slashCommands",{label:tW})}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:em("chat.tabEnter")})]}),(0,d.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:et||0!==tP.length?tO.map(e=>(0,d.jsxs)("section",{style:{marginBottom:12},children:[(0,d.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,d.jsx)("span",{children:em(cJ[e.source])}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,d.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,r=n===ez,i=cX(t,tn);return(0,d.jsxs)("button",{ref:e=>{th.current[n]=e},type:"button",onMouseDown:e=>{e.preventDefault(),tX(t)},onMouseEnter:()=>eO(n),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:7,background:r?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:r?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,d.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",t.name,i&&(0,d.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:em("chat.dormant")})]}),t.description&&(0,d.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:cG(t,em)})]},`${t.source}:${t.name}`)})})]},e.source)):(0,d.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:em("chat.noCommands")})})]}),eB&&null!==eD&&!er&&(r=e6&&(!e3||e3.cwd!==ed),i=1===tV.length?em("chat.match"):em("chat.matches",{count:tV.length}),s=e3?.truncated&&!tq?eD.query?em("chat.searchingAll"):em("chat.indexTruncated"):"",(0,d.jsxs)("div",{ref:tm,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===eU?"min(48vh, 400px)":`min(48vh, 400px, ${eU}px)`},children:[(0,d.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,d.jsx)("span",{children:r?em("chat.loadingFiles"):em("chat.files",{label:i,hint:s})}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:em("chat.tabEnter")})]}),(0,d.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:r||0!==tV.length?tV.map((e,t)=>{let n=t===eq,r=e.path.split("/").pop()??e.path,i=e.path.slice(0,e.path.length-r.length);return(0,d.jsxs)("button",{ref:e=>{tf.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tY(e)},onMouseEnter:()=>eV(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,d.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,d.jsx)(ru,{size:14}):rm(r,14)}),(0,d.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[i&&(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:i}),r,e.isDir&&(0,d.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,d.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tK&&!tq?em("chat.searching"):em("chat.noMatchingFiles")})})]})),(0,d.jsxs)("div",{className:eh?void 0:"chat-composer-entry",style:{minWidth:0,display:"flex",flexDirection:tD?"column":"row",gap:8,alignItems:tD?"stretch":"center",background:"transparent",border:"none",padding:eh?0:"14px 16px 4px",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,d.jsx)("textarea",{ref:tr,className:"chat-input-textarea","aria-label":eh?em("chat.askInSideChat"):void 0,value:ew,onChange:e=>{ty.current=e.target.value,ej(e.target.value),eG(!1),tB(e.target.value,e.target.selectionStart,e.target.selectionEnd)},onSelect:e=>{let t=e.currentTarget;tB(t.value,t.selectionStart,t.selectionEnd)},onKeyDown:t2,onCompositionStart:()=>{to.current=!0},onCompositionEnd:e=>{to.current=!1,tc.current=Date.now();let t=e.currentTarget;tB(t.value,t.selectionStart,t.selectionEnd)},onInput:t4,onPaste:t3,placeholder:I?em("chat.compactingPlaceholder"):h&&(o||p)?em("chat.steerPlaceholder"):h?em("chat.agentPlaceholder"):em("chat.messagePlaceholder"),rows:1,style:{flex:tD?"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:eh?96:44,maxHeight:200,overflow:"auto"}}),eh&&nn]})]}),eI&&(0,d.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eT?"var(--text-muted)":"var(--accent)",marginTop:4},children:[em("chat.shell")," \xb7 ",eT?em("chat.outputLocal"):em("chat.outputModel")]}),!eh&&(0,d.jsxs)("div",{className:"chat-composer-footer",children:[(0,d.jsxs)("div",{className:"chat-input-controls",style:{marginTop:ev?4:8,display:ev?"grid":"flex",gridTemplateColumns:ev?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,d.jsxs)("div",{className:"chat-composer-model",style:{flex:ev?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,d.jsx)("button",{className:"chat-composer-attach",onClick:()=>ta.current?.click(),title:em("chat.attachFiles"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:eb,height:eb,padding:0,background:"none",border:"none",borderRadius:9,color:eE.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=eE.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eE.length?"var(--accent)":"var(--text-muted)"},children:(0,d.jsxs)("svg",{width:ev?18:15,height:ev?18:15,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,d.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,d.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(W||(t8.length>0||m||v)&&S)&&(0,d.jsx)(cL,{options:t8,model:m,onModelChange:S,allOptions:j?.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),onShowAll:k,isStreaming:h,modelSwitching:C,isAutoModelSelection:f,defaultModel:N,onSetDefaultModel:E,thinkingLevel:z,isAutoThinkingSelection:O,availableThinkingLevels:D,thinkingLevelMap:_,onThinkingLevelChange:W,savedDefaultThinkingLevel:V,onSetDefaultThinkingLevel:J})]}),(0,d.jsxs)("div",{ref:ts,className:"chat-composer-options",style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ev?0:"auto"},children:[ev&&(0,d.jsx)("button",{type:"button",title:eC?void 0:em("chat.moreControls"),"aria-label":em("chat.moreControls"),"aria-expanded":eC,"aria-hidden":eC||void 0,tabIndex:eC?-1:void 0,onClick:()=>{eN(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:eb,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:eC?"default":"pointer",fontSize:12,fontWeight:500,visibility:eC?"hidden":"visible",pointerEvents:eC?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eC||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eC||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:em("chat.moreControls")}),(0,d.jsxs)("div",{className:"chat-composer-options-list",style:{display:ev?eC?"flex":"none":"flex",alignItems:"center",gap:ev?1:2,...ev?{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:[!h&&P&&(0,d.jsxs)("div",{ref:ti,style:{position:ev?"static":"relative"},children:[(0,d.jsxs)("button",{className:"chat-composer-control chat-composer-tool",onClick:e=>{h||nt(e)||eS(e=>!e)},disabled:h,title:em("chat.changeToolPreset")+`: ${t7}`,"aria-label":em("chat.changeToolPreset"),"aria-expanded":ek,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ev?"0 10px":"8px 12px",width:ev?"auto":void 0,height:eb,background:ek?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:h?"not-allowed":"pointer",fontSize:12,opacity:h?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{h||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ek?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.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"})}),(!ev||eC)&&(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:"configured"===t9?em("chat.toolsButton"):t7}),(0,d.jsx)("span",{className:"chat-composer-caret","aria-hidden":"true"})]}),ek&&(0,d.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:ev?"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:cP.map(e=>{let t,n=cz[e],r=(L??"configured")===n;return t="configured"===e?em("chat.configuredTools"):"chat-only"===e?em("chat.chatOnly"):"read-only"===e?em("chat.readOnlyTools",{count:4}):"default"===e?em("chat.builtInTools",{count:4}):em("chat.allBuiltInTools"),(0,d.jsxs)("button",{onClick:()=>{eS(!1),r||P(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,d.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,d.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,d.jsx)("span",{style:{width:10,flexShrink:0}}),(0,d.jsx)("span",{style:{flex:1},children:em(cO[e])}),(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),!ev&&(0,d.jsx)("div",{className:"chat-composer-usage",children:ep}),(!h||I)&&M&&(0,d.jsx)("div",{className:"chat-composer-compact",children:(0,d.jsx)("button",{className:"chat-composer-utility",onClick:I?$:e=>{nt(e)||M()},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ev?"0 10px":"8px 12px",width:ev?"auto":void 0,height:eb,background:I?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:I?"#ef4444":"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=I?"#ef4444":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=I?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=I?"#ef4444":"var(--text-muted)"},title:I?em("chat.stopCompaction"):em("chat.compactContext"),"aria-label":I?em("chat.stopCompaction"):em("chat.compactContext"),children:I?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,d.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ev||eC)&&(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:em("chat.compacting")})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,d.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,d.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,d.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),ev&&eC&&(0,d.jsx)("span",{style:{whiteSpace:"nowrap"},children:em("chat.compact")})]})})}),h&&(0,d.jsxs)("button",{type:"button",className:"chat-composer-run-button chat-composer-stop",onClick:a,title:em("chat.stopAgent"),"aria-label":em("chat.stopAgent"),children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:(0,d.jsx)("rect",{x:"6.5",y:"6.5",width:"11",height:"11",rx:"2",fill:"currentColor"})}),em("chat.stop")]}),void 0!==el&&(0,d.jsx)("button",{className:"chat-composer-utility chat-composer-sound",onClick:el,title:es?em("chat.disableSound"):em("chat.enableSound"),"aria-label":es?em("chat.disableSound"):em("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:eb,height:eb,padding:0,background:"none",border:"none",borderRadius:9,color:es?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:es?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=es?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=es?"1":"0.55"},children:es?(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,d.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,d.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,d.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,d.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),ev&&eC&&(0,d.jsx)("button",{type:"button",title:em("chat.collapseControls"),"aria-label":em("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eS(!1),eN(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:ev?eb:36,height:eb,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,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,d.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,d.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]}),(0,d.jsx)("div",{className:"chat-composer-submit",children:nn})]})]})]})]})}));function dt(){return(0,d.jsxs)("svg",{className:"new-session-welcome-mark",width:"52",height:"52",viewBox:"0 0 64 64",fill:"none",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M23 10C27 3 38 3 42 11C51 10 58 18 54 26C62 32 59 43 51 46C50 56 39 60 32 54C24 60 13 55 13 46C4 42 3 31 10 25C7 17 14 9 23 10Z"}),(0,d.jsx)("path",{d:"m23 25 5 6-5 6M34 38h9"})]})}var dn=n(88576),dr=n.n(dn);function di(e){let{level:t,children:n,headingIndex:r,onClick:i}=e;return(0,d.jsx)("button",{type:"button",className:dr().heading,"data-level":t,"data-preview-heading-index":r??void 0,disabled:null===r||!i,onClick:e=>{e.stopPropagation(),null!==r&&i?.(r)},children:n})}let ds=[...la??[],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}e.children=e.children.filter(e=>"paragraph"===e.type||"list"===e.type).slice(0,2)}}],dl=[[sz.A,{throwOnError:!1,strict:!1}]];function da(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 dc=(0,u.memo)(function(e){let{markdown:t,onHeadingClick:n,onAnswerClick:r}=e,i=(0,u.useMemo)(()=>s0(t),[t]);return t?(0,d.jsx)("div",{className:dr().outline,children:(0,d.jsx)(sE.oz,{remarkPlugins:ds,rehypePlugins:dl,components:{h1:e=>{let{children:t,node:r}=e;return(0,d.jsx)(di,{level:1,headingIndex:da(r),onClick:n,children:t})},h2:e=>{let{children:t,node:r}=e;return(0,d.jsx)(di,{level:2,headingIndex:da(r),onClick:n,children:t})},h3:e=>{let{children:t,node:r}=e;return(0,d.jsx)(di,{level:3,headingIndex:da(r),onClick:n,children:t})},h4:()=>null,h5:()=>null,h6:()=>null,p:e=>{let{children:t}=e;return(0,d.jsx)("button",{type:"button",className:dr().paragraph,onClick:r,children:t})},blockquote:()=>null,ul:e=>{let{children:t}=e;return(0,d.jsx)("ul",{className:dr().list,children:t})},ol:e=>{let{children:t}=e;return(0,d.jsx)("ol",{className:dr().list,children:t})},pre:()=>null,table:()=>null,hr:()=>null,a:e=>{let{children:t}=e;return(0,d.jsx)(d.Fragment,{children:t})},code:e=>{let{children:t}=e;return(0,d.jsx)(d.Fragment,{children:t})}},children:i})}):null}),dd=(0,u.memo)(function(e){let{messages:t,getStreamingMessage:n,scrollContainer:r,messageRefs:i,onRevealHistory:s,turnsBefore:l,turnAnchors:a}=e,{t:o}=(0,ns.s)(),[c,p]=(0,u.useState)(!1),[h,m]=(0,u.useState)([]),[f,g]=(0,u.useState)(null),[x,v]=(0,u.useState)(600),[b,y]=(0,u.useState)(!1),[w,j]=(0,u.useState)(null),[k,S]=(0,u.useState)(180),C=(0,u.useRef)(!1),N=(0,u.useRef)(null),E=(0,u.useRef)([]),M=(0,u.useRef)({nodes:[],gap:10,fillsHeight:!1}),$=(0,u.useRef)(null),I=(0,u.useRef)(null),T=(0,u.useRef)(null),R=(0,u.useRef)(null),A=(0,u.useRef)(t);A.current=t;let L=(0,u.useRef)(a);L.current=a;let P=(0,u.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:10,fillsHeight:!1};let n=Math.max(1,t),r=Math.min(180,Math.max(0,n-56));if(1===e.length)return{nodes:[{...e[0],topRatio:Math.max(28,n/2)/n}],gap:10,fillsHeight:!1};let i=r/(e.length-1),s=Math.min(10,i),l=Math.max(28,(n-s*(e.length-1))/2);return{nodes:e.map((e,t)=>({...e,topRatio:(l+t*s)/n})),gap:s,fillsHeight:i<=10}})(h,x),[h,x]),{nodes:z,gap:O}=P;M.current=P;let W=(0,u.useCallback)(e=>{T.current={index:e,until:Date.now()+1600},g(e)},[]),F=(0,u.useCallback)((e,t)=>{let n=T.current;if(n&&Date.now()<n.until)return void g(n.index);T.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)},[]),D=(0,u.useCallback)(()=>{let e=r.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,n=E.current;p(t>20),F(e,n)},[r,F]),_=(0,u.useRef)(null),B=(0,u.useCallback)(()=>{_.current||(_.current=setTimeout(()=>{_.current=null;let e=r.current,t=N.current;if(!e||!t)return;let s=i.current,l=e.getBoundingClientRect(),a=[],o=0,c=null,d=n();for(let[t,n]of(d?[...A.current,d]:A.current).entries()){let r=!0===L.current[t];if(!r&&"assistant"!==n.role)continue;let i=null;if(i8(n,r)&&(i=s?.[o]??null,o++),r){c=null;let t=i?.getBoundingClientRect();c={userMessage:n,assistantPreviews:[],scrollTop:t?t.top-l.top+e.scrollTop:null,toolCount:0},a.push(c);continue}if(!c)continue;null===c.scrollTop&&i&&i2(c.userMessage)&&(c.scrollTop=i.getBoundingClientRect().top-l.top+e.scrollTop),c.toolCount+="assistant"===n.role&&Array.isArray(n.content)?n.content.reduce((e,t)=>e+ +("toolCall"===t.type),0):0;let d=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=sn(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(n);d&&c.assistantPreviews.push({markdown:d,element:i})}let u=a.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));v(t.clientHeight),E.current=u,m(u),p(e.scrollHeight-e.clientHeight>20),F(e,u);let h=R.current,f=h?u[h.nodeIndex]:null;if(h&&f){let t=void 0===h.assistantIndex?null:f.targetTurn.assistantPreviews[h.assistantIndex],n=f.targetTurn.scrollTop;if("assistant"===h.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-l.top+e.scrollTop:null}else if("heading"===h.target){let r=void 0===h.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(h.headingIndex),i=r?.getBoundingClientRect();n=i?i.top-l.top+e.scrollTop:null}if(null===n)return;R.current=null,W(f.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[n,W,i,r,F]);(0,u.useEffect)(()=>{let e=r.current;if(e)return e.addEventListener("scroll",D,{passive:!0}),()=>e.removeEventListener("scroll",D)},[r,D]),(0,u.useEffect)(()=>{let e=r.current;if(!e)return;let t=()=>{B(),D()},n=new ResizeObserver(t);return n.observe(e),e.firstElementChild&&n.observe(e.firstElementChild),t(),()=>{n.disconnect(),_.current&&(clearTimeout(_.current),_.current=null)}},[B,r,D]),(0,u.useEffect)(()=>{let e=setTimeout(()=>{B(),D()},50);return()=>clearTimeout(e)},[t.length,a,B,D]);let H=(0,u.useCallback)((e,t)=>{let n=r.current;if(!n)return;if(W(e.index),null===e.targetTurn.scrollTop){R.current={nodeIndex:e.index,target:"user"},s();return}let i=Math.max(0,e.targetTurn.scrollTop-.3*n.clientHeight);n.scrollTo({top:i,behavior:t})},[W,s,r]),U=(0,u.useCallback)((e,t)=>{let n=r.current;if(!n)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){R.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},s();return}let l=n.getBoundingClientRect(),a=i.getBoundingClientRect().top-l.top+n.scrollTop-.3*n.clientHeight;W(e.index),n.scrollTo({top:Math.max(0,a),behavior:"smooth"})},[W,s,r]),K=(0,u.useCallback)(e=>{let{nodes:t,gap:n}=M.current,r=N.current?.clientHeight??0;if(0===t.length||r<=0)return null;let i=Math.max(0,Math.min(r,e*r)),s=t[0].topRatio*r,l=n>0?Math.round((i-s)/n):0,a=Math.max(0,Math.min(t.length-1,l)),o=t[a];return Math.abs(i-o.topRatio*r)>Math.max(10,n/2)?null:o},[]),q=(0,u.useCallback)((e,t,n)=>{let i=r.current;if(!i)return;let l=e.targetTurn.assistantPreviews[t]?.element;if(!l){R.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:n},s();return}let a=l.querySelectorAll("h1, h2, h3").item(n);if(!a)return;let o=i.getBoundingClientRect(),c=a.getBoundingClientRect().top-o.top+i.scrollTop-.3*i.clientHeight;W(e.index),i.scrollTo({top:Math.max(0,c),behavior:"smooth"})},[W,s,r]),V=(0,u.useCallback)(()=>{I.current&&(clearTimeout(I.current),I.current=null)},[]),Z=(0,u.useCallback)(()=>{V(),y(!0)},[V]);(0,u.useEffect)(()=>{try{window.localStorage.removeItem("pi-web:minimap-preview-locked")}catch{}},[]);let J=(0,u.useCallback)(()=>{V(),I.current=setTimeout(()=>{I.current=null,y(!1),j(null)},250)},[V]);(0,u.useEffect)(()=>()=>V(),[V]);let Y=(0,u.useCallback)(e=>{if(!c)return;let t=e.currentTarget.getBoundingClientRect(),n=Math.max(0,Math.min(1,(e.clientY-t.top)/t.height));if(!K(n))return;C.current=!0,Z(),j(n);let r=(e,n)=>{let r=K(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&H(r,n)};r(e.clientY,"smooth");let i=e=>{C.current&&r(e.clientY,"auto")},s=()=>{C.current=!1,window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},[K,H,Z,c]),G=null===w?null:K(w),X=G?.index??null,Q=G??z[f??0],ee=Math.max(8,Math.min((Q?.topRatio??.5)*x-k/2,x-k-8));return((0,u.useEffect)(()=>{if(!b)return;let e=$.current;if(!e)return;e.scrollTop=0;let t=new ResizeObserver(()=>S(e.offsetHeight));return t.observe(e),()=>t.disconnect()},[h,b,X]),c)?(0,d.jsxs)("div",{ref:N,className:dr().rail,role:"navigation","aria-label":o("chatMinimap.title"),"data-chat-minimap":"",onMouseDown:Y,onMouseLeave:J,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||J()},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),n=(e.clientY-t.top)/t.height;j(n),K(n)?Z():J()},children:[l>0&&(0,d.jsx)("div",{className:dr().earlierMarker,"data-minimap-earlier":"","aria-hidden":"true",style:{top:Math.max(0,(z[0]?.topRatio??0)*x-20)}}),z.map(e=>{let t=b&&G?.index===e.index,n=f===e.index,r=null===w?1/0:Math.abs(e.topRatio-w)*x,i=6+22*Math.exp(-(r*r)/400);return(0,d.jsx)("button",{type:"button",className:dr().node,"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,"data-nearest":t?"true":void 0,"aria-label":o("chatMinimap.turn",{count:l+e.index+1}),"aria-current":n?"step":void 0,onFocus:()=>{j(e.topRatio),Z()},onClick:t=>{0===t.detail&&H(e,"smooth")},style:{top:`${100*e.topRatio}%`,height:Math.max(1,Math.min(32,O))},children:(0,d.jsx)("span",{className:dr().marker,style:{"--tick-width":`${i}px`},"aria-hidden":"true"})},e.index)}),b&&Q&&(0,d.jsxs)("div",{ref:$,className:dr().preview,"data-minimap-preview-box":"",style:{top:`clamp(8px, ${ee}px, max(8px, calc(100% - ${k}px - 8px)))`},"aria-label":o("chatMinimap.turn",{count:l+Q.index+1}),onMouseEnter:Z,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:[l>0&&(0,d.jsx)("button",{type:"button",className:dr().earlier,"data-minimap-preview-earlier":"",onClick:()=>r.current?.scrollTo({top:0,behavior:"smooth"}),children:o("chatMinimap.earlierTurns",{count:l})}),[Q].map(e=>{var t;let n=X===e.index;return(0,d.jsxs)("div",{className:dr().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,"data-active":f===e.index?"true":void 0,children:[(0,d.jsxs)("span",{className:dr().number,children:[(0,d.jsx)("span",{"aria-hidden":"true",children:String(l+e.index+1).padStart(2,"0")}),e.targetTurn.toolCount>0&&(0,d.jsx)("span",{className:dr().toolBadge,role:"img",title:o("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),"aria-label":o("chatMinimap.toolCalls",{count:e.targetTurn.toolCount}),children:e.targetTurn.toolCount>99?"99+":e.targetTurn.toolCount})]}),(0,d.jsxs)("div",{className:dr().content,children:[(0,d.jsx)("button",{type:"button",className:dr().user,"data-minimap-preview-user":e.index,onClick:()=>{H(e,"smooth")},children:(0,d.jsx)("span",{className:dr().userText,children:i2(e.targetTurn.userMessage)?o("chatMinimap.extensionTurn",{type:e.targetTurn.userMessage.customType}):"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,d.jsxs)("div",{className:dr().assistant,children:[(0,d.jsx)("button",{type:"button",className:dr().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>U(e,n),"aria-label":o("chatMinimap.locateAssistant"),title:o("chatMinimap.locateAssistant"),children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M5 4v9a4 4 0 0 0 4 4h10m-4-4 4 4-4 4"})})}),(0,d.jsx)(dc,{markdown:t.markdown,onAnswerClick:()=>U(e,n),onHeadingClick:t=>q(e,n,t)})]},n))]})]},e.index)})]})]}):null});function du(e){let{rootRef:t,chatInputRef:n,startSideChat:r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)(null),[a,o]=(0,u.useState)(!1),[c,p]=(0,u.useState)(!1),[h,m]=(0,u.useState)(null),f=(0,u.useRef)(null),x=(0,u.useRef)(null),v=(0,u.useCallback)(()=>{l(null),o(!1),m(null)},[]);(0,u.useEffect)(()=>{if(a)return;let e=e=>{let n=t.current;if(!n||!(e.target instanceof Node)||!n.contains(e.target))return;let r=window.getSelection(),i=r?.rangeCount?r.getRangeAt(0):null;if(!r||r.isCollapsed||!i||!n.contains(i.commonAncestorContainer))return void l(null);let s=r.toString().trim();if(!s)return void l(null);let a=i.getBoundingClientRect();l({text:s,top:Math.min(window.innerHeight-44,a.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,a.left+a.width/2))})};return document.addEventListener("pointerup",e),()=>document.removeEventListener("pointerup",e)},[t,a]),(0,u.useEffect)(()=>{a&&s&&x.current?.insertIfEmpty(oY(s.text))},[a,s]),(0,u.useLayoutEffect)(()=>{let e=f.current;if(!e||!s)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(s.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(s.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)}},[s,a,h]),(0,u.useEffect)(()=>{if(!s)return;let e=e=>{a||f.current?.contains(e.target)||v()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),c||v())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[s,a,c,v]);let b=(0,u.useCallback)(()=>{s&&(n?.current?.insertQuote(oY(s.text)),v())},[n,s,v]),y=(0,u.useCallback)(async e=>{if(r&&!c&&e.trim()&&s){p(!0),m(null);try{let t=await r(e,s.text);if(!t)return void v();x.current?.restoreSubmission(e),m(t)}catch(t){x.current?.restoreSubmission(e),m(t instanceof Error?t.message:String(t))}finally{p(!1)}}},[s,c,v,r]);return s?(0,g.createPortal)((0,d.jsx)("div",{ref:f,role:a?"dialog":"toolbar","aria-label":i(a?"chat.newQuoteChat":"chat.selectionActions"),style:{position:"fixed",top:s.top,left:s.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:a?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:a?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:a?(0,d.jsxs)("fieldset",{disabled:c,"aria-busy":c,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,d.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:i("chat.askInSideChat")}),(0,d.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:i("i18n.close"),"aria-label":i("i18n.close"),disabled:c,onClick:v,style:{border:"none"},children:(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,d.jsx)(de,{ref:x,compact:!0,onSend:y,onAbort:v,isStreaming:!1}),h&&(0,d.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:h})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:i("chat.quoteSelection"),"aria-label":i("chat.quoteSelection"),onPointerDown:e=>e.preventDefault(),onClick:b,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,d.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,d.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,d.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,d.jsx)("span",{children:i("chat.quoteSelection")})]}),r&&(0,d.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:i("chat.askInSideChat"),"aria-label":i("chat.askInSideChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{o(!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,d.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,d.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,d.jsx)("span",{children:i("chat.askInSideChat")})]})]})}),document.body):null}var dp=n(42790);function dh(e){let{text:t}=e,n=(0,u.useMemo)(()=>{let e=new dp.v;e.use_classes=!0;let n=t.replace(iU,"");return e.ansi_to_html(n).replaceAll('<a href="','<a target="_blank" rel="noopener noreferrer" href="')},[t]);return(0,d.jsx)("span",{dangerouslySetInnerHTML:{__html:n}})}function dm(e){let t,n,r,{widgets:i,children:s}=e,{t:l}=(0,ns.s)(),a=(0,u.useId)(),o=(0,u.useRef)(null),c=(0,u.useRef)(new Map),[p,h]=(0,u.useState)(()=>i.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[m,f]=(0,u.useState)(()=>new Set);if((0,u.useEffect)(()=>{var e;let t=new Map(i.map(e=>[e.key,[...e.lines]])),n=(e=o.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(o.current=t,c.current))t.has(e)||(clearTimeout(n),c.current.delete(e));for(let e of(f(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=c.current.get(e);t&&clearTimeout(t),c.current.set(e,setTimeout(()=>{c.current.delete(e),f(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[i]),(0,u.useEffect)(()=>()=>{for(let e of c.current.values())clearTimeout(e);c.current.clear()},[]),0===i.length)return null;let g=i.find(e=>e.key===p&&e.lines.length>0);return(0,d.jsxs)(d.Fragment,{children:[g&&(0,d.jsx)("div",{className:"extension-widget-panels",children:(t=i.indexOf(g),n=`${a}-trigger-${t}`,r=`${a}-panel-${t}`,(0,d.jsxs)("section",{id:r,className:"extension-widget-panel","aria-labelledby":n,children:[(0,d.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,d.jsx)("pre",{className:"extension-widget-content",children:(0,d.jsx)(dh,{text:g.lines.join("\n")})})]},g.key))}),(0,d.jsxs)("div",{className:"extension-status-row",children:[(0,d.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:i.map((e,t)=>{let n=e.lines.length>0,r=n&&e.key===g?.key,i=m.has(e.key),s=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),o=l("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${a}-trigger-${t}`,u=`${a}-panel-${t}`,p=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,d.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,d.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,d.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,d.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,d.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${r?" is-expanded":""}${i?" is-updating":""}`,"aria-controls":u,"aria-expanded":r,"aria-label":`${o}: ${e.key}, ${s}`,title:`${e.key} - ${o} - ${r?l("i18n.collapse"):l("i18n.expand")}`,onClick:()=>{h(t=>{var n;return t===(n=e.key)?null:n})},children:p},e.key):(0,d.jsx)("div",{className:`extension-widget-trigger${i?" is-updating":""}`,"aria-label":`${o}: ${e.key}, ${s}`,title:`${e.key} - ${o}`,children:p},e.key)})}),s]})]})}let df="command:";function dg(e){let{statuses:t,widgets:n=[],onCommand:r,commandsDisabled:i=!1}=e,s=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(df))return null;let t=e.slice(df.length).trim();return t.length>1&&t.startsWith("/")?t:null}(n.key);if(r){let n=iK(e).replace(/\s+/g," ").trim();t.push({kind:"command",command:r,label:n||r})}else iK(e).trim()&&t.push({kind:"text",text:e})}return t}(t);if(0===s.length&&0===n.length)return null;let l=s.some(e=>"command"===e.kind),a=s.map(e=>"text"===e.kind?iK(e.text):e.label).join(" "),o=s.length>0?(0,d.jsx)("div",{role:"status",className:"extension-status-line","aria-label":a,title:a,children:(0,d.jsx)("span",{className:"extension-status-text",children:s.map((e,t)=>"text"===e.kind?(0,d.jsx)("span",{className:"extension-status-item",children:(0,d.jsx)(dh,{text:e.text})},t):(0,d.jsx)("button",{type:"button",className:"extension-status-item extension-status-command",disabled:!r||i,title:`${e.label} \xb7 ${e.command}`,"aria-label":`${e.label} (${e.command})`,onClick:()=>r?.(e.command),children:e.label},t))})}):null;return(0,d.jsx)("div",{className:`extension-status-shelf${n.length>0?" has-widgets":""}${s.length>0?" has-status":""}${l?" has-commands":""}`,children:n.length>0?(0,d.jsx)(dm,{widgets:n,children:o}):o})}function dx(e,t){return e?.kind==="running_tools"&&e.tools.length>0?e:t?{kind:"waiting_model"}:{kind:"running_command"}}let dv={owner:null,sessionId:null,phase:"idle",result:null},db=dv,dy=0,dw=new Set;function dj(e){db=e,dw.forEach(e=>e())}let dk={subscribe:e=>(dw.add(e),()=>{dw.delete(e)}),getSnapshot:()=>db,getServerSnapshot:()=>dv,update(e,t,n){if(db.owner===e&&db.sessionId===t&&db.phase===n)return;let r="idle"===db.phase&&"idle"!==n;dj({owner:e,sessionId:t,phase:n,result:db.owner!==e||r?null:db.result})},finish(e,t){db.owner===e&&(db.result?.kind!=="error"||"complete"!==t)&&dj({...db,result:{sequence:++dy,kind:t}})},release(e){db.owner===e&&dj(dv)}};function dS(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}function dC(e,t){return e.every(e=>t.has(e.id))?e:e.filter(e=>t.has(e.id))}function dN(e,t){return e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}function dE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function dM(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(!dE(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=dE(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=dE(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 d$(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 dI 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 dT(e){return e instanceof dI&&"prompt_rejected"===e.code&&!1===e.accepted}function dR(e){return`/api/agent/${encodeURIComponent(e)}?systemPrompt=0`}async function dA(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 dI(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted,d$(r)??void 0);return r.data}let dL={not_found:"sideChat.error.notFound",unsaved:"sideChat.error.unsaved",empty:"sideChat.error.empty",subagent:"sideChat.error.subagent",side:"sideChat.error.side"};async function dP(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 dL?t(dL[i.code]):i?.error??`HTTP ${r.status}`}}async function dz(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 dO(){return globalThis.__piSessionViewCache||(globalThis.__piSessionViewCache=new Map),globalThis.__piSessionViewCache}let dW=new WeakMap;function dF(e){let t,n=dW.get(e);if(void 0!==n)return n;try{t=JSON.stringify(e).length}catch{t=Number.MAX_SAFE_INTEGER}return dW.set(e,t),t}function dD(e){let t=dO().get(e);return t?Date.now()-t.savedAt>6e5?(dO().delete(e),null):(dO().delete(e),dO().set(e,t),t):null}function d_(e){if(!e.sessionId||!e.revision)return!1;let t=dO();t.delete(e.sessionId);let n={...e,savedAt:Date.now()};return!(dF(n)>0x2000000)&&(t.set(n.sessionId,n),!function(){let e=dO();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+=dF(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-=dF(r))}}(),dO().has(n.sessionId))}function dB(e){dO().delete(e)}var dH=n(14755);let dU="pi-tool-preset";function dK(){try{return window.localStorage}catch{return null}}function dq(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 dV(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,dq(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),dq(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function dZ(e){return e>=999500?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function dJ(e){return e>0?e>=.01?`$${e.toFixed(2)}`:"<$0.01":null}function dY(e){if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}function dG(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 dX(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(dG).filter(Boolean)}):JSON.stringify({text:"",images:[]})}let dQ=(e,t)=>`live:${e??""}:${t}`;class d0 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 d1{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 d0("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 d0?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){if(this.endedSessionId===e)throw new d0("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 d0("closed")}if(1===t.source.readyState)return;this.lastClose={reason:"stuck",at:Date.now()},this.discard(t,new d0("closed"))}}open(e){let t,n,r;this.current&&(this.lastClose={reason:"replaced",at:Date.now()},this.discard(this.current,new d0("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 d0("closed",e)}this.opens+=1;let i=!1,s=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(c,new d0("ready_timeout"),"ready_timeout")},this.options.readinessTimeoutMs),a={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},o=Date.now(),c={sessionId:e,source:t,attempt:a,watchdog:null,openedAt:o,connectedAt:null,lastSeenAt:null,lastHeartbeatAt:null,events:0};return this.current=c,t.onmessage=t=>{let n;if(this.current===c){c.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){c.lastHeartbeatAt=c.lastSeenAt;return}if("connected"===n.type){c.connectedAt??=c.lastSeenAt,a.ready=!0,a.succeed(),this.stopRetrying();let e=this.options.staleAfterMs;e&&null===c.watchdog&&(c.watchdog=setInterval(()=>{Date.now()-(c.lastSeenAt??o)>e&&this.fail(c,new d0("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(c,new d0("startup_error",e),"startup_error");return}c.events+=1,this.options.onEvent(n)}},t.onerror=()=>{this.fail(c,new d0("closed"),"error")},c}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 d2(e){return!!e&&"unanswered"!==e&&!!(e.running||e.awaitingInput||e.subagentsActive)}function d4(e){return"u"<typeof document?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}let d3=()=>"hidden"===document.visibilityState,d8=()=>!1;function d6(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function d5(e){return("tool_execution_start"===e.type||"tool_execution_update"===e.type||"tool_execution_end"===e.type)&&"string"==typeof e.parentToolCallId&&""!==e.parentToolCallId}function d9(e){return("message_start"===e.type||"message_end"===e.type)&&d6(e.message)&&"system"===e.message.role}function d7(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let ue=/^(?:custom-ui|extension-widget):/;function ut(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return e+t>=n-r}let un={isStreaming:!1,streamingMessage:null};function ur(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 ui(){let e=un,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=dM(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 ur(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return ur(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return ur(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return ur(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return ur(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return ur(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return ur(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 ur(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 ur(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return un;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 us(e,t){let n=e.lastIndexOf(t);return -1===n?e:[...e.slice(0,n),...e.slice(n+1)]}function ul(e,t){return e.reduce((e,n)=>"user"===n.role&&dX(n)===t?e+1:e,0)}function ua(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function uo(e){return e&&"auto"!==e?e:null}let uc=new Map,ud=new Map;function uu(e,t){if(t){uc.set(e,t),ud.has(e)||ud.set(e,F(e));return}uc.delete(e),ud.get(e)?.(),ud.delete(e)}let up=[2e3,5e3,1e4],uh=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 um(e){return new Promise(t=>setTimeout(t,e))}function uf(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ug(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:uf(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:uf(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=uf(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function ux(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 uv(e,t){let[n,r]=(0,u.useState)(()=>t(e.getState()));return(0,u.useLayoutEffect)(()=>{let n=()=>r(t(e.getState()));return n(),e.subscribe(n)},[e,t]),n}let ub=e=>e.isStreaming,uy=e=>!!e.streamingMessage?.content.length,uw=e=>e.streamingMessage;function uj(e){let t=getComputedStyle(e);return Math.max(0,["paddingTop","paddingBottom","borderTopWidth","borderBottomWidth"].reduce((e,n)=>e-(parseFloat(t[n])||0),e.getBoundingClientRect().height))}let uk="pi-web:done-chimes";function uS(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){try{return window.localStorage}catch{return null}}();if(0===e.length)return!1;if(!r)return!0;try{let i=function(e){let t=e.getItem(uk);if(!t)return{};try{let e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return{};let n={};for(let[t,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&(n[t]=r);return n}catch{return{}}}(r),s=e.filter(e=>!("number"==typeof i[e]&&i[e]>=t));if(0===s.length)return!1;for(let e of s)i[e]=n;let l=Object.entries(i).filter(e=>{let[,t]=e;return n-t<=864e5}).sort((e,t)=>t[1]-e[1]).slice(0,200);return r.setItem(uk,JSON.stringify(Object.fromEntries(l))),!0}catch{return!0}}function uC(e){let t,{messageCount:n,toolCallCount:r,durationMs:i,cost:s,cacheMisses:l,defaultExpanded:a=!1,reveal:o=!1,children:c,t:p}=e,[h,m]=(0,u.useState)(a);(0,u.useLayoutEffect)(()=>{o&&m(!0)},[o]);let f=[`${n} ${p(1===n?"chat.message":"chat.messages")}`];r>0&&f.push(`${r} ${p(1===r?"chat.toolCall":"chat.toolCalls")}`),void 0!==i&&f.push(p("chat.turnDuration",{time:sN(i)})),void 0===s||h||o||f.push(`$${s.toFixed(4)}`);let g=l&&!(h||o)?(t={count:l.count,tokens:aQ(l.missedTokens),cost:a1(p,l.missedCost)},p(1===l.count?"transcriptNotice.foldCacheMiss":"transcriptNotice.foldCacheMisses",t)):void 0;return(0,d.jsxs)("div",{className:"process-details-group",style:{marginBottom:14},children:[(0,d.jsxs)("button",{type:"button",className:"process-details-toggle","aria-expanded":h||o,"aria-label":[p("chat.processDetails"),...f,...g?[g]:[]].join(" \xb7 "),onClick:()=>m(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:p(h?"chat.collapseProcess":"chat.expandProcess"),children:[(0,d.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:h?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,d.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[(0,d.jsx)("span",{className:"process-details-label",children:p("chat.processDetails")}),(0,d.jsx)("span",{"aria-hidden":"true",children:" \xb7 "}),f.join(" \xb7 "),g&&(0,d.jsx)("span",{style:{color:a0},children:` \xb7 ${g}`})]})]}),(0,d.jsx)(rf,{open:h||o,children:(0,d.jsx)("div",{className:"process-details-content",style:{marginTop:8},children:c})})]})}function uN(e){let t,{session:r,searchTarget:i,onSearchTargetHandled:s,initialScrollPosition:l,onScrollPositionChange:a,sessionRunning:o,newSessionCwd:c,newSessionDraftKey:p,newSessionContextBar:m,newSessionProjectName:f,onChooseNewSessionProject:g,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:y,onSessionEnded:w,onToolEnd:j,onAttentionNeeded:k,onSessionCreated:S,onSessionForked:N,panel:E=!1,onSideSession:M,modelsRefreshKey:$,chatInputRef:I,onBranchDataChange:T,onSystemPromptChange:R,onSystemToolsChange:A,onSystemInfoLoaderChange:L,onDebugSnapshotReaderChange:P,onSessionStatsChange:z,onSessionStatsPanelOpen:O,sessionStatsControl:W,onOpenSettings:F,onContextUsageChange:D,onOpenFile:_,onFilesUploaded:K,onOpenSubagent:q,quoteSelectionEnabled:J=!1,initialPrompt:Y,onInitialPromptConsumed:G,soundEnabled:X=!0,onSoundToggle:Q,playDoneSound:ee=()=>{},unlockAudio:et,holdAudio:en}=e,{t:er}=(0,ns.s)(),{theme:ei}=lH(),es=nf(),el=!v(r?.relation),ea=(0,u.useRef)(ee);ea.current=ee;let eo=(0,u.useRef)(X);eo.current=X;let ec=(0,u.useRef)(!1),[ed]=(0,u.useState)(()=>Symbol("active-chat")),eu=(0,u.useCallback)(e=>{if(e.subagentsActive||dk.finish(ed,e.aborted?"stopped":e.failed?"error":"complete"),el&&eo.current&&!e.aborted&&!e.failed&&!e.subagentsActive){let e=tu.current??r?.id;(!e||uS([e],Date.now()-3e3))&&ea.current()}y?.(e)},[ed,el,y,r?.id]),ep=(0,u.useRef)(i?null:l??null),[eh,em]=(0,u.useState)(()=>{let e=ep.current;return e&&!e.atBottom?e:null}),[ef,eg]=(0,u.useState)(!1),{loading:ex,error:ev,messages:eb,activeToolResults:ey,toolClocks:ew,entryIds:ej,messageKeys:ek,liveUserEntryIds:eS,historyCursor:eC,hasEarlierMessages:eN,earlierTurnCount:eE,streamingStore:eM,agentRunning:e$,bashRunning:eI,pendingBash:eT,modelNames:eR,modelList:eA,modelError:eL,missingCwd:eP,canForkMissingCwd:ez,modelScopeWarnings:eO,isModelScopeActive:eW,allModelList:eF,modelThinkingLevels:eD,modelThinkingLevelMaps:e_,toolPreset:eB,thinkingLevel:eH,retryInfo:eU,contextUsage:eK,forkingEntryId:eq,isCompacting:eV,compactError:eZ,compactResult:eJ,displayModel:eY,modelSwitching:eG,sessionStats:eX,slashCommands:eQ,slashCommandsLoading:e0,queuedMessages:e1,notices:e2,extensionDialog:e4,waitingExtensionDialogCount:e3,extensionCustomUi:e8,waitingExtensionCustomUiCount:e6,extensionStatuses:e5,extensionWidgets:e9,respondToExtensionUi:e7,sendExtensionCustomInput:te,setNoticePaused:tt,addNotice:tn,isAutoModelSelection:tr,isAutoThinkingSelection:ti,defaultModel:ts,savedDefaultThinkingLevel:tl,agentPhase:ta,isNew:to,editEntryId:tc,showScrollToBottom:td,sessionIdRef:tu,scrollContainerRef:tp,lastUserMsgRef:th,promptAnchorActive:tm,handleSend:tf,handleAbort:tg,startSideChat:tx,handleFork:tv,forkIntoCwd:tb,handleEditContent:ty,cancelEdit:tw,handleModelChange:tk,handleCompact:tS,handleSteer:tC,handleFollowUp:tN,handlePromptWithStreamingBehavior:tE,handleAbortCompaction:tM,dismissCompactError:t$,handleRecallQueue:tI,handleBuiltinSlashCommand:tT,handleToolPresetChange:tR,handleThinkingLevelChange:tA,handleSetDefaultModel:tL,handleSetDefaultThinkingLevel:tP,loadSlashCommands:tz,loadAllModels:tO,scrollUserMsgToTop:tW,loadContext:tF,activeLeafId:tD,scrollToBottom:t_,scrollToMessage:tU}=function(e){var t;let r,i,{session:s,newSessionCwd:l,newSessionDraftKey:a,onAgentEnd:o,onSessionEnded:c,onToolEnd:d,onAttentionNeeded:p,onSessionCreated:h,onSessionForked:m,onSideSession:f,modelsRefreshKey:g,onBranchDataChange:x,onSystemPromptChange:v,onSystemToolsChange:b,onSystemInfoLoaderChange:y,onSessionStatsPanelOpen:w,onOpenSettings:j,onDebugSnapshotReaderChange:k}=e,S=null===s&&null!==l,N=S?e.initialNewSessionChoices??null:null,[E,M]=(0,u.useState)(null),[$,I]=(0,u.useState)(!S),[T,R]=(0,u.useState)(null),[A,L]=(0,u.useState)(null),[P,z]=(0,u.useState)([]),[O,W]=(0,u.useState)(new Map),[F,D]=(0,u.useState)(ax),[_,K]=(0,u.useState)([]),[q,J]=(0,u.useState)(()=>new Map),[Y,G]=(0,u.useState)(()=>new Map),[X,Q]=(0,u.useState)(null),[ee,et]=(0,u.useState)(!1),[en,er]=(0,u.useState)(0),[ei]=(0,u.useState)(ui),es=ei.dispatch,[el,ea]=(0,u.useState)(!1),[eo,ec]=(0,u.useState)(!1),[ed,eu]=(0,u.useState)(null),[ep,eh]=(0,u.useState)({}),[em,ef]=(0,u.useState)([]),[eg,ex]=(0,u.useState)(null),[ev,eb]=(0,u.useState)(null),[ey,ew]=(0,u.useState)(null),ej=ey??ev,[ek,eS]=(0,u.useState)([]),[eC,eN]=(0,u.useState)(!1),[eE,eM]=(0,u.useState)(null),e$=(0,u.useRef)(null),[eI,eT]=(0,u.useState)({}),[eR,eA]=(0,u.useState)({}),[eL,eP]=(0,u.useState)(()=>N?.model??null),[ez,eO]=(0,u.useState)(null),[eW,eF]=(0,u.useState)(dH.Q8),[eD,e_]=(0,u.useState)(()=>N?.thinkingLevel??null),[eB,eH]=(0,u.useState)(null),[eU,eK]=(0,u.useState)(null),[eq,eV]=(0,u.useState)(null),[eZ,eJ]=(0,u.useState)(null),[eY,eG]=(0,u.useState)(null),[eX,eQ]=(0,u.useState)(null),[e0,e1]=(0,u.useState)(null),e2=(0,u.useRef)(0),e4=(0,u.useRef)(0),[e3,e8]=(0,u.useState)(null),[e6,e5]=(0,u.useState)(null),[e9,e7]=(0,u.useState)(null),[te,tt]=(0,u.useState)(null),[tn,tr]=(0,u.useState)(null),[ti,ts]=(0,u.useState)(!1),[tl,ta]=(0,u.useState)(!1),[to,tc]=(0,u.useState)(!0),[td,tu]=(0,u.useState)(null),[tp,th]=(0,u.useState)(null),[tm,tf]=(0,u.useState)(null),[tg,tx]=(0,u.useState)(!1),[tv,tb]=(0,u.useState)(!1),[ty,tw]=(0,u.useState)([]),[tk,tS]=(0,u.useState)(!1),[tC,tN]=(0,u.useReducer)(ug,{visible:[],pending:[]}),[tE,tM]=(0,u.useState)(null),[t$,tI]=(0,u.useState)([]),[tT,tR]=(0,u.useState)([]),[tA,tL]=(0,u.useState)([]),[tP,tz]=(0,u.useState)([]),[tO,tW]=(0,u.useState)({steering:[],followUp:[]}),tF=(0,u.useRef)(null),tD=(0,u.useRef)(null),t_=(0,u.useRef)(0),tU=(0,u.useRef)(!1),tK=(0,u.useRef)(!1),[tq,tZ]=(0,u.useState)(0),tJ=(0,u.useRef)(null),tY=(0,u.useRef)(()=>{}),tG=(0,u.useRef)({renewStartedAt:null,inFlightSince:null,requests:0,unanswered:0,errors:0,last:null}),tX=(0,u.useRef)({count:0,lastAt:null}),tQ=(0,u.useRef)({count:0,lastAt:null,lastReason:null}),t0=(0,u.useRef)(null),t1=(0,u.useRef)(null),t2=(0,u.useRef)(!1),t4=(0,u.useRef)(0),t3=(0,u.useRef)(s?.id??null),t8=(0,u.useRef)(null),t6=(0,u.useRef)(s?.id??null),t5=(0,u.useRef)(!1),t9=(0,u.useRef)(!1),t7=(0,u.useRef)(!1),ne=(0,u.useRef)(!1),nt=(0,u.useRef)(!1),nn=(0,u.useRef)(-1),nr=(0,u.useRef)(!1),ni=(0,u.useRef)(0),ns=(0,u.useRef)(0),nl=(0,u.useRef)(null),na=(0,u.useRef)(!!e.deferInitialScroll),no=(0,u.useRef)(null),nc=(0,u.useRef)(!1),nd=(0,u.useRef)(!0),nu=(0,u.useRef)(0),np=(0,u.useRef)(null),nh=(0,u.useRef)(void 0),nm=(0,u.useRef)(void 0),nf=(0,u.useRef)(null),ng=(0,u.useRef)(null),nx=(0,u.useRef)([]),nv=(0,u.useRef)(null),nb=(0,u.useRef)(0),ny=(0,u.useRef)(!1),nw=(0,u.useRef)(N?.model??null),nj=(0,u.useRef)(N?.thinkingLevel??null),nk=(0,u.useRef)({}),nS=(0,u.useRef)(null),nC=(0,u.useRef)(0),nN=(0,u.useRef)(null),nE=(0,u.useRef)(null),nM=(0,u.useRef)(null),n$=(0,u.useRef)(null),nI=(0,u.useRef)(null),nT=(0,u.useRef)(0),nR=(0,u.useRef)(null),nA=(0,u.useCallback)(()=>{n$.current=nC.current,nI.current?.runId===nC.current&&(nI.current=null)},[]),nL=(0,u.useRef)(!1),nP=(0,u.useRef)(new Map),nz=(0,u.useRef)(!0),nO=(0,u.useRef)(new Map),nW=(0,u.useRef)(null),nF=(0,u.useRef)([]),nD=(0,u.useRef)([]),n_=(0,u.useRef)(null),nB=(0,u.useRef)(null),nH=(0,u.useRef)(!1),nU=(0,u.useRef)(0);t6.current=s?.id??null,nW.current=E,nF.current=P,nD.current=_,n_.current=A,nB.current=X,nH.current=ee,nU.current=en,t2.current=tl,t4.current=t$.length+tT.length;let nK=(0,u.useCallback)(e=>nz.current&&t8.current!==e&&t3.current===e&&(t9.current||tU.current||t6.current===e&&!tK.current),[]);tF.current||(tF.current=new d1({createSource:e=>tV("agent",new EventSource(`/api/agent/${encodeURIComponent(e)}/events?holder=${encodeURIComponent(tH())}`),e),onEvent:e=>nl.current?.(e),shouldMaintain:nK,readinessTimeoutMs:6e4,reconnectDelayMs:1e3,staleAfterMs:75e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let nq=e.setToolPreset??eF,nV=s?.id;(0,u.useLayoutEffect)(()=>{(nV||S&&!t3.current)&&nq(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dK();if(!e)return dH.Q8;try{let t=e.getItem(dU);return(0,dH.sn)(t)?t:dH.Q8}catch{return dH.Q8}}())},[nV,S,nq]);let nZ=e.onNewSessionChoicesChange;(0,u.useEffect)(()=>{S&&nZ?.({model:eL,thinkingLevel:eD})},[S,eL,eD,nZ]);let nJ=(0,u.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth",t=nf.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),nu.current=t.scrollTop)},[]),nY=e9??te??E?.context.model??tn??null,nG=S?eL??ez:nY??(E?.context.messages.length===0?ez:null),nX=uo(E?.context.thinkingLevel&&"off"!==E.context.thinkingLevel?E.context.thinkingLevel:null),nQ=S?eD??eB:eq??eZ??nX??(E?.context.messages.length===0?eB:null),n0=s?.id??a??void 0,n1=(0,u.useCallback)(e=>{tt(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eJ(uo(e.thinkingLevel))},[]),n2=(0,u.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=nP.current.get(t);if(!e)break;t=e}return t},[]),n4=(0,u.useCallback)((t,n,r)=>{let i=n?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}}),s=n2(r);if(!nz.current&&!ny.current&&r===a)return;let l=e.chatInputRef?.current;l?l.restoreSubmission(t,i,s):s&&V(s,t,i)},[a,e.chatInputRef,n2]),[n3,n8]=(0,u.useState)(()=>{let e=s?.id;return e&&!B(e)&&uu(e,null),e&&uc.get(e)||null}),n6=(0,u.useCallback)(e=>{s?.id&&(uu(s.id,e),n8(e))},[s?.id]),n5=(0,u.useCallback)((t,n)=>{s?.id&&(e.chatInputRef?.current?.replaceMessage(t),n6(n))},[e.chatInputRef,s?.id,n6]),n9=(0,u.useCallback)(()=>n6(null),[n6]),n7=(0,u.useMemo)(()=>{let e=E?.totalActiveMs,t=e0&&e0.sessionId===E?.sessionId?e0.value:void 0,n=void 0===e&&void 0===t?void 0:Math.max(e??0,t??0);if(tE)return{...tE,totalActiveMs:n,...eX?{contextUsage:eX}:{}};let r=E?.stats,i=function(e,t,n){let r=dV(n);if(!e)return r;let i=dV(t),s=(e,t)=>Math.max(0,e-t),l={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return l.total=l.input+l.output+l.cacheRead+l.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:l,cost:e.cost+s(r.cost,i.cost)}}(r,E?.context.messages??[],P);return 0!==i.tokens.total||0!==P.length||r?{sessionFile:E?.filePath||void 0,sessionId:t3.current??s?.id??"",sessionName:s?.name,...i,totalActiveMs:n,...eX?{contextUsage:eX}:{}}:null},[P,tE,eX,e0,E?.sessionId,E?.context.messages,E?.filePath,E?.totalActiveMs,E?.stats,s?.id,s?.name]),re=(0,u.useCallback)((e,t,n,r)=>{nz.current&&t3.current===t&&nC.current===n&&!(r<=e4.current)&&(e4.current=r,e?.contextUsage!==void 0&&eQ(e.contextUsage??null),"number"==typeof e?.totalActiveMs&&e1({sessionId:t,value:e.totalActiveMs}))},[]),rt=(0,u.useCallback)(async e=>{let t=nC.current,n=++e2.current;try{let r=await fetch(dR(e));if(!r.ok)return;let i=await r.json();re(i.state,e,t,n)}catch{}},[re]),rn=(0,u.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:nO.current.get(i);if(s)return await s;let l=(async()=>{let i=!1,s=++nT.current,l=!t9.current;try{t&&I(!0);let a=new URLSearchParams({deferThinking:"1",deferMedia:"1",tree:"summary"});r?.force&&a.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${a}`);if(404===o.status)return t&&(M(null),L(null),z([]),K([]),Q(null),et(!1),er(0),R(null)),dB(e),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let c=await o.json();if(t3.current!==e)return null;(nR.current?.seq??0)<s&&(nR.current={sid:e,seq:s,messages:c.context.messages,entryIds:c.context.entryIds??[]});let d=dD(e),u=!!(c.snapshotRevision&&d?.revision===c.snapshotRevision&&d.entryIds.length>=(c.context.entryIds??[]).length),p=u?nF.current:c.context.messages;if(M(u?{...c,context:{...c.context,messages:nF.current,entryIds:nD.current,oldestEntryId:nB.current,hasMore:nH.current,turnsBefore:nU.current}}:c),L(c.leafId),u)d_({sessionId:e,revision:c.snapshotRevision,messages:nF.current,entryIds:nD.current,leafId:c.leafId,oldestEntryId:nB.current,hasMore:nH.current,turnsBefore:nU.current,summaryTree:c.tree,thinkingLevel:c.context.thinkingLevel,model:c.context.model,stats:c.stats,totalActiveMs:c.totalActiveMs,loadedEntryIds:nD.current});else{let e={messages:nF.current,entryIds:nD.current},t={messages:p,entryIds:c.context.entryIds??[]};J(n=>(function(e,t){let n=new Set(t.entryIds),r=new Map([...e.aliases].filter(e=>{let[t]=e;return n.has(t)})),i=e.entryIds.length,s=e.entryIds[i-1],l=void 0===s?0:t.entryIds.indexOf(s)+1;if(0===l&&void 0!==s)return r;for(let n=0;i+n<e.messages.length;n++){var a,o;let c=t.entryIds[l+n];if(void 0===c||(a=e.messages[i+n],o=t.messages[l+n],a.role!==o.role||("user"===a.role?dX(a)!==dX(o):"custom"===a.role?a.customType!==o.customType:a.timestamp!==o.timestamp)))break;r.set(c,dQ(s,n))}return r})({...e,aliases:n},t)),G(new Map),z(t.messages),K(t.entryIds),Q(c.context.oldestEntryId),et(c.context.hasMore),er(c.context.turnsBefore??0)}if(t5.current=void 0!==c.toolNames,nq(void 0!==c.toolNames?(0,dH.YO)(c.toolNames):dH.Q8),e7(e=>nL.current?e:null),eV(null),R(null),"summary"===c.treeFormat&&c.snapshotRevision&&d_({sessionId:e,revision:c.snapshotRevision,messages:p,entryIds:c.context.entryIds??[],leafId:c.leafId,oldestEntryId:c.context.oldestEntryId,hasMore:c.context.hasMore,turnsBefore:c.context.turnsBefore??0,summaryTree:c.tree,thinkingLevel:c.context.thinkingLevel,model:c.context.model,stats:c.stats,totalActiveMs:c.totalActiveMs,loadedEntryIds:c.context.entryIds??[]}),c.wrapperRebuilt&&(tF.current?.close("rebuilt"),tF.current?.maintain(e)),!n&&c.context.thinkingLevel&&"off"!==c.context.thinkingLevel&&eJ(uo(c.context.thinkingLevel)),i=!0,l&&s>ni.current&&eu(e=>e?.result?null:e),t&&I(!1),!n)return null;try{let t=nC.current,n=++e2.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t3.current!==e)return null;let s=i.state;return n1(s),s?(re(s,e,t,n),void 0!==s.systemPrompt&&e8(s.systemPrompt??null),void 0!==s.extensionStatuses&&tL(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tz(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tW(ua(s.queuedMessages)),void 0!==s.autoCompactionEnabled&&tc(s.autoCompactionEnabled??!0)):i.running||tW({steering:[],followUp:[]}),i}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return R(String(e)),"error"}finally{t&&!i&&I(!1)}})();return nO.current.set(i,l),l.finally(()=>{nO.current.get(i)===l&&nO.current.delete(i)}),await l},[re,nq,n1]),rr=(0,u.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,l=await fetch(s,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let a=await l.json();if(t3.current!==e||r?.signal?.aborted||!nz.current)return;return Q(a.context.oldestEntryId),et(a.context.hasMore),er(a.context.turnsBefore??0),M(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...a.context.messages,...t.context.messages],entryIds:[...a.context.entryIds,...t.context.entryIds],oldestEntryId:a.context.oldestEntryId,hasMore:a.context.hasMore,turnsBefore:a.context.turnsBefore}:a.context;return{...t,context:r}}),n?(z(e=>[...a.context.messages,...e]),K(e=>[...a.context.entryIds,...e])):(z(a.context.messages),K(a.context.entryIds??[])),a.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),ri=(0,u.useCallback)(async e=>{try{let t=await dA(e,{type:"get_tools"});if(!t||!nz.current||t3.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return nq(t5.current?r(t):dH.Q8),b?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[b,nq]),rs=(0,u.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=t3.current;if(S&&l&&r&&!ny.current&&(ny.current=!0,a)){if(a!==r){nP.current.set(a,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(a,r):Z(a,r)}h?.({id:r,path:"",cwd:l,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},a)}},[S,l,a,h,e.chatInputRef]),rl=(0,u.useCallback)((e,t,n)=>{e.model&&nw.current===t&&(tr(e.model),t||eO(e.model)),e.thinkingLevel&&nj.current===n&&(eJ(uo(e.thinkingLevel)),n||eH(uo(e.thinkingLevel)))},[]),ra=(0,u.useCallback)(async()=>{if(t3.current||!S||!l)return t3.current;if(ng.current)return ng.current;let e=(async()=>{let e=nw.current,t=nj.current;e&&tr(e);let n=(0,dH.xG)(eW);t5.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:l,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=d$(e);throw n?new dI(t,r.status,void 0,void 0,n):Error(t)}let i=await r.json(),s=i.sessionId;return t3.current=s,rl(i,e,t),s})();ng.current=e;try{return await e}finally{ng.current=null}},[rl,S,l,eW]),ro=(0,u.useCallback)(async()=>{let e=t3.current??await ra();if(!e)return;let[t]=await Promise.all([dA(e,{type:"get_state"}),ri(e)]);nz.current&&t3.current===e&&(n1(t),e8(t.systemPrompt??""))},[ra,ri,n1]),rc=(0,u.useCallback)(e=>{nx.current=e,tw(e)},[]),rd=(0,u.useCallback)(()=>{nb.current+=1,nv.current=null,rc([])},[rc]),ru=(0,u.useCallback)(async(e,t)=>{let n=null===t6.current&&nz.current;n&&tF.current?.ensureConnected(e).catch(()=>{});try{return await t()}finally{!n||null!==t6.current||t3.current!==e||0!==t4.current||t9.current||nr.current||tF.current?.close("grace_end")}},[]),rp=(0,u.useCallback)(()=>{let e=++nb.current,t=(async()=>{let t=t3.current??await ra();if(!t)return nb.current===e&&rc([]),[];tS(!0);try{let n=await ru(t,()=>dA(t,{type:"get_commands"})),r=n?.commands??[];return nb.current===e&&rc(r),r}catch(t){return console.error("Failed to load slash commands:",t),nb.current===e&&rc([]),null}finally{nb.current!==e&&nv.current||tS(!1)}})();nv.current=t;let n=()=>{nv.current===t&&(nv.current=null)};return t.then(n,n),t},[ra,rc,ru]),rh=(0,u.useCallback)(async()=>await rp()??[],[rp]),rm=(0,u.useCallback)(async()=>{let e=nv.current,t=nx.current;return!e&&t.length>0?t:await (e??rp()).catch(()=>null)??(t.length>0?t:null)},[rp]),rf=(0,u.useCallback)(()=>{t_.current+=1,tU.current=!1,t1.current=null,tD.current&&(clearTimeout(tD.current),tD.current=null)},[]),rg=(0,u.useCallback)(e=>{tF.current?.close(e)},[]),rx=(0,u.useCallback)(e=>tF.current.ensureConnected(e),[]),rv=(0,u.useCallback)(e=>{tF.current.maintain(e)},[]);(0,u.useEffect)(()=>{let e=s?.id;if(e)return nz.current=!0,tK.current=!1,rv(e),()=>{t3.current===e&&tF.current?.close("deselected")}},[rv,s?.id]);let rb=(0,u.useCallback)(e=>{let t=tJ.current;if(t?.sid===e)return t.promise;let n=new AbortController,r=setTimeout(()=>n.abort(),5e3),i={sid:e,promise:Promise.resolve(null)};return i.promise=(async()=>{let t=null,s=null,l=Date.now();tG.current.inFlightSince=l,tG.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),tJ.current===i&&(tJ.current=null);try{let e=tG.current,n=Date.now(),r="unanswered"===s?"unanswered":null===s?"error":"reply";"unanswered"===r&&(e.unanswered+=1),"error"===r&&(e.errors+=1);let i="object"==typeof s&&null!==s?s:null;e.inFlightSince=null,e.last={at:n,durationMs:Math.max(0,n-l),outcome:r,httpStatus:t,reply:i&&{running:!0===i.running,awaitingInput:!0===i.awaitingInput,subagentsActive:!0===i.subagentsActive}}}catch{}}})(),tJ.current=i,i.promise},[]),ry=!el&&!eo&&!tl&&0===t$.length&&0===tT.length;(0,u.useEffect)(()=>{let e=s?.id;if(!e||!ry)return;let t=!1,n=null,r=()=>!t&&"hidden"===document.visibilityState&&!tK.current&&t3.current===e&&t6.current===e&&!t9.current&&!nr.current,i=async()=>{if(n=null,t0.current=null,!r())return;let t=await rb(e);if(r()){if(!("unanswered"===t||t&&!d2(t)))return void l();tK.current=!0,tX.current={count:tX.current.count+1,lastAt:Date.now()},rg("released")}},l=()=>{null===n&&(n=setTimeout(()=>void i(),3e4),t0.current=Date.now()+3e4)},a=()=>{"hidden"===document.visibilityState?l():n&&(clearTimeout(n),n=null,t0.current=null)};return"hidden"===document.visibilityState&&l(),document.addEventListener("visibilitychange",a),()=>{t=!0,n&&clearTimeout(n),t0.current=null,document.removeEventListener("visibilitychange",a)}},[rg,ry,tq,rb,s?.id]);let rw=(0,u.useCallback)(async(e,t)=>{let n=t3.current;if(tI(t=>dN(t,e.id)),!n)return;try{await dA(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e);return}if(null!==t6.current)return;let r=nw.current,i=nj.current;try{let e=await dA(n,{type:"get_state"});if(!nz.current||t3.current!==n||null!==t6.current)return;rl({model:e.model?{provider:e.model.provider,modelId:e.model.id}:null,thinkingLevel:e.thinkingLevel},r,i),void 0!==e.systemPrompt&&e8(e.systemPrompt)}catch{}},[rl]),rj=(0,u.useCallback)(async(e,t)=>{let n=t3.current;if(n)try{await dA(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rk=(0,u.useCallback)(e=>{let t=e.message.trim();t&&tN({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"}})},[]),rS=(0,u.useRef)(e.t);rS.current=e.t;let rC=(0,u.useCallback)((e,t)=>rS.current(e,t),[]),rN=(0,u.useCallback)(()=>{rk({type:"warning",message:rC("chat.sendUnconfirmed")})},[rk,rC]),rE=(0,u.useCallback)(e=>{nz.current&&z(t=>us(t,e.bubble));let t=dD(e.sid);t?.messages.includes(e.bubble)&&d_({...t,messages:us(t.messages,e.bubble)})},[]),rM=(0,u.useCallback)((e,t,n)=>{let r=nI.current;if(!r||r.runId!==t||r.sid!==e)return;nI.current=null;let i=nR.current,s=i?.sid===e&&i.seq>n?i:null,l=s?null===r.lastEntryIdAtSend?0:s.entryIds.indexOf(r.lastEntryIdAtSend)+1||-1:-1;s&&l>=0&&ul(s.messages.slice(l),r.key)>r.sameTextAfterSend||(n4(r.message,r.images,r.draftKey),s&&rE(r),rk(s&&!r.command&&l===s.entryIds.length?{type:"error",message:rC("chat.sendNotReceived")}:{type:"warning",message:rC("chat.sendUnconfirmed")}))},[rk,rE,n4,rC]),r$=(0,u.useCallback)(()=>{let e=nI.current;if(nI.current=null,e){if(e.parkedDraftKey){let t=e.images?.map(e=>{let{data:t,mimeType:n}=e;return{data:t,mimeType:n}});V(e.parkedDraftKey,e.message,t)}else n4(e.message,e.images,e.draftKey);rE(e)}},[rE,n4]),rI=(0,u.useRef)(r$);rI.current=r$;let rT=(0,u.useCallback)(t=>{switch(dS(t)&&p?.(t),t.method){case"select":case"confirm":case"input":case"editor":tI(e=>e.some(e=>e.id===t.id)?e:[...e,t]);break;case"notify":if(t.id&&!uh(t.id))break;rk({id:t.id,message:iK(t.message),type:t.notifyType??"info"});break;case"setStatus":tL(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":tz(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=iK(t.title));break;case"set_editor_text":e.chatInputRef?.current?.setText(iK(t.text));break;case"custom":tR(e=>{let n;return t.closed?dN(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)})}},[rk,p,e.chatInputRef]),rR=(0,u.useCallback)(()=>{let e=t9.current;return t9.current=!1,ea(!1),tf(null),eG(null),W(new Map),D(ax),es({type:"end"}),e},[es]),rA=(0,u.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 nn.current!==e&&(nn.current=e,o?.({aborted:t,...n?{subagentsActive:n}:{},...ne.current?{failed:!0}:{}}),!0)},[o]),rL=(0,u.useCallback)(e=>{if(t6.current===e)return void rf();rf(),tU.current=!0;let t=t_.current,n=async()=>{if(t===t_.current&&t3.current===e&&tU.current)try{let r=await fetch(dR(e));if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==t_.current||t3.current!==e||!tU.current)return;let s=i.state;if(n1(s),i.running&&s&&(s.isStreaming||s.isPromptRunning)){tU.current=!1,tD.current=null,t1.current=null,t7.current=!!s?.isStreaming,nt.current=!!s?.isPromptRunning,t9.current=!0,ea(!0),tf(e=>dx(e,!!s?.isStreaming));return}if(i.running&&s?.isCompacting){ta(!0),tD.current=setTimeout(()=>void n(),600),t1.current=Date.now()+600;return}tU.current=!1,tD.current=null,t1.current=null,rg("grace_end")}catch{if(t!==t_.current||t3.current!==e||!tU.current)return;tD.current=setTimeout(()=>void n(),600),t1.current=Date.now()+600}};tD.current=setTimeout(()=>void n(),3e4),t1.current=Date.now()+3e4},[rf,rg,n1]),rP=(0,u.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t3.current,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nC.current;if(nC.current!==t)return;let n=nT.current;try{e&&await rn(e)}finally{if(nC.current!==t)return;e&&rM(e,t,n);let r=nt.current,i=t7.current;nt.current=!1,t7.current=!1,nN.current=null;let s=rR();r?rA(t):i&&s&&o?.({aborted:!1,...ne.current?{failed:!0}:{}}),e&&rL(e)}},[rn,rA,o,rL,rR,rM]),rz=(0,u.useCallback)(async(e,t)=>{await um(800);let n=Date.now();for(;t9.current&&Date.now()-n<2e4;){if(void 0!==t&&nC.current!==t)return;try{let n=await fetch(dR(e));if(n.ok){let r=await n.json(),i=r.state;if(n1(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await rP(e,t)}}catch{}await um(600)}},[rP,n1]),rO=(0,u.useCallback)(async e=>{let t=ns.current+1;for(ns.current=t;nr.current&&ns.current===t&&t3.current===e;){await um(1e3);try{let n=await fetch(dR(e));if(!n.ok)continue;let r=await n.json();if(n1(r.state),r.state?.isBashRunning)continue;if(await rn(e),ns.current!==t||t3.current!==e)return;nr.current=!1,ec(!1),eu(null);return}catch{}}},[rn,n1]),rW=(0,u.useCallback)(async e=>{if(!t9.current||t3.current!==e)return;let t=nC.current,n=++e2.current;try{let r=await fetch(dR(e));if(!r.ok)return;let i=await r.json();if(t3.current!==e||nC.current!==t)return;let s=i.state;if(re(s,e,t,n),n1(s),ta(s?.isCompacting??!1),tc(s?.autoCompactionEnabled??!0),tW(ua(s?.queuedMessages)),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting)){t7.current=!!s.isStreaming,nt.current=!!s.isPromptRunning;return}if(!t9.current)return;s&&(void 0!==s.extensionStatuses&&tL(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&tz(s.extensionWidgets??[]),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(t=>{t&&nz.current&&t3.current===e&&t.state?.systemPrompt!==void 0&&e8(t.state.systemPrompt??null)}).catch(()=>{})),await rP(e,t)}catch{}},[re,rP,n1]);(0,u.useEffect)(()=>{if(!el)return;let e=()=>{let e=t3.current;e&&rW(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)}},[el,rW]),(0,u.useEffect)(()=>{t9.current=el},[el]);let rF=(0,u.useCallback)(e=>nz.current&&t3.current===e&&!t9.current,[]),rD=(0,u.useRef)(null),r_=(0,u.useRef)(null),rB=(0,u.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:l}=await i.json();if(!rF(e))return;let a=nD.current.at(-1),o=nF.current.at(-1),c=void 0!==a&&nF.current.length===nD.current.length?(n=(t={messages:s.messages,entryIds:s.entryIds??[]}).entryIds.lastIndexOf(a))<0?null:{messages:t.messages.slice(n+1),entryIds:t.entryIds.slice(n+1)}:null;if(!c)return void await rn(e);if(0===c.entryIds.length)return;if(nr.current&&c.messages.some(e=>"bashExecution"===e.role)){r_.current=e;return}nD.current=[...nD.current,...c.entryIds],nF.current=[...nF.current,...c.messages],K(e=>e.at(-1)===a?[...e,...c.entryIds]:e),z(e=>e.at(-1)===o?[...e,...c.messages]:e),l&&(rD.current={base:n_.current,lastEntryId:c.entryIds.at(-1),leafId:l});let d=dD(e);d&&d_({...d,loadedEntryIds:[...d.loadedEntryIds,...c.entryIds]})},[rF,rn]),rH=(0,u.useRef)(rB);rH.current=rB;let rU=(0,u.useRef)(null);rU.current??=(t={pendingReads:e=>[nO.current.get(e),nO.current.get(`force:${e}`)],read:e=>rH.current(e),wanted:rF,onError:e=>console.error("Failed to read a message sent while idle:",e)},r=!1,i=null,e=>{i=e,r||(r=!0,(async()=>{try{for(;null!==i;){let e=i;if(i=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}})())}),nl.current=(0,u.useCallback)(t=>{if(!t8.current)switch(t.type){case"session_ended":{let e=t3.current;if(!e||t.sessionId!==e)return;t8.current=e,rf(),tF.current?.close(),dB(e),c?.(e);return}case"connected":if(es({type:"end"}),Array.isArray(t.pendingExtensionUiIds)){let e=new Set(t.pendingExtensionUiIds);tI(t=>dC(t,e)),tR(t=>dC(t,e))}D(aw),!0===t.isStreaming&&(rf(),t7.current=!0,t9.current=!0,ea(!0),tf({kind:"waiting_model"})),t3.current&&rt(t3.current);break;case"agent_start":ne.current=!1,nA(),rf(),t7.current=!0,t9.current=!0,ea(!0),tf({kind:"waiting_model"}),eG(null),es({type:"start"});break;case"agent_end":if(!t9.current)break;if(tf(null),eG(null),es({type:"end"}),t3.current){let e=t3.current,t=nC.current,n=++e2.current;rn(e),fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.ok?e.json():null).then(r=>{r&&nz.current&&t3.current===e&&nC.current===t&&(n1(r.state),re(r.state,e,t,n),r.state?.systemPrompt!==void 0&&e8(r.state.systemPrompt??null),r.state?.extensionStatuses!==void 0&&tL(r.state.extensionStatuses??[]),r.state?.extensionWidgets!==void 0&&tz(r.state.extensionWidgets??[]),tW(ua(r.state?.queuedMessages)))}).catch(()=>{})}break;case"agent_settled":{let e=t7.current;if(t7.current=!1,!e||nt.current)break;let n=t3.current,r=rR();ta(!1),n&&(rn(n),rL(n)),r&&o?.({aborted:!0===t.aborted,...!0===t.subagentsActive?{subagentsActive:!0}:{},...ne.current?{failed:!0}:{}});break}case"prompt_done":{nA();let e=nC.current,n=nt.current;nt.current=!1,nN.current=null;let r=rA(e,!0===t.aborted,!0===t.subagentsActive);if(!n&&!r)break;let i=t3.current;i&&rn(i),!t7.current&&(rR(),i&&rL(i))}break;case"prompt_error":ne.current=!0,rk({type:"error",message:t.errorMessage??"Command failed"});break;case"extension_error":var n,r;rk({type:"error",message:(n=t.extensionPath,r=t.error??"Extension command failed","string"==typeof n&&n&&!ue.test(n)?`Extension "${n}" error: ${r}`:r)});break;case"message_start":case"message_update":if(!t9.current||d9(t))break;if("message_start"===t.type){let e=t.message;if(e?.role==="user")break;e?.role==="assistant"?(es({type:"snapshot",message:e}),e.content.length>0&&tf(null)):e&&tf(null)}else{let e=t.assistantMessageEvent;e&&(es({type:"delta",event:e}),"toolcall_start"!==e.type&&"toolcall_delta"!==e.type&&tf(null))}!nc.current&&nd.current&&null===np.current&&(np.current=requestAnimationFrame(()=>{np.current=null,nd.current&&nJ("auto")}));break;case"user_message_entry":{let e=nM.current;nM.current=null,G(n=>(function(e,t,n){let{entryId:r}=n;if(!t||"string"!=typeof r||n.timestamp!==t.timestamp)return e;let i=new Map(e);for(let e of t.messages)i.set(e,r);return i})(n,e,t));break}case"message_end":{if(!t9.current){let e=t.message;e?.role==="custom"&&!i2(e)&&t3.current&&rU.current?.(t3.current);break}if(d9(t))break;let e=t.message;if(e&&"user"===e.role){let t=dM(e),n=dX(t),r=nN.current;nN.current=null;let i=r===n?nE.current:null;nM.current={timestamp:t.timestamp,messages:i?[i,t]:[t]},r&&nA(),z(e=>{let i=e[e.length-1];return r&&i?.role==="user"&&dX(i)===r?r===n?e:[...e.slice(0,-1),t]:[...e,t]})}else if(e){"assistant"===e.role&&(ne.current="error"===e.stopReason);let n=Array.isArray(t.transcriptNotices)?t.transcriptNotices:void 0;if(z(t=>{var r;return[...t,(r=dM(e),n&&0!==n.length?{...r,[aG]:[...n]}:r)]}),"toolResult"===e.role){let t=e.toolCallId;D(e=>ay(e,t)),W(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n})}if("assistant"===e.role){let e=t3.current;e&&rt(e)}}es({type:"end"}),tf({kind:"waiting_model"});break}case"tool_execution_start":{if(d5(t))break;let e=t.toolCallId,n=t.toolName,r=performance.now();D(e=>ab(e,t,r)),tf(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(d5(t))break;let e=t.toolCallId,n=t.toolName,r=t.partialResult,i=r?.content,s="Agent"===n&&sr(r?.details);("bash"===n||"powershell"===n||n===az||s)&&Array.isArray(i)&&W(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 l=n===az?function(e){if(!aW(e))return null;let{calls:t}=aD(e.details),n=t.findLast(e=>"running"===e.status)??t.at(-1);if(!n)return null;let r=n.args;if(r.length>120){let e=117,t=r.charCodeAt(e-1);t>=55296&&t<=56319&&e--,r=`${r.slice(0,e)}...`}return r?`${n.name} ${r}`:n.name}(t.partialResult):function(e){if(!d7(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>d7(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);tf(t=>{let r=t?.kind==="running_tools"?[...t.tools]:[],i=r.find(t=>t.id===e),s={id:e,name:n||i?.name||"tool",progress:l??i?.progress};return{kind:"running_tools",tools:[...r.filter(t=>t.id!==e),s]}});break}case"tool_execution_end":{if(d5(t))break;let e=t.toolCallId;d?.(t.toolName);let n=performance.now();D(e=>ab(e,t,n));let r=function(e){if(!("tool_execution_end"!==e.type||d5(e))&&"string"==typeof e.toolCallId&&d6(e.result)&&Array.isArray(e.result.content))return{role:"toolResult",toolCallId:e.toolCallId,toolName:"string"==typeof e.toolName?e.toolName:void 0,content:e.result.content,details:e.result.details,usage:e.result.usage,isError:!0===e.isError,..."number"==typeof e.durationMs?{durationMs:e.durationMs}:{}}}(t);W(t=>{if(!r&&!t.has(e))return t;let n=new Map(t);return r?n.set(e,r):n.delete(e),n}),tf(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":nA(),tW({steering:[...t.steering??[]],followUp:[...t.followUp??[]]});break;case"auto_retry_start":case"summarization_retry_scheduled":eG({attempt:t.attempt,maxAttempts:t.maxAttempts,errorMessage:t.errorMessage});break;case"auto_retry_end":case"summarization_retry_attempt_start":case"summarization_retry_finished":eG(null);break;case"auto_compaction_start":case"compaction_start":ta(!0),tu(null),th(null);break;case"auto_compaction_end":case"compaction_end":ta(!1),eG(null),t.errorMessage?(tu(t.errorMessage),th(null)):!t.aborted&&(th(ux(t.result,t.reason??"auto")),t3.current&&rn(t3.current));break;case"bash_output":{let e=t.output;if(!nr.current||"string"!=typeof e)break;eu(n=>n&&!n.result&&n.command===t.command?{...n,liveOutput:e}:n);break}case"editor_paste":"string"==typeof t.text&&e.chatInputRef?.current?.pasteText(iK(t.text));break;case"extension_ui_request":rT(t);break;case"extension_ui_closed":tI(e=>dN(e,t.id))}},[rk,re,e.chatInputRef,rf,es,rT,rn,nA,rA,o,c,d,rt,rL,nJ,rR,n1]);let rK=(0,u.useCallback)(async(e,t)=>{let n=e.trim();if(!n&&!t?.length)return;let r=!t?.length&&n.startsWith("!");if(nr.current||t9.current&&!r){nr.current&&r&&rk({type:"warning",message:rC("chat.bashAlreadyRunning")}),n4(e,t,n0);return}if(n3&&(n6(null),!await nm.current?.(n3))){n6(n3),n4(e,t,n0);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 nh.current?.(i,r):void n4(e,t,n0)}let a=nC.current+1;ne.current=!1,rf(),nt.current=!0;let o=t?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),c={role:"user",content:o?.length?[...e.trim()?[{type:"text",text:e}]:[],...o]:e,timestamp:Date.now()},d=dX(c),u=nD.current,p=u.at(-1)??null,h=ul(nF.current.slice(u.length),d);z(e=>[...e,c]),nN.current=d,nE.current=c,nC.current=a,t9.current=!0,ea(!0),tf(i?{kind:"running_command"}:{kind:"waiting_model"}),es({type:"start"}),nc.current=!0,tx(!0);let m=()=>{z(e=>{let t=e.lastIndexOf(c);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nN.current=null},f=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),g=null,x=!1;try{if(S&&l){let t=t3.current??await ng.current,n=t??await ra();if(!n)throw Error("Unable to create a session for the prompt");g=n,eL&&(tr(eL),t&&await dA(n,{type:"set_model",provider:eL.provider,modelId:eL.modelId})),nz.current&&await rx(n).catch(e=>{if(nz.current)throw e}),x=!0;let r=await dA(n,{type:"prompt",message:e,...f?.length?{images:f}:{}});r?.queued&&m(),rs(1,e)}else if(s){g=s.id,await rx(s.id),x=!0;let t=await dA(s.id,{type:"prompt",message:e,...f?.length?{images:f}:{}});t?.queued&&m()}else throw Error("No active session for the prompt");ew(null),i&&g&&rz(g,a)}catch(n){if(console.error("Failed to send message:",n),!(!x||dT(n))&&g){n$.current!==a&&(nI.current={runId:a,sid:g,message:e,images:t,draftKey:n0,parkedDraftKey:S&&l?C(l):null,lastEntryIdAtSend:p,sameTextAfterSend:h,bubble:c,key:d,command:i},nz.current||r$()),rz(g,a);return}if(nt.current=!1,z(e=>us(e,c)),n instanceof dI&&n.missingCwd?ew(n.missingCwd):rk({type:"error",message:n instanceof Error?n.message:String(n)}),n4(e,t,n0),nN.current=null,g)return void rW(g);t9.current=!1,rg("send_failed"),ea(!1),tf(null),es({type:"end"})}},[S,l,eL,s,ra,rx,rs,rz,rk,r$,rf,rg,n0,es,rW,n4,n3,n6,rC]);nh.current=(0,u.useCallback)(async(e,t)=>{if(nr.current)return;let n=`${t?"!!":"!"}${e}`;nr.current=!0;let r=Date.now();eu({command:e,excludeFromContext:t,startedAt:r}),ec(!0);let i=null;try{let l=t3.current??s?.id??await ra();if(!l)throw Error("Unable to create a session for the shell command");await rx(l).catch(()=>{});let a=await dA(l,{type:"bash",command:e,excludeFromContext:t});t9.current&&a?(i={command:e,excludeFromContext:t,startedAt:r,result:a},ni.current=nT.current):(await rn(l),rs(1,n))}catch(e){console.error("Failed to execute shell command:",e),e instanceof dI&&"extension_reported"===e.code||rk({type:"error",message:e instanceof Error?e.message:String(e)}),n4(n,void 0,n0)}finally{nr.current=!1,eu(i),ec(!1);let e=r_.current;r_.current=null,e&&rU.current?.(e)}},[rk,n0,rx,ra,rn,rs,n4,s]);let rq=ed?.result;(0,u.useEffect)(()=>{if(el||!rq)return;let e=t3.current;e&&rn(e,!1,!1,{force:!0})},[el,rq,rn]);let rV=(0,u.useCallback)(t=>{let n=[...t?.steering??[],...t?.followUp??[]].join("\n\n");t?.images?.length?n4(n,t.images,n0):n&&e.chatInputRef?.current?.prependText(n)},[n0,e.chatInputRef,n4]),rZ=(0,u.useCallback)(async()=>{let e=t3.current;if(e){if(nr.current&&!t9.current){try{await dA(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{let t=await dA(e,{type:"abort"});t&&tW({steering:[],followUp:[]}),rV(t)}catch(e){console.error("Failed to abort:",e)}}},[rV]),rJ=(0,u.useCallback)(async(e,t)=>{if(nr.current)return;let n=t3.current;if(n){e5(e);try{let{cancelled:r,newSessionId:i}=await dA(n,{type:"fork",entryId:e})??{};!r&&i&&(t&&H(i,t),m?.(i))}catch(e){console.error("Fork failed:",e),rk({type:"error",message:e instanceof Error?e.message:String(e)})}finally{e5(null)}}},[rk,m]),rY=(0,u.useCallback)(async t=>{let n=t3.current;if(!n)return rC("sidebar.forkNotFound");try{let r=await fetch(`/api/sessions/${encodeURIComponent(n)}/fork`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),i=await r.json().catch(()=>({}));if(!r.ok||!i.sessionId||!i.session){let{key:e,params:t}=tj(i.code,i.error??`HTTP ${r.status}`);return rC(e,t)}let s=e.chatInputRef?.current;return s?s.rekeyDraft(n,i.sessionId):Z(n,i.sessionId),m?.(i.sessionId,i.session),null}catch(e){return rC("sidebar.forkFailed",{error:e instanceof Error?e.message:String(e)})}},[m,e.chatInputRef,rC]),rG=!!ej&&!S&&!!s?.id&&s?.relation?.kind!=="subagent"&&s?.relation?.kind!=="side",rX=(0,u.useCallback)(async e=>{if(nr.current)return!1;let t=t3.current;if(!t)return!1;try{let n=await dA(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||t3.current!==t)return!1;return await rn(t),t3.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[rn]);nm.current=rX;let rQ=(0,u.useCallback)(async e=>{if(nr.current||t9.current||tl)return;L(e);let t=t3.current;t&&(await rr(t,e),e&&dA(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tl,rr]),r0=(0,u.useCallback)(async(e,t)=>{if(S){let n={provider:e,modelId:t};nw.current=n,eP(n),tr(n),null===nj.current&&eH(uo(nk.current[`${e}/${t}`])??nS.current);let r=t3.current??await ng.current;if(!r)return;try{await dA(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=t3.current;if(!n||nL.current)return;nL.current=!0,e7({provider:e,modelId:t}),ts(!0);let r=t9.current||nr.current,i=async()=>{let e=await fetch(dR(n)).catch(()=>null),t=e?.ok?await e.json().catch(()=>null):null;t?.state&&nz.current&&t3.current===n&&n1(t.state)};try{let s=await dA(n,{type:"set_model",provider:e,modelId:t});tt({provider:s.provider,modelId:s.id}),nL.current=!1,r?(e7(null),await i()):await rn(n)}catch(e){console.error("Failed to set model:",e),nL.current=!1,e7(e9),rk({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),r?await i():await rn(n,!1,!0)}finally{nL.current=!1,ts(!1)}},[rk,e9,S,rn,eP,n1]),r1=(0,u.useCallback)(async e=>{let t=t3.current;if(!t||tl)return!0;ta(!0),tu(null),th(null);try{let n=await dA(t,{type:"compact",...e?{customInstructions:e}:{}});return th(ux(n,"manual")),await rn(t)&&rs(),!0}catch(e){return tu(e instanceof Error?e.message:String(e)),th(null),!1}finally{ta(!1)}},[tl,rn,rs]),r2=(0,u.useCallback)(()=>tu(null),[]),r4=(0,u.useCallback)(async e=>{let t,n=l??s?.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=d$(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||(eb(i),ex(i?null:t instanceof Error?t.message:String(t))),t}eb(null),eh(t.models),ex(t.modelError??null),eS(t.modelScopeWarnings??[]),eN(!!t.isScoped),eM(null),e$.current=null,eT(t.thinkingLevels??{}),eA(t.thinkingLevelMaps??{});let a=t.modelList??[];ef(a);let o=t.defaultModel?a.find(e=>e.id===t.defaultModel?.modelId&&e.provider===t.defaultModel?.provider):void 0;if(eO(o?{provider:o.provider,modelId:o.id}:null),nk.current=t.thinkingLevelPins??{},nS.current=uo(t.defaultThinkingLevel),eK(uo(t.savedDefaultThinkingLevel)),S&&!t3.current){let e=nw.current,n=e&&(0===a.length||!!t.isScoped||a.some(t=>t.provider===e.provider&&t.id===e.modelId));e&&!n&&(nw.current=null,eP(null));let r=n?e:o&&{provider:o.provider,modelId:o.id},i=r&&t.thinkingLevelPins?.[`${r.provider}/${r.modelId}`];null===nj.current&&eH(uo(i)??nS.current)}},[S,l,s?.cwd]),r3=(0,u.useCallback)(()=>{if(e$.current)return;let e={};e$.current=e;let t=l??s?.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();e$.current===e&&(eh(e=>({...n.models,...e})),eT(e=>({...n.thinkingLevels,...e})),eA(e=>({...n.thinkingLevelMaps,...e})),eM(n.modelList??[]))}).catch(t=>{e$.current===e&&(e$.current=null,rk({type:"error",message:t instanceof Error?t.message:String(t)}))})},[rk,l,s?.cwd]);(0,u.useEffect)(()=>{!eC||!nG||eE||em.some(e=>e.provider===nG.provider&&e.id===nG.modelId)||r3()},[eE,nG,eC,r3,em]);let r8=(0,u.useCallback)(async e=>{let t=l??s?.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}`)},[l,s?.cwd]),r6=(0,u.useCallback)(()=>{r4().catch(()=>{})},[r4]),r5=(0,u.useCallback)(async(e,t)=>{try{await r8({provider:e,modelId:t})}catch(e){rk({type:"error",message:`Failed to save default model: ${e instanceof Error?e.message:String(e)}`});return}rk({type:"success",message:`Default model: ${e}/${t}`}),eO({provider:e,modelId:t}),(nG?.provider!==e||nG?.modelId!==t)&&await r0(e,t),r6()},[rk,nG,r0,r6,r8]),r9=(0,u.useCallback)(async(t,n)=>{let r=e.session?.relation?.kind;if("side"===r||"subagent"===r)return rC(dL[r]);let i=t3.current;if(!i)return rC("sideChat.error.noSession");let s=await dP(i,rC,n);return"error"in s?s.error:(f?.(s.session,t),null)},[f,e.session?.relation?.kind,rC]),r7=(0,u.useCallback)(async t=>{if(!t.startsWith("/"))return{handled:!1};let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,s=i.trim(),l=t3.current??await ra(),a=e=>(e.handled&&(e.error?rk({type:"error",message:e.error}):e.action||rk({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":if(!l||tl)return a({handled:!0,error:"No active session to compact"});return r1(s||void 0).then(t=>{!t&&s&&e.chatInputRef?.current?.prependText(`/compact ${s}`)}),a({handled:!0,action:"compact"});case"auto-compact":{if(!l)return a({handled:!0,error:"No active session"});let e=await dA(l,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await dA(l,{type:"set_auto_compaction",enabled:t}),tc(t),a({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!l)return a({handled:!0,error:"No active session to reload"});return await dA(l,{type:"reload"}),await Promise.all([rn(l,!1,!0),ri(l),rh(),r4()]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!l)return a({handled:!0,error:"No active session to name"});if(!s)return a({handled:!0,error:"Usage: /name <name>"});return await dA(l,{type:"set_session_name",name:s}),await rn(l)&&rs(),a({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!l)return a({handled:!0,error:"No active session"});if(!w)return a({handled:!0,message:function(e,t){if(!e)return t("session.noUsage");let n=dJ(e.cost);return[t(1===e.totalMessages?"session.usageSummaryOne":"session.usageSummary",{messages:e.totalMessages,tokens:dZ(e.tokens.total)}),...n?[n]:[]].join(" \xb7 ")}(n7,rC)});let e=await dA(l,{type:"get_session_stats"});return e&&tM(e),w(),a({handled:!0,action:"openSessionStats"})}case"mcp":{if(s||!j)return{handled:!1};let e=await rm();if(!e||!(e.some(oX)||!e.some(e=>"mcp"===e.name)))return{handled:!1};return j("mcp"),a({handled:!0,action:"openSettings"})}case"copy":{if(!l)return a({handled:!0,error:"No active session"});let e=await dA(l,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await s$(t),a({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!l)return a({handled:!0,error:"No active session to clone"});if(t9.current||nr.current)return a({handled:!0,error:"Cannot clone while the session is running"});let e=rD.current,t=await dA(l,{type:"clone",leafId:e?.base===A&&e.lastEntryId===nD.current.at(-1)?e.leafId:A});if(t?.cancelled&&t.byExtension)return{handled:!0};if(t?.cancelled||!t?.newSessionId)return a({handled:!0,error:"Cannot clone an empty or unsaved session"});let n=a({handled:!0,message:"Cloned current session branch"});return m?.(t.newSessionId),n}case"side":{let e=await r9(s||null);return a(e?{handled:!0,error:e}:{handled:!0,action:"openSideChat"})}default:return{handled:!1}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}},[A,rk,ra,r1,tl,r4,rn,rh,ri,rs,j,m,w,e.chatInputRef,n7,rm,r9,rC]),ie=(0,u.useCallback)(async(e,t,n)=>{let r=t3.current;if(n3)return void n4(e,n,n0);if(!r){n4(e,n,n0),rk({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 dA(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){if(console.error("Failed to submit streaming prompt:",t),n4(e,n,n0),t instanceof dI&&t.missingCwd)return void ew(t.missingCwd);dT(t)?rk({type:"error",message:t.message}):rN()}},[rk,rN,n0,n3,n4]),it=(0,u.useCallback)(async(e,t)=>{await ie(e,"steer",t)},[ie]),ir=(0,u.useCallback)(async(e,t,n)=>{await ie(e,t,n)},[ie]),ii=(0,u.useCallback)(async(e,t)=>{await ie(e,"followUp",t)},[ie]),is=(0,u.useCallback)(async()=>{let e=t3.current;if(e)try{await dA(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),il=(0,u.useCallback)(async()=>{let e=t3.current;if(e)try{let t=await dA(e,{type:"clear_queue"});tW({steering:[],followUp:[]}),rV(t)}catch(e){console.error("Failed to recall queued messages:",e),rk({type:"error",message:"Failed to recall queued messages"})}},[rk,rV]),ia=(0,u.useCallback)(async e=>{if("auto"===e){nj.current=null,e_(null),eV(null);let e=t3.current;if(e){let t=uo(nG&&nk.current[`${nG.provider}/${nG.modelId}`])??nS.current??"medium";try{await dA(e,{type:"set_thinking_level",level:t});let n=await dA(e,{type:"get_state"});nz.current&&t3.current===e&&eJ(uo(n?.thinkingLevel)??t)}catch(e){console.error("Failed to restore default thinking level:",e)}}return}S?(nj.current=e,e_(e)):eV(e);let t=t3.current??await ng.current;if(t)try{await dA(t,{type:"set_thinking_level",level:e}),nz.current&&t3.current===t&&(eJ(e),eV(null))}catch(e){console.error("Failed to set thinking level:",e),eV(null)}},[S,nG]),io=(0,u.useCallback)(async e=>{try{await r8({thinkingLevel:e})}catch(e){rk({type:"error",message:`Failed to save default reasoning level: ${e instanceof Error?e.message:String(e)}`});return}rk({type:"success",message:`Default reasoning level: ${e}`}),eK(e),nQ!==e&&await ia(e),r6()},[rk,nQ,ia,r6,r8]),ic=(0,u.useCallback)(async e=>{let t=(0,dH.xG)(e);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dK();if(t)try{t.setItem(dU,e)}catch{}}(e),nq(e);let n=t3.current??await ng.current;if(!n){t5.current=void 0!==t;return}try{let e=await dA(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});t5.current=void 0!==t;let r=e?.sessionId??n;(r!==n||e?.recreated)&&(rf(),rg("set_tools"),tI([]),tR([]),t3.current=r,e?.recreated&&t6.current===r&&rv(r)),rd(),tL([]),tz([]);let[i]=await Promise.all([dA(r,{type:"get_state"}),ri(r)]);nz.current&&t3.current===r&&(e8(i.systemPrompt??""),n1(i))}catch(e){console.error("Failed to set tools:",e)}},[rf,rd,rg,ri,rv,nq,n1]),id=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=nf.current;n&&(null!==np.current&&(cancelAnimationFrame(np.current),np.current=null),na.current=!0,nc.current=!1,nd.current=!1,tx(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),nu.current=n.scrollTop)},[]),iu=(0,u.useCallback)(()=>{let e=nf.current,t=no.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!==np.current&&(cancelAnimationFrame(np.current),np.current=null),nd.current=!0,nu.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),ip=(0,u.useCallback)(()=>{let e=nf.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=t9.current,s=nd.current,l=function(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:96;return!!ut(n,r,i)||!(n<t)&&(!!(!e&&n>t&&ut(n,r,i,s))||e)}(s,nu.current,t,n,r,i?96:8);nd.current=l,nu.current=t;let a=function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:8;return!(n<=t)&&!ut(e,t,n,r)}(t,n,r);tb(e=>e===a?e:a),!s&&l&&i?nJ("auto"):l||null===np.current||(cancelAnimationFrame(np.current),np.current=null)}},[nJ]),ih=(0,u.useCallback)((e,t)=>{t?.running&&(ri(e),(t.state?.isStreaming||t.state?.isPromptRunning)&&(t7.current=!!t.state.isStreaming,nt.current=!!t.state.isPromptRunning,t9.current=!0,ea(!0),tf(e=>dx(e,t.state?.isStreaming===!0)),es({type:"resume"}),!t.state.isStreaming&&t.state.isPromptRunning&&rz(e)),t.state?.isBashRunning&&(nr.current=!0,ec(!0),rO(e))),t?.state&&(void 0!==t.state.isCompacting&&ta(t.state.isCompacting),void 0!==t.state.systemPrompt&&e8(t.state.systemPrompt??null),void 0!==t.state.extensionStatuses&&tL(t.state.extensionStatuses??[]),void 0!==t.state.extensionWidgets&&tz(t.state.extensionWidgets??[]),void 0!==t.state.queuedMessages&&tW(ua(t.state.queuedMessages)))},[es,ri,rO,rz]);tY.current=(e,t)=>{!tK.current||t8.current===e||(tK.current=!1,tQ.current={count:tQ.current.count+1,lastAt:Date.now(),lastReason:t},tZ(e=>e+1),nz.current&&t3.current===e&&t6.current===e&&(rv(e),rn(e,!1,!0).then(t=>{nz.current&&t3.current===e&&ih(e,t)})))},(0,u.useEffect)(()=>{let e=s?.id;if(!e)return;let t=!1,n=tG.current,r=async()=>{let n=await rb(e);!t&&"hidden"===document.visibilityState&&d2(n)&&tY.current(e,"activity")};r();let i=setInterval(()=>void r(),3e4);n.renewStartedAt=Date.now();let l=()=>{"visible"===document.visibilityState&&(tY.current(e,"visible"),r())};return document.addEventListener("visibilitychange",l),()=>{t=!0,clearInterval(i),n.renewStartedAt=null,document.removeEventListener("visibilitychange",l)}},[rb,s?.id]),(0,u.useEffect)(()=>{if(nz.current=!0,e4.current=e2.current,s){t3.current=s.id;let e=dD(s.id);e&&(M({sessionId:s.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}),L(e.leafId),z(e.messages),K(e.entryIds),Q(e.oldestEntryId),et(e.hasMore),er(e.turnsBefore),R(null),I(!1)),rn(s.id,!e,!0,{force:!0}).then(e=>{ih(s.id,e)})}return()=>{nz.current=!1;let e=S?a:null;e&&queueMicrotask(()=>{nz.current||ny.current||U(e)});let t=t3.current,n=nW.current;if(t&&n&&n.sessionId===t&&n.snapshotRevision){let e=dD(t),r=nD.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)?d_({sessionId:t,revision:n.snapshotRevision,messages:nF.current,entryIds:nD.current,leafId:n_.current,oldestEntryId:nB.current,hasMore:nH.current,turnsBefore:nU.current,summaryTree:n.tree,thinkingLevel:n.context.thinkingLevel,model:n.context.model,stats:n.stats,totalActiveMs:n.totalActiveMs,loadedEntryIds:nD.current}):dB(t)}rI.current(),null!==np.current&&(cancelAnimationFrame(np.current),np.current=null),ns.current+=1,rf(),rg()}},[]),(0,u.useEffect)(()=>{v?.(e3)},[e3,v]),(0,u.useEffect)(()=>(y?.(ro),()=>y?.(null)),[ro,y]);let im=(0,u.useCallback)(()=>{let e,t=null;try{t=tF.current?.snapshot?.()??null}catch{t=null}let n=t3.current,r=tG.current,i=tQ.current;return{pageId:"string"==typeof(e=globalThis[tB])?e:null,sessionId:n,selectedSessionId:t6.current,mounted:nz.current,wantsStream:null!==n&&nK(n),connection:t,released:{active:tK.current,...tX.current},reattached:{...i},hiddenReleaseDueAt:t0.current,hiddenGraceMs:3e4,graceDueAt:t1.current,run:{agentRunning:t9.current,bashRunning:nr.current,compacting:t2.current,dialogs:t4.current},lease:{renewIntervalMs:3e4,renewStartedAt:r.renewStartedAt,inFlightSince:r.inFlightSince,requests:r.requests,unanswered:r.unanswered,errors:r.errors,last:r.last&&{...r.last,reply:r.last.reply&&{...r.last.reply}}}}},[nK]);(0,u.useEffect)(()=>(k?.(im),()=>k?.(null)),[im,k]);let ig=el||eo||tl;(0,u.useEffect)(()=>{x&&x(E?.tree??[],A,rQ,ig)},[E?.tree,A,rQ,ig,x]),(0,u.useEffect)(()=>{let e=nf.current;if(e)return nu.current=e.scrollTop,e.addEventListener("scroll",ip,{passive:!0}),()=>{e.removeEventListener("scroll",ip)}},[P.length,$,ip]),(0,u.useEffect)(()=>{el||tx(!1)},[el]),(0,u.useLayoutEffect)(()=>{P.length>0&&(nc.current?(nc.current=!1,na.current=!0,iu()):na.current?!t9.current&&nd.current&&nJ("auto"):(na.current=!0,nJ("instant")))},[P.length,el,nJ,iu]),(0,u.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await r4(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=up.length||(await um(up[t]),e.signal.aborted))return}})(),()=>e.abort()},[r4,g]),(0,u.useEffect)(()=>{if(!tp)return;let e=setTimeout(()=>th(null),6e3);return()=>clearTimeout(e)},[tp]);let[ix,iv]=(0,u.useState)(null),ib=(0,u.useRef)(5e3),iy=(0,u.useRef)(null),iw=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(0===tC.visible.length){iw.current=null;return}let e=tC.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{tN({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=tC.visible[0];if(!t||(iw.current!==t.id&&(iw.current=t.id,ib.current=5e3),tC.visible.some(e=>e.id===ix)))return;iy.current=Date.now();let n=setTimeout(()=>{tN({type:"mark_oldest_exiting"})},ib.current);return()=>{clearTimeout(n),null!==iy.current&&(ib.current=Math.max(0,ib.current-(Date.now()-iy.current)),iy.current=null)}},[tC.visible,ix]),(0,u.useEffect)(()=>{tM(null)},[P.length,eX?.tokens,eX?.percent,eX?.contextWindow]);let ij=nQ??"auto",ik=t$[0]??null,iS=Math.max(0,t$.length-1),iC=tT[0]??null,iN=Math.max(0,tT.length-1),iE=(0,u.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?dQ(r,s-e.length):n.get(t)??t)}return i})(_,P.length,q),[_,P.length,q]);return{data:E,loading:$,error:T,activeLeafId:A,messages:P,activeToolResults:O,toolClocks:F,entryIds:_,messageKeys:iE,liveUserEntryIds:Y,historyCursor:X,hasEarlierMessages:ee,earlierTurnCount:en,streamingStore:ei,agentRunning:el,modelNames:ep,modelList:em,modelError:eg,missingCwd:ej,canForkMissingCwd:rG,modelScopeWarnings:ek,isModelScopeActive:eC,allModelList:eE,modelThinkingLevels:eI,modelThinkingLevelMaps:eR,newSessionModel:eL,toolPreset:eW,thinkingLevel:ij,retryInfo:eY,contextUsage:eX,systemPrompt:e3,forkingEntryId:e6,isCompacting:tl,compactError:td,compactResult:tp,currentModel:nY,displayModel:nG,modelSwitching:ti,sessionStats:n7,autoCompactionEnabled:to,slashCommands:ty,slashCommandsLoading:tk,queuedMessages:tO,notices:tC.visible,extensionDialog:ik,waitingExtensionDialogCount:iS,extensionCustomUi:iC,waitingExtensionCustomUiCount:iN,extensionStatuses:tA,extensionWidgets:tP,respondToExtensionUi:rw,sendExtensionCustomInput:rj,isAutoModelSelection:S&&null===eL,isAutoThinkingSelection:S&&null===eD,defaultModel:ez,savedDefaultThinkingLevel:eU,agentPhase:tm,isNew:S,editEntryId:n3,promptAnchorActive:tg,showScrollToBottom:tv,sessionIdRef:t3,scrollContainerRef:nf,lastUserMsgRef:no,pendingScrollToUserRef:nc,initialScrollDoneRef:na,handleSend:rK,handleAbort:rZ,startSideChat:r9,handleFork:rJ,forkIntoCwd:rY,handleNavigate:rX,handleModelChange:r0,handleCompact:r1,handleSteer:it,handleFollowUp:ii,handlePromptWithStreamingBehavior:ir,handleAbortCompaction:is,dismissCompactError:r2,handleRecallQueue:il,handleBuiltinSlashCommand:r7,handleEditContent:n5,cancelEdit:n3?n9:void 0,addNotice:rk,setNoticePaused:iv,handleToolPresetChange:ic,handleThinkingLevelChange:ia,handleSetDefaultModel:r5,handleSetDefaultThinkingLevel:io,loadTools:ri,loadSlashCommands:rh,loadAllModels:r3,setActiveLeafId:L,setData:M,setMessages:z,loadContext:rr,scrollToBottom:nJ,scrollUserMsgToTop:iu,scrollToMessage:id,dispatch:es,setAgentRunning:ea,setForkingEntryId:e5,bashRunning:eo,pendingBash:ed,handleAgentEventRef:nl}}({session:r,sessionRunning:o,newSessionCwd:c,newSessionDraftKey:p,initialNewSessionChoices:x,onNewSessionChoicesChange:b,onAgentEnd:eu,onSessionEnded:w,onToolEnd:j,onAttentionNeeded:k,onSessionCreated:S,onSessionForked:N,onSideSession:M,modelsRefreshKey:$,chatInputRef:I,onBranchDataChange:T,onSystemPromptChange:R,onSystemToolsChange:A,onSystemInfoLoaderChange:L,onSessionStatsPanelOpen:O,onOpenSettings:F,onDebugSnapshotReaderChange:P,t:er,deferInitialScroll:!!eh}),tK=uv(eM,ub),tq=uv(eM,uy),tZ=(0,u.useCallback)(()=>eM.getState().streamingMessage,[eM]),tJ=e$||eI,tY=e4||e8?"waiting":eV||eI||ta?.kind==="running_tools"||ta?.kind==="running_command"?"working":tJ?tK&&tq?"replying":"sending":"idle";(0,u.useEffect)(()=>{dk.update(ed,r?.id??tu.current,tY)},[ed,r?.id,tu,tY]),(0,u.useEffect)(()=>()=>dk.release(ed),[ed]);let tG=(0,u.useRef)(new Set);(0,u.useEffect)(()=>{for(let e of e2)"error"!==e.type||tG.current.has(e.id)||dk.finish(ed,"error");tG.current=new Set(e2.map(e=>e.id))},[ed,e2]);let tX=(0,u.useCallback)((e,t)=>{tv(e,{value:c2(t),images:c4(t)})},[tv]);(0,u.useEffect)(()=>{if(e$&&en)return en()},[e$,en]);let[tQ,t0]=(0,u.useState)(!1),[t1,t2]=(0,u.useState)(!1),[t4,t3]=(0,u.useState)(null),t8=(0,u.useCallback)(()=>{t3(null),t0(!0)},[]),t6=(0,u.useCallback)(async e=>{t3(null),t2(!0);let t=await tb(e);t2(!1),t?t3(t):t0(!1)},[tb]),t5=(0,u.useCallback)(async e=>{let t;try{t=await tx(e)}catch(e){t=e instanceof Error?e.message:String(e)}t&&(I?.current?.restoreSubmission(e),tn({type:"error",message:t}))},[tn,I,tx]),t9=(0,u.useRef)(!1);(0,u.useEffect)(()=>{ex||ev||!Y||t9.current||(t9.current=!0,G?.(),tf(Y))},[Y,ex,ev,tf,G]),(0,u.useEffect)(()=>{let e=!!e4&&!ec.current;ec.current=!!e4,el&&e&&ea.current()},[el,e4]),(0,u.useEffect)(()=>{E||(h=tJ?tg:null)},[E,tJ,tg]);let[t7,ne]=(0,u.useState)(50),[nt,nn]=(0,u.useState)(null),nr=(0,u.useRef)(null),ni=(0,u.useRef)(null),nl=(0,u.useCallback)(e=>{if(ni&&(ni.current=e),!e)return;let t=function(e){for(let t=e.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if("auto"===e||"scroll"===e)return t}return null}(e);if(!t||"u"<typeof IntersectionObserver||!CSS.supports?.("content-visibility","auto"))return()=>{ni&&(ni.current=null)};let n=new Set,r=new Set,i=e=>{e.style.removeProperty("content-visibility"),e.style.removeProperty("contain-intrinsic-block-size"),e.style.removeProperty("contain"),r.delete(e)},s=e=>{for(let t of e)t.style.contain="layout";let t=e.map(uj);e.forEach((e,n)=>{e.style.containIntrinsicBlockSize=`auto ${t[n]}px`,e.style.contentVisibility="auto",r.add(e)})},l=new IntersectionObserver(t=>{let l=[];for(let s of t){let t=s.target;s.isIntersecting?(n.add(t),r.has(t)&&i(t)):(n.delete(t),r.has(t)||t.parentElement!==e||l.push(t))}l.length>0&&s(l)},{root:t,rootMargin:"100% 0px"}),a=e=>{e instanceof HTMLElement&&l.observe(e)},o=t=>{t instanceof HTMLElement&&t.parentElement!==e&&(l.unobserve(t),n.delete(t),r.has(t)&&i(t))};Array.from(e.children).forEach(a);let c=new MutationObserver(e=>{for(let t of e)t.removedNodes.forEach(o),t.addedNodes.forEach(a)});c.observe(e,{childList:!0});let d=e.getBoundingClientRect().width,u=null,p=new ResizeObserver(()=>{let t=e.getBoundingClientRect().width;t!==d&&(d=t,u&&clearTimeout(u),u=setTimeout(()=>{u=null;let t=Array.from(r);0!==t.length&&(t.forEach(i),s(t.filter(t=>t.parentElement===e&&!n.has(t))))},200))});return p.observe(e),()=>{ni&&(ni.current=null),u&&clearTimeout(u),l.disconnect(),c.disconnect(),p.disconnect(),r.forEach(i)}},[ni]),na=(0,u.useRef)(null),no=(0,u.useRef)(!1),nc=(0,u.useRef)(!1),nd=(0,u.useRef)(eh);nd.current=eh;let[nu,np]=(0,u.useState)(null),nh=eb[ej.indexOf(nu?.entryId??"")],nm=nh?.role==="assistant"?nu?.blockIndex===void 0?nh.content.find(e=>"text"===e.type):nh.content[nu.blockIndex]:void 0,ng=(0,u.useRef)({entryIds:ej,historyCursor:eC,hasEarlierMessages:eN});ng.current={entryIds:ej,historyCursor:eC,hasEarlierMessages:eN};let nx=(0,u.useRef)(null),nv=(0,u.useCallback)(async(e,t,n)=>{nx.current=t;let r=await tF(e,tD,t,n);return r||nx.current!==t||(nx.current=null),r},[tD,tF]);(0,u.useEffect)(()=>{eC!==nx.current&&(nx.current=null)},[eC]),(0,u.useLayoutEffect)(()=>{let e=r?.id,t=tp.current,n=ni.current;if(e&&a&&t&&n)return()=>{if(nd.current)return;if(ut(t.scrollTop,t.clientHeight,t.scrollHeight))return void a(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&&a(e,{atBottom:!1,...i,oldestEntryId:ng.current.historyCursor})}},[ex,a,tp,r?.id]),(0,u.useEffect)(()=>{i&&em(null)},[i]),(0,u.useEffect)(()=>{let e=r?.id;if(!eh||!e||ex||i||nc.current)return;nc.current=!0;let t=new AbortController;return(async()=>{let n=ng.current;if(n.entryIds.includes(eh.anchorEntryId)){ne(e=>Math.max(e,2*n.entryIds.length)),eg(!0);return}no.current=!0;let r=n.historyCursor,i=n.hasEarlierMessages;try{for(;i&&r&&!t.signal.aborted;){let n=await nv(e,r,{signal:t.signal});if(t.signal.aborted)return;if(!n){t_("instant"),em(null);return}if(ne(e=>e+Math.max(50,2*n.messages.length)),n.entryIds.includes(eh.anchorEntryId))return void eg(!0);if(n.oldestEntryId===eh.oldestEntryId)break;r=n.oldestEntryId,i=n.hasMore}t.signal.aborted||(t_("instant"),em(null))}finally{no.current=!1}})(),()=>{t.abort(),em(null)}},[tD,nv,ex,eh,t_,i,r?.id]),(0,u.useLayoutEffect)(()=>{let e=ni.current;if(!eh||!e||i)return;let t=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===eh.anchorEntryId);if(t instanceof HTMLElement){tU(t,eh.anchorOffset),em(null);return}ef&&(t_("instant"),em(null))},[ej,eh,ef,t_,tU,i,t7]),(0,u.useEffect)(()=>{if(!i||ex)return;let e=new AbortController;return(async()=>{let t=ng.current,n=t.entryIds.includes(i.entryId);if(!n&&!tJ&&t.hasEarlierMessages&&t.historyCursor&&!no.current){no.current=!0;let r=tp.current;r&&(na.current=r.scrollHeight-r.scrollTop);let s=await nv(i.sessionId,t.historyCursor,{tail:200,signal:e.signal});no.current=!1,n=!!s?.entryIds.includes(i.entryId)}e.signal.aborted||(n?(na.current=null,ne(e=>Math.max(e,(ng.current.entryIds.length+200)*2)),np(i)):s?.(i))})(),()=>e.abort()},[i,ex,tJ,nv,s,tp]),(0,u.useLayoutEffect)(()=>{if(!nu||nu!==i)return;let e=`[data-entry-id="${CSS.escape(nu.entryId)}"]`,t=tp.current?.querySelector(nh?.role==="user"?e:`${e} [data-search-target]`);t&&(tU(t),t.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),np(null),s?.(nu)},[nu,i,nh,tp,tU,s]),(0,u.useEffect)(()=>{let e=tp.current;if(!nt||!e)return;let t=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||no.current)return;if(!eN){na.current=e.scrollHeight-e.scrollTop,ne(e=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e+t})(e));return}if(!eC||eC===nx.current)return;let n=r?.id??tu.current;n&&(no.current=!0,na.current=e.scrollHeight-e.scrollTop,nv(n,eC).finally(()=>{no.current=!1}))},{root:e,threshold:0});return t.observe(nt),()=>t.disconnect()},[nt,t7,eC,eN,r,nv,tu,tp]),(0,u.useEffect)(()=>{ne(e=>Math.max(e,eb.length))},[eb.length]),(0,u.useEffect)(()=>{if(null==na.current)return;let e=tp.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-na.current),na.current=null}},[t7,tp]);let nb=eX?[eX.sessionId,eX.sessionFile??"",eX.sessionName??"",eX.userMessages,eX.assistantMessages,eX.toolCalls,eX.toolResults,eX.totalMessages,eX.tokens.input,eX.tokens.output,eX.tokens.cacheRead,eX.tokens.cacheWrite,eX.tokens.total,eX.cost??0,eX.totalActiveMs??0].join("|"):null,ny=(0,u.useRef)(eX);ny.current=eX,(0,u.useEffect)(()=>{z?.(ny.current)},[nb,z]),(0,u.useEffect)(()=>()=>{z?.(null)},[z]);let nw=eK?`${eK.percent??"null"}|${eK.contextWindow}|${eK.tokens??"null"}`:null,nk=(0,u.useRef)(eK);nk.current=eK,(0,u.useEffect)(()=>{D?.(nk.current)},[nw,D]),(0,u.useEffect)(()=>()=>{D?.(null)},[D]);let nS=(0,u.useCallback)(async e=>{let t=r?.cwd??c;if(!t)return void tn({type:"warning",message:er("chat.dropNeedsCwd")});try{var n;let r,{status:i,data:s}=await ry(t,e,"skip");if(200!==i&&207!==i)throw Error(s.error??`HTTP ${i}`);let l=s.uploaded??[],a=s.skipped??[],o=(n=[...l,...a],r=new Set(n),e.filter(e=>r.has(e.name)).map(e=>rb(e.name,!1)).join(""));for(let e of(o&&I?.current?.insertText(o),l.length>0&&(tn({type:"success",message:er("chat.dropUploaded",{count:l.length})}),K?.()),a.length>0&&tn({type:"warning",message:er("chat.dropAlreadyExists",{names:a.join(", ")})}),s.errors??[]))tn({type:"error",message:er("chat.dropFailed",{message:`${e.name}: ${e.error}`})})}catch(e){tn({type:"error",message:er("chat.dropFailed",{message:e instanceof Error?e.message:String(e)})})}},[tn,I,c,K,r?.cwd,er]),nC=(0,u.useCallback)(e=>{let{images:t,files:n,folders:r}=function(e){let t=[],n=[],r=[];for(let i of e)"folder"===i.kind?r.push(i.name):i.file.type.startsWith("image/")?t.push(i.file):n.push(i.file);return{images:t,files:n,folders:r}}(e);t.length>0&&I?.current?.addImages(t),r.length>0&&tn({type:"warning",message:er("chat.dropFoldersUnsupported",{names:r.join(", ")})}),n.length>0&&nS(n)},[tn,I,er,nS]),nN=(0,u.useCallback)(e=>{nC(e.map(e=>({kind:"file",file:e})))},[nC]),{isDragOver:nE,handleDragEnter:nM,handleDragOver:n$,handleDragLeave:nI,handleDrop:nT}=function(e){let[t,n]=(0,u.useState)(!1),r=(0,u.useRef)(0),i=(0,u.useCallback)(e=>{rj(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,u.useCallback)(e=>{rj(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},[]);return{isDragOver:t,handleDragEnter:i,handleDragOver:s,handleDragLeave:(0,u.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,u.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(rk(t.dataTransfer))},[e])}}(nC),nR=e$||tK,nA=(0,u.useMemo)(()=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.map(i4);for(let i=0;i<e.length;){var r;if(i3(e[i])){i+=1;continue}let s=i+1;for(;s<e.length&&!i3(e[s]);)s+=1;let l=e[s];if((l?"assistant"===l.role:!0===t.openTail)&&(r=e[i-1],r?.role==="assistant"&&("stop"===r.stopReason||"aborted"===r.stopReason))&&!n.slice(i,s).includes(!0)){let t=-1;for(let n=s-1;n>=i;n--){if("custom"!==e[n].role){if(-1!==t)break;continue}if(-1===t&&(t=n),!i2(e[n])){t=n;break}}-1!==t&&(n[t]=!0)}i=s}return n})(eb,{openTail:nR}),[eb,nR]),nL=eb.reduce((e,t,n)=>e+ +!!i8(t,nA[n]),0),nP=(0,u.useMemo)(()=>{let e=new Map(ey);for(let t of eb)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ey,eb]),nz=(0,u.useMemo)(()=>new WeakMap,[]),nW=(0,u.useMemo)(()=>{let e=new Set,t=[];for(let n=eb.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}(eb[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eb]),nF=((t=(0,u.useRef)([])).current=Array(nL).fill(null).map((e,n)=>t.current[n]??null),t),nD=(0,u.useCallback)(()=>{ne(e=>Math.max(e,2*eb.length))},[eb.length]),n_=to&&0===eb.length&&!tK&&!tJ;nj(tp,!!r?.id||!n_);let nB=r?.cwd??c??void 0,[nH,nU]=er("chat.newSessionProjectWelcome").split("{project}"),nK=(0,u.useRef)(null),nq=(0,u.useRef)(0),nV=(0,u.useRef)(null),nZ=(0,u.useRef)(!1),nJ=(0,u.useRef)(null);(0,u.useLayoutEffect)(()=>{let e=nK.current;if(!e$||!tm){nJ.current=null,nq.current=0,nZ.current=!1,e&&(e.style.height="");return}let t=tp.current,n=nr.current,r=th.current;if(!t||!n||!r||!e)return;let i=!1,s=()=>{var s;let l;if(i||tp.current!==t||nr.current!==n||th.current!==r||nK.current!==e)return;let a=t.getBoundingClientRect().top,o=Math.max(0,r.getBoundingClientRect().top-a+t.scrollTop-16),c=e.getBoundingClientRect().top-a+t.scrollTop,d=(s=t.clientHeight,0===(l=Math.max(0,o))?0:Math.max(0,Math.ceil(l+s-Math.max(0,c)))),u=!nZ.current;u&&(nZ.current=!0),d!==nq.current&&(nq.current=d,e.style.height=d>0?`${d}px`:"",u&&d>0&&tW())};nJ.current=s,s();let l="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==nV.current||(nV.current=requestAnimationFrame(()=>{nV.current=null,s()}))});return l?.observe(t),l?.observe(n),l?.observe(r),()=>{i=!0,nJ.current===s&&(nJ.current=null),l?.disconnect(),null!==nV.current&&(cancelAnimationFrame(nV.current),nV.current=null)}},[e$,th,eb.length,tm,tp,tW]);let nY=(0,u.useCallback)(()=>{nJ.current?.()},[]);(0,u.useLayoutEffect)(nY,[tK,tq,nY]);let nG=eY?eD[`${eY.provider}:${eY.modelId}`]??null:null,nX=eY?e_[`${eY.provider}:${eY.modelId}`]??null:null,nQ=(0,d.jsx)(de,{ref:I,onSend:tf,onAbort:tg,onSideChat:M&&!v(r?.relation)?t5:void 0,onSteer:e$?tC:void 0,onFollowUp:e$?tN:void 0,onPromptWithStreamingBehavior:e$?tE:void 0,isStreaming:tJ,model:eY,isAutoModelSelection:tr,modelNames:eR,modelList:eA,modelError:eL,missingCwd:eP,onForkMissingCwd:ez?t8:void 0,modelScopeWarnings:eO,allModelList:eF,onLoadAllModels:eW?tO:void 0,onModelChange:tk,modelSwitching:eG,defaultModel:ts,onSetDefaultModel:tL,onCompact:r||to?tS:void 0,onAbortCompaction:tM,isCompacting:eV,compactError:eZ,onDismissCompactError:t$,compactResult:eJ,toolPreset:eB,onToolPresetChange:r&&!v(r.relation)||to?tR:void 0,thinkingLevel:eH,isAutoThinkingSelection:ti,onThinkingLevelChange:r||to?tA:void 0,availableThinkingLevels:nG,thinkingLevelMap:nX,savedDefaultThinkingLevel:tl,onSetDefaultThinkingLevel:r||to?tP:void 0,retryInfo:eU,queuedMessages:e1,inputHistory:nW,onRecallQueue:tI,slashCommands:eQ,slashCommandsLoading:e0,onLoadSlashCommands:tz,extensionUiOpen:!!(e4||e8),onBuiltinCommand:tT,soundEnabled:X,onSoundToggle:Q,onAudioUnlock:et,draftKey:r?.id??p??void 0,cwd:r?.cwd??c,onAttachFiles:nN,sessionStatsControl:W});return ex?(0,d.jsx)("div",{role:"status",className:"chat-loading-state flex h-full items-center justify-center text-text-muted",children:er("chat.loadingSession")}):ev?(0,d.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ev}):(0,d.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)",...r?.relation?.kind==="subagent"?ie(r.id):void 0},onDragEnter:nM,onDragOver:n$,onDragLeave:nI,onDrop:nT,children:[nE&&(0,d.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,d.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,d.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,d.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,d.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,d.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,d.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,d.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,d.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,d.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,d.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,d.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,d.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,d.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,d.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,d.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,d.jsx)("div",{style:{position:"absolute",top:12,left:36*!es,right:0,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,d.jsx)(u$,{notices:e2,floating:!0,onPauseChange:tt})}),(0,d.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[e4&&(0,d.jsx)(uR,{request:e4,waitingCount:e3,onRespond:e7},e4.id),e8&&(0,d.jsx)(uA,{request:e8,waitingCount:e6,onInput:te},e8.id),!n_&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{ref:tp,className:"chat-transcript-scroll scrollbar-subtle min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-gutter:stable]",style:{visibility:eh?"hidden":void 0},children:(0,d.jsx)("div",{className:"chat-transcript-gutter",style:{minWidth:0,padding:"0 16px"},children:(0,d.jsxs)("div",{className:"chat-transcript-column",ref:nr,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var e;let t,n,i=-1;for(let e=eb.length-1;e>=0;e--)if("user"===eb[e].role){i=e;break}let s=-1;for(let e=eb.length-1;e>=0;e--)if(nA[e]){s=e;break}let l=new Map,a=0;eb.forEach((e,t)=>{i8(e,nA[t])&&l.set(t,a++)});let o=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.messageOverride??eb[e];if("custom"===n.role&&"pi-web:side-boundary"===n.customType)return(0,d.jsx)(uE,{},"side-chat-divider");if(i2(n))return null;let s=!1===t.withNotices?[]:aX(eb[e]),a=i8(n,nA[e]),o=l.get(e),c=t.keyPrefix??"message",p=ek[e],h=!1;if("assistant"===n.role){h=!0;for(let t=e+1;t<eb.length&&!nA[t];t++)if("assistant"===eb[t].role){h=!1;break}h&&tK&&e===eb.length-1&&(h=!1)}void 0!==t.showTimestamp&&(h=t.showTimestamp);let m=void 0===ej[e]?eS.get(eb[e]):void 0,f=(0,d.jsx)(ot,{message:n,toolResults:nP,toolClocks:ew,modelNames:eR,cwd:nB,onOpenFile:_,onOpenSubagent:q,entryId:ej[e],searchBlock:ej[e]===nu?.entryId?nm:void 0,onFork:eI||to?void 0:tX,forkEntryId:m,forking:eq===(ej[e]??m),onEditContent:tJ?void 0:ty,onCancelEdit:tw,isEditing:tc===ej[e],hideAssistantHeader:t.hideAssistantHeader,showTimestamp:h,prevTimestamp:e>0?eb[e-1].timestamp:void 0,sessionId:r?.id??tu.current??void 0,writtenFiles:t.writtenFiles,turnDurationMs:t.turnDurationMs,onCompact:t.recoverTruncation?tS:void 0,isCompacting:t.recoverTruncation?eV:void 0,compactError:t.recoverTruncation?eZ:void 0},`${c}-view-${p}`),g=s.length>0?(0,d.jsx)(a4,{notices:s},`${c}-notices-${p}`):null;return a&&void 0!==o?(0,d.jsxs)("div",{"data-entry-id":ej[e],ref:!1===t.attachRef?void 0:t=>{nF.current[o]=t,e===i&&(th.current=t)},children:[f,g]},`${c}-${p}`):(0,d.jsxs)(u.Fragment,{children:[f,g]},`${c}-${p}`)},c=[];for(let e=0;e<eb.length;){let t,n=nA[e];if(!n&&0!==e){c.push(o(e)),e+=1;continue}let r=n?e:-1,i=n?e:0,a=e+1;for(;a<eb.length&&!nA[a];)a+=1;let u=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&sn(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}(eb,r,a),p=(tJ||tK)&&a===eb.length&&r===s;if(-1===u||p){for(let e=i;e<a;e++)c.push(o(e));e=a;continue}n&&c.push(o(r));let h=n&&ej[r]?function(e,t,n){let r,i,s,l=sC(e[t]?.timestamp);if(void 0===l)return;for(let r=t+1;r<n&&"custom"===e[r].role;r++){let t=sC(e[r].timestamp);void 0!==t&&(l=Math.max(l,t))}let a=!1,o=0;for(let l=t+1;l<n;l++){let t=e[l];if("assistant"===t.role){var c;void 0!==i&&void 0!==s&&(o+=Math.max(0,s-i)),i=s=void 0;let e=function(e){if("assistant"!==e.role)return;let t=sC(e.timestamp),n=sC(e.durationMs);return void 0!==t&&void 0!==n?t+n:void 0}(t);a=void 0!==e,void 0!==e&&(r=Math.max(r??e,e)),void 0!==e&&"assistant"===(c=t).role&&("stop"===c.stopReason||"length"===c.stopReason)&&(i=r)}else if("toolResult"===t.role){let e=sC(t.timestamp);void 0!==e&&(r=Math.max(r??e,e))}else if(void 0!==i){let e=sC(t.timestamp);void 0!==e&&(s=Math.max(s??e,e))}}if(a&&void 0!==r)return Math.max(0,r-l-o)}(eb,r,a):void 0,m=function(e,t){let n=e.get(t);if(n)return n;let{answerBlocks:r}=sn(t),i=r.length>0||i9(t)||se(t)||i7(t)?sS(t,r):null,s=t.content.indexOf(r[0]),l={answer:i,process:sS(t,t.content.slice(0,s<0?void 0:s),{omitUsage:!!i,omitStop:!!i})};return e.set(t,l),l}(nz,eb[u]),f=m.answer,g=(f?.content??[]).some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0),x="sunbeam"===ei&&g,v=[],b=0,y=0,w=!1;for(let e=r+1;e<=u;e++){let n=eb[e];if("custom"===n.role){if(i2(n))continue;w||=!!(nu&&nu.entryId===ej[e]),b+=1,v.push(o(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===u?m.process:n,i=e!==u||!f,s=i5(r);if(0===s.length){let t=i?aX(n):[];t.length>0&&v.push((0,d.jsx)(a4,{notices:t},`process-notices-${ek[e]}`));continue}t??=l.get(e),y+=s.filter(e=>"toolCall"===e.type).length,b+=1,w||=!!(nu&&ej[e]===nu.entryId&&(!nm||s.includes(nm))),v.push(o(e,{attachRef:!1,keyPrefix:"process",messageOverride:r,hideAssistantHeader:x&&r.provider===f?.provider&&r.model===f?.model,showTimestamp:!1,withNotices:i}))}let j=null;if(0===b)c.push(...v);else if(v.length>0){let e=eb.slice(r+1,f?u:u+1);j=(0,d.jsx)("div",{ref:void 0===t?void 0:e=>{nF.current[t]=e},children:(0,d.jsx)(uC,{messageCount:b,toolCallCount:y,durationMs:h,cost:function(e){let t=0;for(let n of e){if("assistant"!==n.role)continue;let e=n.usage?.cost?.total;"number"==typeof e&&Number.isFinite(e)&&e>0&&(t+=e)}return t>0?t:void 0}(e),cacheMisses:function(e){let t;for(let n of e)for(let e of aX(n))"cache_miss"===e.kind&&(t??={count:0,missedTokens:0,missedCost:0},t.count+=1,t.missedTokens+=e.missedTokens,t.missedCost+=e.missedCost);return t}(e),defaultExpanded:!g,reveal:w,t:er,children:v},g?"answered":"unanswered")},`process-group-${ek[i]}`),x||c.push(j)}let k=x&&null!==j;if(f){let e=[];for(let t=r+1;t<=u;t++){let n=eb[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=o(u,{messageOverride:f,hideAssistantHeader:k,writtenFiles: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,function(e,t,n){let r=new Set,i=[];for(let l of e){var s;if("toolCall"!==l.type||!(sm(s=l.toolName)||sf(s))&&!sg(l.toolName))continue;let e=t?.get(l.toolCallId);if(e&&!e.isError)for(let t of sg(l.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of sx(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!sv(e)||!sv(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(sb(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=sk(sj(n.preview));if(e.length>0)return e}return sk(sw(sx(e)))}(l.input,e):[function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(l.input)]){if(!t)continue;let e=function(e,t){let n;if(!e)return null;let r=sa(e)||sa(t),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),l=t?i(t).replace(/\/+$/,""):void 0,a=/^[a-zA-Z]:\//.test(s),o=s.startsWith("//"),c=r?sc(s):s;if(a||o||c!==s)n=c;else if(s.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!l)return null;n=`${l}/${s}`}return sd(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,nP,nB)),turnDurationMs:0===v.length?h:void 0,recoverTruncation:a===eb.length&&!tK&&!st(f)});c.push(k?(0,d.jsxs)(oi,{message:f,modelNames:eR,children:[j,t]},`assistant-reply-${ek[i]}`):t)}for(let e=u+1;e<a;e++)c.push(o(e));e=a}let{startIndex:p}=(t=Math.min(Math.max(t7,0),Math.max(e=c.length,0)),{startIndex:n=Math.max(0,e-t),hasMore:n>0}),h=p>0||eN;return(0,d.jsxs)(d.Fragment,{children:[h&&(0,d.jsx)("div",{ref:nn,className:"py-3 text-center text-xs text-text-muted",children:er("chat.loadEarlier")}),(0,d.jsx)("div",{ref:nl,children:c.slice(p)})]})})(),tK&&tq&&(0,d.jsx)(uM,{store:eM,onCommit:nY,toolResults:nP,modelNames:eR,cwd:nB,onOpenFile:_,onOpenSubagent:q}),eV?(0,d.jsxs)("div",{className:"chat-compaction-status",role:"status","aria-live":"polite","aria-atomic":"true",children:[(0,d.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M7 3H5a2 2 0 0 0-2 2v4m14 12h2a2 2 0 0 0 2-2v-4M3 13v6a2 2 0 0 0 2 2h4M21 11V5a2 2 0 0 0-2-2h-4M8 8h8M8 12h8M8 16h5"})}),(0,d.jsxs)("span",{children:[er("chat.compactingContext"),(0,d.jsxs)("span",{className:"chat-compaction-hint",children:[" \xb7 ",er("chat.compactingHint")]}),(e1?.steering.length??0)+(e1?.followUp.length??0)>0&&(0,d.jsxs)("span",{className:"chat-compaction-hint",children:[" \xb7 ",er("chat.queued",{count:(e1?.steering.length??0)+(e1?.followUp.length??0)})]})]})]}):e$&&!tq&&ta&&(0,d.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,d.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}(ta,er)})}),eI&&!eT&&(0,d.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,d.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:er("chat.runningCommand")})}),eT&&(0,d.jsx)(ot,{message:{role:"bashExecution",command:eT.command,output:"",...eT.result,excludeFromContext:eT.excludeFromContext,timestamp:eT.startedAt},sessionId:r?.id??tu.current??void 0,onOpenSubagent:q}),eT?.liveOutput&&!eT.result&&(0,d.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,d.jsx)("pre",{className:"m-0 flex flex-col justify-end overflow-hidden whitespace-pre-wrap break-words",style:{maxHeight:"29em"},children:(0,d.jsx)("span",{children:eT.liveOutput.replace(/\n+$/,"").split("\n").slice(-20).join("\n")})})}),(0,d.jsx)("div",{ref:nK,"aria-hidden":"true"})]})})}),!es&&(0,d.jsx)("div",{className:"chat-minimap-gutter",style:{order:-1,width:36,flexShrink:0,display:"flex"},children:!eh&&(0,d.jsx)(dd,{messages:eb,getStreamingMessage:tZ,scrollContainer:tp,messageRefs:nF,onRevealHistory:nD,turnsBefore:eE,turnAnchors:nA})})]})]}),J&&(0,d.jsx)(du,{rootRef:nr,chatInputRef:I,startSideChat:M&&!v(r?.relation)?tx:void 0}),(0,d.jsxs)("div",{className:"relative flex min-h-0 flex-col",children:[!n_&&(0,d.jsx)("div",{style:{position:"absolute",bottom:"100%",left:36*!es,right:0,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,d.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${td&&!eh?" is-visible":""}`,title:er("chat.scrollToLatest"),"aria-label":er("chat.scrollToLatest"),onClick:()=>t_("smooth"),children:(0,d.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,d.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),n_&&(0,d.jsx)("div",{className:"new-session-hero",style:{paddingLeft:es?16:52,paddingRight:16},children:(0,d.jsxs)("div",{className:"new-session-hero-inner",style:{maxWidth:"var(--chat-content-max-width, 820px)"},children:[(0,d.jsxs)("div",{className:"new-session-intro",children:[(0,d.jsx)(dt,{}),(0,d.jsx)("h1",{className:"new-session-welcome",children:f?(0,d.jsxs)(d.Fragment,{children:[nH,(0,d.jsx)("button",{type:"button",className:"new-session-welcome-project",title:er("workspace.newSessionContext"),onClick:e=>g?.(e.currentTarget),children:f}),nU]}):er("chat.newSessionWelcome")})]}),m]})}),nQ,(0,d.jsx)(dg,{statuses:e5,widgets:e9,onCommand:tf,commandsDisabled:tJ})]}),n_&&(0,d.jsx)("div",{className:"min-h-0 flex-1"}),tQ&&(0,d.jsx)(nO,{busy:t1,error:t4,onCancel:()=>{t0(!1),t3(null)},onSelect:e=>void t6(e)})]})}function uE(){let{t:e}=(0,ns.s)();return(0,d.jsxs)("div",{role:"separator",className:"my-4 flex items-center gap-3 text-xs",style:{color:"var(--text-dim)"},children:[(0,d.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}}),(0,d.jsx)("span",{children:e("sideChat.divider")}),(0,d.jsx)("span",{className:"h-px flex-1",style:{background:"var(--border)"}})]})}let uM=(0,u.memo)(function(e){let{store:t,onCommit:n,toolResults:r,modelNames:i,cwd:s,onOpenFile:l,onOpenSubagent:a}=e,o=uv(t,uw);return((0,u.useLayoutEffect)(n,[o,n]),o)?(0,d.jsx)(ot,{message:o,toolResults:r,isStreaming:!0,modelNames:i,cwd:s,onOpenFile:l,onOpenSubagent:a},aY(o)):null});function u$(e){let{notices:t,floating:n=!1,onPauseChange:r}=e;return 0===t.length?null:(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!n},children:t.map((e,i)=>{var s;let l,a,o,c="error"===e.type?"#ef4444":"warning"===e.type?"#d97706":"success"===e.type?"#10b981":"var(--accent)";return(0,d.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>r?.(e.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||r?.(null)},onFocus:()=>r?.(e.id),onBlur:e=>{e.currentTarget.matches(":hover")||r?.(null)},style:{display:"flex",alignItems:"flex-start",gap:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(i!==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,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:c,flexShrink:0,marginTop:25.5}}),(0,d.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:(s=e.message,l=[],a=(e,t)=>{if(!t)return;let n=l[l.length-1];n?.kind===e?n.text+=t:l.push({kind:e,text:t})},o=!1,s.split("\n").forEach((e,t)=>{let n=iJ.test(e);t>0&&a(n&&o?"art":"text","\n"),a(n?"art":"text",e),o=n}),l).map((e,t)=>"art"===e.kind?(0,d.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,d.jsx)(u.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(iY)){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(iG.test(i))r-=1;else if(")"===i&&n>t)r-=1,n-=1;else break}return e.slice(0,r)}(r[0]);if(!/^https?:\/\/[^/]/i.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,d.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 uI(e){let{count:t}=e,{t:n}=(0,ns.s)();return t<=0?null:(0,d.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionMoreWaiting",{count:t})})}function uT(e){let{expanded:t}=e;return(0,d.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,d.jsx)("path",{d:"M3.5 1v2.5H1M6.5 1v2.5H9M6.5 9v-2.5H9M3.5 9v-2.5H1"}):(0,d.jsx)("path",{d:"M1 3.5V1h2.5M6.5 1H9v2.5M9 6.5V9H6.5M3.5 9H1V6.5"})})}function uR(e){let{request:t,waitingCount:n,onRespond:r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)("editor"===t.method?t.prefill??"":""),[a,o]=(0,u.useState)(!1),c=(0,u.useRef)(null),p=(0,u.useRef)(null),[h,m]=(0,u.useState)(null),[f,g]=(0,u.useState)(!1),x=(0,u.useCallback)(()=>g(e=>!e),[]),[v,b]=(0,u.useState)(()=>Date.now()),y=(0,u.useCallback)(e=>e?.focus(),[]),w=function(e){if("select"===e.method&&e.options.length>0)return iK(e.options[0]);if("confirm"===e.method){let t=iK(e.message).split("\n").find(e=>e.trim());return t?.trim()}}(t),j=void 0===t.expiresAt?null:Math.max(0,Math.ceil((t.expiresAt-v)/1e3));(0,u.useLayoutEffect)(()=>{if(a)return;let e=c.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()}},[a]),(0,u.useEffect)(()=>{if(void 0===t.expiresAt)return;let e=setInterval(()=>b(Date.now()),1e3);return()=>clearInterval(e)},[t.expiresAt]);let k=null!==j&&(0,d.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:i("chat.extensionExpiresIn",{seconds:j})}),S=()=>{"confirm"===t.method?r(t,{confirmed:!0}):r(t,{value:s})};return(0,d.jsx)("div",{onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||(e.preventDefault(),e.stopPropagation(),r(t,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:a?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:a?(0,d.jsxs)("button",{type:"button",onClick:()=>o(!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,d.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:i("chat.extensionPending")}),(0,d.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:iK(t.title)}),w&&(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:w}),(0,d.jsx)(uI,{count:n}),k,(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:i("chat.extensionExpand")})]}):(0,d.jsxs)("div",{ref:c,role:"dialog","aria-label":iK(t.title),style:{pointerEvents:"auto",width:f?"100%":`min(${h??560}px, 100%)`,maxHeight:f?"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,d.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,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:iK(t.title)}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,d.jsx)("span",{children:i("chat.extensionRequest")}),(0,d.jsx)(uI,{count:n}),k]})]}),(0,d.jsx)("button",{type:"button",onClick:x,title:i(f?"chat.extensionRestoreSize":"chat.extensionMaximize"),"aria-label":i(f?"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,d.jsx)(uT,{expanded:f})}),(0,d.jsx)("button",{type:"button",onClick:()=>o(!0),"aria-expanded":!0,title:i("chat.extensionCollapse"),"aria-label":i("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,d.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,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,d.jsxs)("div",{ref:p,style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===t.method&&(0,d.jsx)(ah,{children:iK(t.message)}),"select"===t.method&&(0,d.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,d.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":iK(e),ref:0===n?y:void 0,onClick:()=>r(t,{value:e}),onKeyDown:n=>{("Enter"===n.key||" "===n.key)&&(n.preventDefault(),r(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,d.jsx)("div",{inert:!0,children:(0,d.jsx)(ah,{children:iK(e)})})},e))}),"input"===t.method&&(0,d.jsx)("input",{autoFocus:!0,value:s,placeholder:t.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||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,d.jsx)("textarea",{autoFocus:!0,value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&229!==e.nativeEvent.keyCode&&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,d.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,d.jsx)("button",{autoFocus:"confirm"===t.method||"select"===t.method&&0===t.options.length,onClick:()=>r(t,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:i("chat.cancel")}),"confirm"===t.method?(0,d.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:i("chat.confirm")}):"select"!==t.method?(0,d.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:i("chat.submit")}):null]})]})})}function uA(e){let{request:t,waitingCount:n,onInput:r}=e,{t:i}=(0,ns.s)(),s=(0,u.useRef)(null),l=(0,u.useRef)(!1),[a,o]=(0,u.useState)(!1),c=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(iU,""),i=iK(e).trimEnd();if(t.test(i))continue;let s=e,l=iZ(s);("│"===l||"┃"===l)&&" "===iZ(s=iV(s,0))&&(s=iV(s,0));let a=function(e){let t=iq(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),o=a>=0?iq(s)[a]?.char:void 0;("│"===o||"┃"===o)&&(s=iV(s,a)),n.push(function(e){let t=e;for(;;){let e=iq(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&&""===iK(n[0]).trim();)n.shift();for(;n.length>0&&""===iK(n[n.length-1]).trim();)n.pop();return n.length?n:e.map(e=>e.replace(iU,""))}(t.lines),p=c.map(iK).find(e=>e.trim())?.trim();return(0,u.useEffect)(()=>{a||s.current?.focus()},[a]),(0,d.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:a?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:a?(0,d.jsxs)("button",{type:"button",onClick:()=>o(!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,d.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:i("chat.extensionPending")}),(0,d.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:i("chat.extensionPanel")}),p&&(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),(0,d.jsx)(uI,{count:n}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:i("chat.extensionExpand")})]}):(0,d.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||s.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,d.jsx)("textarea",{ref:s,"aria-label":i("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:e=>{if(l.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode)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;if(" "===e)return"\0";if("/"===e||"-"===e)return"\x1f";let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}let t=iX[e.key],n=1+ +!!e.shiftKey+2*!!e.altKey+4*!!e.ctrlKey;if(n>1&&!(e.altKey&&!e.ctrlKey&&!e.shiftKey&&iQ[e.key])){if(/^\x1b\[[ABCDHF]$/.test(t??""))return`\x1b[1;${n}${t.at(-1)}`;if(/^\x1b\[\d+~$/.test(t??""))return`${t.slice(0,-1)};${n}~`}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=iQ[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":" ":iX[e.key]??null}(e);n&&(e.preventDefault(),e.stopPropagation(),r(t,n))},onInput:e=>{if(l.current||e.nativeEvent.isComposing)return;let n=e.currentTarget.value;e.currentTarget.value="",n&&r(t,n)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.current=!1;let n=e.currentTarget;queueMicrotask(()=>{let e=n.value;n.value="",e&&r(t,e)})},onPaste:e=>{e.preventDefault();let n=e.clipboardData.getData("text");n&&r(t,function(e){let t=e;for(;t.includes(i0)||t.includes(i1);)t=t.split(i0).join("").split(i1).join("");return`${i0}${t}${i1}`}(n))},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,d.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:i("chat.extensionPanel")}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,d.jsx)(uI,{count:n}),(0,d.jsx)("button",{type:"button",onClick:()=>o(!0),"aria-expanded":!0,title:i("chat.extensionCollapse"),"aria-label":i("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,d.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,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,d.jsx)("button",{onClick:()=>r(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:i("chat.close")})]})]}),(0,d.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,d.jsx)(dh,{text:c.join("\n")})})]})})}var uL=n(65954),uP=n.n(uL);function uz(e){let{usage:t,onClick:n,expanded:r}=e,{t:i}=(0,ns.s)(),s=(0,u.useId)(),l=(0,u.useRef)(null),a=(0,u.useRef)(void 0),[o,c]=(0,u.useState)(null),p=null===t.percent?null:Math.max(0,Math.min(100,t.percent)),h=null===p?i("session.contextUnknown"):i("session.contextPercent",{used:Math.round(p),remaining:100-Math.round(p)}),m=i("session.contextTokens",{used:null===t.tokens?"?":dZ(t.tokens),total:dZ(t.contextWindow)}),f=()=>{clearTimeout(a.current),c(null)},x=()=>{clearTimeout(a.current);let e=l.current?.getBoundingClientRect();e&&c({left:Math.max(118,Math.min(window.innerWidth-118,e.left+e.width/2)),top:e.top-9})},v=()=>{a.current=setTimeout(f,120)};return(0,u.useEffect)(()=>{let e=()=>c(null),t=t=>{"Escape"===t.key&&(t.stopPropagation(),e())};return o&&(window.addEventListener("resize",e),document.addEventListener("scroll",e,!0),document.addEventListener("keydown",t,!0)),()=>{window.removeEventListener("resize",e),document.removeEventListener("scroll",e,!0),document.removeEventListener("keydown",t,!0)}},[o]),(0,u.useEffect)(()=>()=>clearTimeout(a.current),[]),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{ref:l,type:"button",className:uP().trigger,"data-context-usage":"","aria-label":`${i("session.contextWindow")}: ${h}; ${m}`,"aria-describedby":o?s:void 0,"aria-expanded":r,"aria-controls":"workspace-usage-page",onPointerEnter:x,onPointerLeave:v,onFocus:x,onBlur:f,onClick:()=>{f(),n()},children:(0,d.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.5",opacity:"0.2"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:null!==p&&p>90?"#ef4444":null!==p&&p>70?"#d9a323":"var(--text-muted)",strokeWidth:"2.5",pathLength:"100",strokeDasharray:`${p??0} 100`,strokeLinecap:"round",transform:"rotate(-90 12 12)"})]})}),o&&(0,g.createPortal)((0,d.jsxs)("div",{id:s,role:"tooltip",className:uP().tooltip,style:{left:o.left,top:o.top},onPointerEnter:()=>clearTimeout(a.current),onPointerLeave:v,children:[(0,d.jsx)("span",{children:i("session.contextWindow")}),(0,d.jsx)("strong",{children:h}),(0,d.jsx)("span",{className:uP().counts,children:m})]}),document.body)]})}function uO(e){let{sessions:t,runningSessionIds:n,cwd:r,onSelectSession:i,onNewSession:s,onOpenProject:l}=e,{t:a,locale:o}=(0,ns.s)(),[c,p]=(0,u.useState)(8),h=t.filter(e=>!v(e.relation)).sort((e,t)=>Date.parse(t.modified)-Date.parse(e.modified)),m=c<h.length,f=new Intl.DateTimeFormat(o,{month:"short",day:"numeric"});return(0,d.jsx)("div",{className:"home-view",role:"region","aria-label":a("navigation.home"),children:(0,d.jsxs)("div",{className:"home-content",children:[(0,d.jsxs)("div",{className:"home-intro",children:[(0,d.jsx)(dt,{}),(0,d.jsx)("h1",{children:a("chat.newSessionWelcome")}),(0,d.jsx)("p",{children:a("home.description")})]}),(0,d.jsxs)("div",{className:"home-actions",children:[(0,d.jsxs)("button",{type:"button",className:"home-new-task","aria-describedby":"home-project-context",onClick:s,children:[(0,d.jsx)(n8,{size:16}),(0,d.jsx)("span",{children:a("home.newTask")})]}),(0,d.jsxs)("button",{type:"button",className:"home-open-project",onClick:l,children:[(0,d.jsx)(n3,{size:16}),(0,d.jsx)("span",{children:a("home.openProject")})]}),(0,d.jsxs)("span",{id:"home-project-context",className:"home-project-context",title:r??void 0,children:[r&&(0,d.jsx)(n3,{size:14}),(0,d.jsx)("span",{children:r?e2(r)||r:a("home.chooseProject")})]})]}),(0,d.jsxs)("section",{className:"home-recent","aria-labelledby":"home-recent-title",children:[(0,d.jsx)("h2",{id:"home-recent-title",children:a("home.recentTasks")}),h.length?(0,d.jsx)("div",{className:"home-session-list",id:"home-session-list",children:h.slice(0,c).map(e=>{let t=new Date(e.modified),r=e7(e);return(0,d.jsxs)("a",{className:"home-session",href:J(e.id),onClick:t=>{Y(t)&&(t.preventDefault(),i(e))},children:[(0,d.jsx)(rr,{size:17}),(0,d.jsxs)("span",{className:"home-session-details",children:[(0,d.jsx)("span",{className:"home-session-title",title:r,children:r}),(0,d.jsx)("span",{className:"home-session-project",title:e.cwd,children:e2(e.projectRoot||e.cwd)||e.cwd})]}),n.has(e.id)?(0,d.jsx)("span",{className:"home-running",children:a("home.running")}):Number.isFinite(t.getTime())&&(0,d.jsx)("time",{dateTime:t.toISOString(),children:f.format(t)})]},e.id)})}):(0,d.jsx)("p",{className:"home-empty",children:a("home.noTasks")}),h.length>8&&(0,d.jsxs)("button",{type:"button",className:"home-recent-more","aria-controls":"home-session-list","data-show-less":!m,onClick:()=>p(m?c+8:8),children:[(0,d.jsx)("span",{children:a(m?"home.showMore":"home.showLess")}),(0,d.jsx)(nV,{size:14})]})]})]})})}function uW(e){let{snapshot:t,projectKey:n,onProjectChange:r,onSelectSession:i,onRestore:s,onDelete:l,onDeleteMany:a,onRefresh:o}=e,{t:c,locale:p}=(0,ns.s)(),[h,m]=(0,u.useState)(""),[f,g]=(0,u.useState)(()=>new Map),[x,v]=(0,u.useState)(null),[b,y]=(0,u.useState)(null),[w,j]=(0,u.useState)(!1),[k,S]=(0,u.useState)(null),C=(0,u.useRef)(!1),N=(0,u.useRef)(null),[E,M]=(0,u.useState)(()=>new Map),$=(0,u.useRef)(null),I=(0,u.useRef)(null),T=(0,u.useRef)(!1),R=(0,u.useMemo)(()=>[...new Map(t.entries.map(e=>[e.project.key,e.project])).values()],[t.entries]),A=(0,u.useMemo)(()=>{var e;let r;return e=t.entries,r=h.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean),e.filter(e=>{if(n&&e.project.key!==n)return!1;let t=[e7(e.session),e.session.firstMessage,e.project.name,e.project.root,e.session.cwd].join("\n").toLocaleLowerCase();return r.every(e=>t.includes(e))})},[t.entries,h,n]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of A){let n=e.get(t.project.key);n?n.push(t):e.set(t.project.key,[t])}return[...e.values()]},[A]),P=(0,u.useMemo)(()=>new Intl.DateTimeFormat(p,{year:"numeric",month:"short",day:"numeric"}),[p]);(0,u.useEffect)(()=>{t.loaded&&n&&!R.some(e=>e.key===n)&&r(null)},[t.loaded,n,R,r]),(0,u.useLayoutEffect)(()=>{(f.size||T.current)&&t_(document,window.matchMedia?.("(pointer: coarse)").matches?I.current:$.current),T.current=!1},[f,t.entries,w]),(0,u.useEffect)(()=>{v(null)},[h,n]),(0,u.useEffect)(()=>{x&&!t.entries.some(e=>e.session.id===x)&&v(null)},[t.entries,x]);let z=async e=>{if(!f.has(e)&&!b&&!C.current){g(t=>new Map(t).set(e,"restore")),M(t=>{let n=new Map(t);return n.delete(e),n});try{if(!await s(e))throw Error("restore failed")}catch{M(t=>new Map(t).set(e,c("archive.restoreFailed")))}finally{T.current=!0,g(t=>{let n=new Map(t);return n.delete(e),n})}}},O=e=>{v(null),I.current?.querySelector(`[data-archived-session="${CSS.escape(e)}"] .archive-workspace-delete`)?.focus()},W=async e=>{if(!f.has(e)&&!b&&!C.current){g(t=>new Map(t).set(e,"delete")),M(t=>{let n=new Map(t);return n.delete(e),n});try{if(!await l(e))throw Error("delete failed");v(null)}catch{M(t=>new Map(t).set(e,c("archive.deleteFailed")))}finally{T.current=!0,g(t=>{let n=new Map(t);return n.delete(e),n})}}},F=()=>{C.current||(y(null),N.current?.focus())},D=async()=>{if(b?.length&&!C.current&&!f.size){C.current=!0,j(!0),S(null);try{if(!await a(b))throw Error("archive clear incomplete")}catch{S(c("archive.clearFailed"))}finally{C.current=!1,T.current=!0,j(!1),y(null)}}};return(0,d.jsxs)("div",{className:"archive-workspace",ref:I,tabIndex:-1,children:[(0,d.jsxs)("div",{className:"archive-workspace-toolbar",children:[(0,d.jsxs)("label",{className:"archive-workspace-search",children:[(0,d.jsx)(n9,{size:16}),(0,d.jsx)("input",{ref:$,type:"search",value:h,onChange:e=>m(e.target.value),maxLength:200,placeholder:c("archive.search"),"aria-label":c("archive.search"),onKeyDown:e=>{"Escape"===e.key&&h&&!e.nativeEvent.isComposing&&229!==e.keyCode&&(e.stopPropagation(),e.preventDefault(),m(""))}})]}),(0,d.jsxs)("select",{value:n??"",onChange:e=>r(e.target.value||null),"aria-label":c("archive.projectFilter"),children:[(0,d.jsx)("option",{value:"",children:c("archive.allProjects")}),R.map(e=>(0,d.jsx)("option",{value:e.key,children:e.name},e.key))]}),(0,d.jsx)("span",{className:"archive-workspace-count",role:"status",children:c("archive.count",{count:A.length})}),(0,d.jsxs)("button",{ref:N,type:"button",className:"archive-workspace-delete archive-workspace-clear",disabled:!t.loaded||!!t.error||!t.entries.length||f.size>0||w,"aria-expanded":null!==b,onClick:()=>{v(null),S(null),y(t.entries.map(e=>e.session.id))},children:[(0,d.jsx)(nG,{size:15}),c(w?"archive.deleting":"archive.clearAll")]})]}),b&&(0,d.jsxs)("div",{className:"archive-delete-confirmation archive-clear-confirmation",role:"group","aria-label":c("archive.clearAll"),onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||229===e.keyCode||(e.preventDefault(),e.stopPropagation(),F())},children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("strong",{children:c("archive.clearTitle",{count:b.length})}),(0,d.jsx)("p",{children:c("archive.clearWarning")})]}),(0,d.jsx)("button",{type:"button",autoFocus:!0,disabled:w,onClick:F,children:c("sidebar.cancel")}),(0,d.jsx)("button",{type:"button",className:"is-danger",disabled:w,onClick:()=>void D(),children:c(w?"archive.deleting":"archive.clearAll")})]}),k&&(0,d.jsxs)("div",{className:"archive-workspace-error",role:"alert",children:[(0,d.jsx)("span",{children:k}),(0,d.jsx)("button",{type:"button",onClick:o,children:c("i18n.refresh")})]}),(0,d.jsx)("p",{className:"archive-workspace-description",children:c("archive.description")}),t.error&&(0,d.jsxs)("div",{className:"archive-workspace-error",role:"alert",children:[c("archive.loadFailed"),(0,d.jsx)("button",{type:"button",onClick:o,children:c("i18n.refresh")})]}),t.loaded?A.length?L.map(e=>(0,d.jsxs)("section",{className:"archive-workspace-group","aria-label":e[0].project.name,children:[(0,d.jsxs)("h2",{title:e[0].project.root,children:[(0,d.jsx)(n3,{size:16}),(0,d.jsx)("span",{children:e[0].project.name}),(0,d.jsx)("small",{children:e.length})]}),e.map(e=>{let{session:t,archivedAt:n}=e,r=e7(t);return(0,d.jsxs)("div",{className:"archive-workspace-row","data-archived-session":t.id,children:[(0,d.jsxs)("a",{href:J(t.id),title:r,onClick:e=>{Y(e)&&(e.preventDefault(),i(t))},children:[(0,d.jsx)(nH,{size:16}),(0,d.jsx)("span",{className:"archive-workspace-title",children:r}),(0,d.jsx)("time",{dateTime:new Date(n).toISOString(),title:c("archive.archivedOn"),children:P.format(n)})]}),(0,d.jsxs)("button",{type:"button",className:"archive-workspace-restore",onClick:()=>void z(t.id),disabled:f.has(t.id)||null!==b||w,"aria-label":c("archive.restoreSession",{title:r}),children:[(0,d.jsx)(nU,{size:15}),c("restore"===f.get(t.id)?"archive.restoring":"sidebar.restore")]}),(0,d.jsxs)("button",{type:"button",className:"archive-workspace-delete",disabled:f.has(t.id)||null!==b||w,"aria-label":c("archive.deleteSession",{title:r}),"aria-expanded":x===t.id,onClick:()=>{M(e=>{let n=new Map(e);return n.delete(t.id),n}),v(t.id)},children:[(0,d.jsx)(nG,{size:15}),c("sidebar.delete")]}),x===t.id&&(0,d.jsxs)("div",{className:"archive-delete-confirmation",role:"group","aria-label":c("sidebar.deleteSession",{title:r}),onKeyDown:e=>{"Escape"===e.key&&!e.nativeEvent.isComposing&&229!==e.keyCode&&(e.preventDefault(),e.stopPropagation(),f.has(t.id)||O(t.id))},children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("strong",{children:c("sidebar.deleteSession",{title:r})}),(0,d.jsx)("p",{children:c("archive.deleteWarning")})]}),(0,d.jsx)("button",{type:"button",autoFocus:!0,disabled:f.has(t.id),onClick:()=>O(t.id),children:c("sidebar.cancel")}),(0,d.jsx)("button",{type:"button",className:"is-danger",disabled:f.has(t.id),onClick:()=>void W(t.id),children:c("delete"===f.get(t.id)?"archive.deleting":"sidebar.delete")})]}),E.has(t.id)&&(0,d.jsx)("p",{className:"archive-workspace-row-error",role:"alert",children:E.get(t.id)})]},t.id)})]},e[0].project.key)):!t.error&&(0,d.jsx)("p",{className:"archive-workspace-empty",children:c(t.entries.length?"archive.noMatches":"sidebar.noArchived")}):(0,d.jsx)("p",{className:"archive-workspace-empty",role:"status",children:c("archive.loading")})]})}var uF=n(60680),uD=n.n(uF);function u_(e){let{pose:t,dragging:r,hop:i}=e,s=(0,u.useRef)(null),l=(0,u.useRef)(null),a=(0,u.useRef)(null),o=(0,u.useRef)(null),c=(0,u.useRef)(t),p=(0,u.useRef)(r),[h,m]=(0,u.useState)(!1);return(0,u.useEffect)(()=>{let e=!1;n.e(5455).then(n.bind(n,75455)).then(t=>{let{mountPortraitMotion:n}=t;!e&&s.current&&(o.current=n(s.current,()=>{e||m(!0)},()=>{e||m(!1)}),o.current.setPose(c.current))}).catch(()=>{});let t=e=>{if("touch"===e.pointerType||e.buttons||p.current)return;let t=s.current?.getBoundingClientRect();t&&o.current?.setLook((e.clientX-t.left-t.width/2)/320)},r=()=>o.current?.setLook(0);return window.addEventListener("pointermove",t,{passive:!0}),window.addEventListener("blur",r),document.addEventListener("pointerleave",r),()=>{e=!0,o.current?.dispose(),o.current=null,window.removeEventListener("pointermove",t),window.removeEventListener("blur",r),document.removeEventListener("pointerleave",r)}},[]),(0,u.useEffect)(()=>{c.current=t,o.current?.setPose(t)},[t]),(0,u.useEffect)(()=>{if(!i||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;let e="happy"===c.current?5:12;return a.current?.cancel(),a.current=l.current?.animate([{transform:"translateY(0)",offset:0,easing:"ease-in"},{transform:"translateY(1.5px)",offset:.16,easing:"cubic-bezier(0.2, 0.7, 0.3, 1)"},{transform:`translateY(-${e}px)`,offset:.43,easing:"cubic-bezier(0.55, 0, 0.85, 0.4)"},{transform:"translateY(1px)",offset:.72,easing:"ease-out"},{transform:"translateY(-1px)",offset:.86,easing:"ease-in-out"},{transform:"translateY(0)",offset:1}],{duration:"happy"===c.current?680:820})??null,()=>{a.current?.cancel()}},[i]),(0,u.useEffect)(()=>{p.current=r,r&&a.current?.cancel()},[r]),(0,u.useEffect)(()=>{let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=()=>{e.matches&&a.current?.cancel()};return e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]),(0,d.jsxs)("span",{ref:l,className:uD().portrait,"data-dragging":r,"data-living":h,children:[(0,d.jsx)("img",{src:`/pets/lin-yue/${t}.webp`,alt:"",width:"280",height:"536",draggable:!1}),(0,d.jsx)("canvas",{ref:s,"aria-hidden":"true"})]})}let uB=Object.fromEntries(["welcome","helloReply","cheerReply","sleepReply","wakeReply","greetRun","received","replying","working","attention","backToYou","greetDone","stopped","failed"].map(e=>[`pet.${e}`,[`pet.${e}`,`pet.${e}2`,`pet.${e}3`]]));function uH(e,t,n,r){let i=n.x+8,s=n.y+8,l=Math.max(i,n.x+n.width-t.width-8),a=Math.max(s,n.y+n.height-t.height-8),o=e=>Math.max(i,Math.min(e,l)),c=e=>Math.max(s,Math.min(e,a)),d=r.map(e=>({...e,x:e.x-12,y:e.y-12,width:e.width+24,height:e.height+24})),u=new Set([o(e.x),i,l]),p=new Set([c(e.y),s,a]);for(let e of d)u.add(o(e.x-t.width)),u.add(o(e.x+e.width)),p.add(c(e.y-t.height)),p.add(c(e.y+e.height));let h={position:{x:i,y:s},overlap:1/0,distance:1/0};for(let n of u)for(let r of p){let i=d.reduce((e,i)=>e+Math.max(0,Math.min(n+t.width,i.x+i.width)-Math.max(n,i.x))*Math.max(0,Math.min(r+t.height,i.y+i.height)-Math.max(r,i.y))*(i.priority??1),0),s=(n-e.x)**2+(r-e.y)**2;(i<h.overlap||i===h.overlap&&s<h.distance)&&(h={position:{x:n,y:r},overlap:i,distance:s})}return h}uB["pet.patReply1"]=["pet.patReply1","pet.patReply2","pet.patReply3","pet.patReply4"];let uU='.chat-input-shell, [role="dialog"]',uK=(i=r=[],s=!0,l=new Set,a=(e,t)=>{let n=s?[]:e.filter(e=>!l.has(e.id)&&e.sessionId!==t);for(let t of(s=!1,e))l.add(t.id);for(;l.size>256;)l.delete(l.values().next().value);return n},o=new Set,c=e=>{e.length===i.length&&e.every((e,t)=>e.id===i[t].id)||(i=e,o.forEach(e=>e()))},{subscribe:e=>(o.add(e),()=>{o.delete(e)}),getSnapshot:()=>i,getServerSnapshot:()=>r,reconcile(e,t,n){let r=a(e,t);c((r.length?function(e,t){let n=new Map(e.map(e=>[e.sessionId,e]));for(let e of t)n.delete(e.sessionId),n.set(e.sessionId,e);return[...n.values()].reverse().sort((e,t)=>t.at-e.at).slice(0,12)}(i,r):i).filter(e=>e.sessionId!==t&&!n.includes(e.sessionId)))},dismiss(e){c(i.filter(t=>t.sessionId!==e))}}),uq="pi-yun-pet-preferences",uV={name:"",quiet:!1};function uZ(e){return"string"==typeof e?Array.from(e.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g,"").trim()).slice(0,24).join(""):""}function uJ(e){try{let t=JSON.parse(e??"null");return{name:uZ(t?.name),quiet:t?.quiet===!0}}catch{return{...uV}}}function uY(e){let{preferences:t,defaultName:n,onChange:r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)(t.name);return(0,u.useEffect)(()=>l(t.name),[t.name]),(0,d.jsxs)("div",{className:uD().preferences,children:[(0,d.jsxs)("label",{children:[i("pet.customName"),(0,d.jsx)("input",{value:s,placeholder:n,maxLength:48,onChange:e=>l(e.target.value),onBlur:()=>{let e=uZ(s);l(e),r({name:e})},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.currentTarget.blur())}})]}),(0,d.jsxs)("label",{className:uD().quietSwitch,children:[(0,d.jsx)("input",{type:"checkbox",checked:t.quiet,onChange:e=>r({quiet:e.target.checked})}),i("pet.quiet")]}),(0,d.jsx)("p",{children:i("pet.quietHint")}),(0,d.jsx)("p",{children:i("pet.preferencesHint")})]})}let uG="pi-yun-pet-care-v1",uX=["movement","water","posture"],uQ={movement:60,water:45,posture:30},u0=(e,t,n,r)=>"number"==typeof e&&Number.isFinite(e)?Math.max(n,Math.min(r,e)):t,u1=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:180;return Math.round(u0(e,t,1,n))};function u2(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function u4(){return{habits:Object.fromEntries(uX.map(e=>[e,{enabled:!1,minutes:uQ[e],elapsedMs:0,targetMs:6e4*uQ[e],pausedOn:""}])),focus:{minutes:25,remainingMs:0,phase:"idle",pending:!1,snoozeMs:0},notice:null,cooldownMs:0,day:"",leaseOwner:"",leaseUntil:0}}function u3(e){return{...e,habits:Object.fromEntries(uX.map(t=>[t,{...e.habits[t]}])),focus:{...e.focus},notice:e.notice?{...e.notice,kinds:[...e.notice.kinds]}:null}}function u8(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Math.random,r=u3(e),i=Math.max(0,t.activeMs);if(r.day!==t.day){for(let e of uX)r.habits[e].pausedOn&&(r.habits[e].elapsedMs=0,r.habits[e].targetMs=6e4*r.habits[e].minutes,r.habits[e].pausedOn="");r.day=t.day,r.cooldownMs=0}for(let e of(r.notice&&r.notice.expiresAt<=t.now&&(r.notice=null),r.cooldownMs=Math.max(0,r.cooldownMs-i),uX)){let n=r.habits[e];n.enabled&&n.pausedOn!==t.day&&(n.elapsedMs=Math.min(n.targetMs,n.elapsedMs+i))}if("running"===r.focus.phase&&(r.focus.endsAt||(r.focus.endsAt=t.now+r.focus.remainingMs),r.focus.remainingMs=Math.max(0,r.focus.endsAt-t.now),r.focus.remainingMs||(r.focus.phase="done",r.focus.pending=!0)),r.focus.snoozeMs=Math.max(0,r.focus.snoozeMs-i),!t.canDeliver||"running"===r.focus.phase||r.notice)return r;let s=r.focus.pending&&!r.focus.snoozeMs;if((!uX.filter(e=>{let n=r.habits[e];return n.enabled&&n.pausedOn!==t.day&&n.elapsedMs>=n.targetMs}).length||r.cooldownMs>0)&&!s)return r;let l=uX.filter(e=>{let n=r.habits[e];return n.enabled&&n.pausedOn!==t.day&&n.targetMs-n.elapsedMs<=1e4});for(let e of l){let t=r.habits[e];t.elapsedMs=0,t.targetMs=6e4*t.minutes*(.95+.1*n())}return s&&(r.focus.pending=!1),r.notice={id:`${t.owner}:${t.now}`,owner:t.owner,kinds:l,focusDone:s,expiresAt:t.now+2e4,variant:Math.min(2,Math.floor(3*n()))},r.cooldownMs=12e4,r}function u6(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;return"visible"!==e.visibilityState||!e.hasFocus()}async function u5(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null},n={body:e.body,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl,shownAt:Date.now()}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}function u9(e){return JSON.stringify([uX.map(t=>{let n=e.habits[t];return[n.enabled,n.minutes,n.pausedOn,Math.ceil(Math.max(0,n.targetMs-n.elapsedMs)/1e3)]}),e.focus.phase,e.focus.minutes,Math.ceil(e.focus.remainingMs/1e3),e.notice?.id,e.notice?.expiresAt,e.day])}function u7(e){let{kind:t,state:n,onChange:r}=e,{t:i}=(0,ns.s)(),s=n.habits[t],[l,a]=(0,u.useState)(String(s.minutes));(0,u.useEffect)(()=>a(String(s.minutes)),[s.minutes]);let o=s.pausedOn===u2(),c=Math.max(0,Math.ceil((s.targetMs-s.elapsedMs)/1e3));return(0,d.jsxs)("div",{className:uD().careHabit,children:[(0,d.jsx)("label",{className:uD().careHabitName,htmlFor:`pet-care-${t}`,children:i(`pet.care.${t}`)}),(0,d.jsxs)("label",{className:uD().careInterval,children:[(0,d.jsx)("input",{type:"number",inputMode:"numeric",min:"1",max:"180",value:l,"aria-label":i("pet.care.intervalLabel",{habit:i(`pet.care.${t}`)}),onChange:e=>{let t=e.target.value,n=Number(t);a(t),t.trim()&&Number.isInteger(n)&&n>=1&&n<=180&&n!==s.minutes&&r({minutes:n})},onBlur:()=>{let e=u1(l.trim()?Number(l):0/0,s.minutes);a(String(e)),e!==s.minutes&&r({minutes:e})},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.currentTarget.blur())}}),i("pet.care.minutes")]}),(0,d.jsxs)("label",{className:uD().careToggle,children:[(0,d.jsx)("input",{id:`pet-care-${t}`,type:"checkbox","aria-label":i(`pet.care.${t}`),checked:s.enabled,onChange:e=>r({enabled:e.target.checked})}),(0,d.jsx)("span",{"aria-hidden":"true"})]}),s.enabled&&!o&&(0,d.jsx)("span",{className:uD().careCountdown,role:"timer","aria-live":"off","aria-label":i("pet.care.habitRemaining",{habit:i(`pet.care.${t}`)}),children:0===c?i("pet.care.waitingNotice"):i("pet.care.countdown",{time:`${String(Math.floor(c/60)).padStart(2,"0")}:${String(c%60).padStart(2,"0")}`})}),o&&(0,d.jsx)("button",{type:"button",className:uD().careRestore,onClick:()=>r({restoreToday:!0}),children:i("pet.care.restoreToday")})]})}function pe(e){let{state:t,configure:n,startFocus:r,controlFocus:i}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(String(t.focus.minutes)),[o,c]=(0,u.useState)("unsupported");(0,u.useEffect)(()=>c("u"<typeof Notification?"unsupported":Notification.permission),[]),(0,u.useEffect)(()=>a(String(t.focus.minutes)),[t.focus.minutes]);let p=Math.max(0,Math.ceil(t.focus.remainingMs/1e3)),h="running"===t.focus.phase||"paused"===t.focus.phase;return(0,d.jsxs)("div",{className:uD().careControls,children:[(0,d.jsx)("div",{className:uD().careHabits,children:uX.map(e=>(0,d.jsx)(u7,{kind:e,state:t,onChange:t=>n(e,t)},e))}),(0,d.jsx)("p",{className:uD().careTimingSummary,children:s("pet.care.activeTimeHint")}),(0,d.jsxs)("section",{className:uD().careFocus,"aria-label":s("pet.care.focus"),children:[(0,d.jsxs)("div",{className:uD().careFocusHeader,children:[(0,d.jsx)("strong",{children:s("pet.care.focus")}),h&&(0,d.jsxs)("div",{className:uD().careClock,role:"timer","aria-live":"off","aria-label":s("pet.care.remaining"),children:[String(Math.floor(p/60)).padStart(2,"0"),":",String(p%60).padStart(2,"0")]})]}),(0,d.jsx)("p",{className:uD().careTimingSummary,children:s("pet.care.focusTimingHint")}),"default"===o&&(0,d.jsx)("button",{type:"button",onClick:()=>{Notification.requestPermission().then(c).catch(()=>c("denied"))},children:s("pet.care.enableNotifications")}),"granted"===o&&(0,d.jsx)("p",{className:uD().careTimingSummary,children:s("pet.care.notificationsEnabled")}),"denied"===o&&(0,d.jsx)("p",{className:uD().careTimingSummary,children:s("pet.care.notificationsDenied")}),"unsupported"===o&&(0,d.jsx)("p",{className:uD().careTimingSummary,children:s("pet.care.notificationsUnsupported")}),h?(0,d.jsx)(d.Fragment,{children:(0,d.jsxs)("div",{className:uD().careButtons,children:[(0,d.jsx)("button",{type:"button",onClick:()=>i("paused"===t.focus.phase?"resume":"pause"),children:s("paused"===t.focus.phase?"pet.care.resume":"pet.care.pause")}),(0,d.jsx)("button",{type:"button",onClick:()=>i("stop"),children:s("pet.care.end")})]})}):(0,d.jsxs)("div",{className:uD().careFocusStart,children:[(0,d.jsxs)("label",{className:uD().careInterval,children:[(0,d.jsx)("input",{type:"number",inputMode:"numeric",min:"1",max:"120",value:l,"aria-label":s("pet.care.focusDuration"),onChange:e=>a(e.target.value)}),s("pet.care.minutes")]}),(0,d.jsx)("button",{type:"button",onClick:()=>{let e=u1(l.trim()?Number(l):0/0,25,120);a(String(e)),r(e)},children:s("pet.care.start")})]})]}),(0,d.jsxs)("details",{className:uD().careHelp,children:[(0,d.jsx)("summary",{children:s("pet.care.help")}),(0,d.jsx)("p",{children:s("pet.care.timingHint")})]})]})}function pt(e){let{notice:t,onRespond:n}=e,{t:r}=(0,ns.s)();return(0,d.jsxs)("div",{children:[(0,d.jsx)("strong",{className:uD().careNoticeTitle,children:r(t.focusDone?"pet.care.focusDone":"pet.care.reminder")}),(0,d.jsx)("span",{children:t.kinds.map(e=>r(`pet.care.line.${e}.${t.variant}`)).join(" ")||r("pet.care.focusRest")}),(0,d.jsxs)("div",{className:uD().careButtons,children:[(0,d.jsx)("button",{type:"button",onClick:()=>n(t.id,"ack"),children:r("pet.care.ack")}),(0,d.jsx)("button",{type:"button",onClick:()=>n(t.id,"snooze"),children:r("pet.care.snooze")}),t.kinds.length>0&&(0,d.jsx)("button",{type:"button",onClick:()=>n(t.id,"today"),children:r("pet.care.skipToday")})]})]})}let pn="pi-yun-pet-visible",pr="pi-yun-pet-pos",pi="pi-yun-pet-small";function ps(){let e=window.visualViewport;return{x:e?.offsetLeft??0,y:e?.offsetTop??0,width:e?.width??window.innerWidth,height:e?.height??window.innerHeight}}function pl(e){let{name:t}=e,n={paw:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("ellipse",{cx:"8.5",cy:"5.5",rx:"1.8",ry:"2.5",transform:"rotate(-15 8.5 5.5)"}),(0,d.jsx)("ellipse",{cx:"15.5",cy:"5.5",rx:"1.8",ry:"2.5",transform:"rotate(15 15.5 5.5)"}),(0,d.jsx)("ellipse",{cx:"4.5",cy:"10",rx:"1.6",ry:"2.2",transform:"rotate(-30 4.5 10)"}),(0,d.jsx)("ellipse",{cx:"19.5",cy:"10",rx:"1.6",ry:"2.2",transform:"rotate(30 19.5 10)"}),(0,d.jsx)("path",{d:"M12 11c-2 0-2.8 2.1-4.7 3.7C4.7 17 6 20.6 9 19.5a8.4 8.4 0 0 1 6 0c3 1.1 4.3-2.5 1.7-4.8C14.8 13.1 14 11 12 11Z"})]}),wave:(0,d.jsx)("path",{d:"m8 12-2-5a1.5 1.5 0 0 1 3-1l2 5-1-7a1.5 1.5 0 0 1 3 0l1 7 1-5a1.5 1.5 0 0 1 3 .5L17 14l2-2c2-2 4 0 2 2l-4 6c-4 4-9 1-11-2l-3-5c-1-2 1-3 2-2l3 3M3 3 1 1m19 3 2-2"}),heart:(0,d.jsx)("path",{d:"M20.8 4.6a5.5 5.5 0 0 0-7.8 0l-1 1-1-1a5.5 5.5 0 0 0-7.8 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8Z"}),cheer:(0,d.jsx)("path",{d:"m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2-5.6-3-5.6 3 1.1-6.2L3 9.6l6.2-.9Z"}),moon:(0,d.jsx)("path",{d:"M20.9 13A9 9 0 0 1 11 3.1 9 9 0 1 0 20.9 13Z"}),size:(0,d.jsx)("path",{d:"M9 3H3v6m12 12h6v-6M3 3l6 6m12 12-6-6"}),close:(0,d.jsx)("path",{d:"m6 6 12 12M6 18 18 6"}),more:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"5",cy:"12",r:"1"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,d.jsx)("circle",{cx:"19",cy:"12",r:"1"})]}),reset:(0,d.jsx)("path",{d:"M3 10a9 9 0 1 1 2 8M3 4v6h6"})},r="paw"===t?20:17;return(0,d.jsx)("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"paw"===t?1.7:1.6,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n[t]})}function pa(e,t){try{window.localStorage.setItem(e,t)}catch{}}function po(e){let{sessions:t,onSelectSession:n}=e,{t:r}=(0,ns.s)(),[i,s]=(0,u.useState)(!1),[l,a]=(0,u.useState)(null),o=nf(),[c,p]=(0,u.useState)(null),h=c??o,{preferences:m,updatePreferences:f}=function(){let[e,t]=(0,u.useState)(uV);return(0,u.useEffect)(()=>{try{t(uJ(localStorage.getItem(uq)))}catch{}let e=e=>{if(e.key===uq||null===e.key)try{t(uJ(localStorage.getItem(uq)))}catch{}};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[]),{preferences:e,updatePreferences:(0,u.useCallback)(e=>{t(t=>{let n=t;try{let e=localStorage.getItem(uq);null!==e&&(n=uJ(e))}catch{}let r={...n,...e,name:uZ(e.name??n.name)};try{localStorage.setItem(uq,JSON.stringify(r))}catch{}return r})},[])}}(),x=m.name||r("pet.name"),v=(0,u.useSyncExternalStore)(dk.subscribe,dk.getSnapshot,dk.getServerSnapshot),{background:b,results:y,dismissResult:w}=function(e,t){let[n,r]=(0,u.useState)({running:[],waiting:[]}),i=(0,u.useSyncExternalStore)(uK.subscribe,uK.getSnapshot,uK.getServerSnapshot),s=(0,u.useRef)(t);s.current=t,(0,u.useEffect)(()=>{let t;if(!e)return;let n=!1,i=new AbortController,l=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],a=async()=>{if(!document.hidden)try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:i.signal});if(t.ok){var e;let i=await t.json();if(n)return;r({running:[...new Set([...l(i.runningSessionIds),...l(i.subagentsActiveSessionIds)])],waiting:l(i.awaitingInputSessionIds)}),uK.reconcile((e=i.recentRunResults,Array.isArray(e)?e.filter(e=>null!==e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.sessionId&&("complete"===e.kind||"error"===e.kind||"stopped"===e.kind)&&"number"==typeof e.at&&Number.isFinite(e.at)):[]),s.current,[...l(i.runningSessionIds),...l(i.subagentsActiveSessionIds)])}}catch{}n||(t=setTimeout(a,2500))};return a(),()=>{n=!0,i.abort(),clearTimeout(t)}},[e]);let l=uK.dismiss;return(0,u.useEffect)(()=>{t&&l(t)},[t,l]),{background:n,results:i,dismissResult:l}}(i,v.sessionId),j=[...new Set([..."waiting"===v.phase&&v.sessionId?[v.sessionId]:[],...b.waiting.filter(e=>e!==v.sessionId).sort()])],k=j[0]??null,S="idle"!==v.phase?v.sessionId:b.running.find(e=>e!==v.sessionId)??null,C=k?"waiting":"idle"!==v.phase||b.running.some(e=>e!==v.sessionId)?"busy":"idle",[N,E]=(0,u.useState)(!1),[M,$]=(0,u.useState)(null),[I,T]=(0,u.useState)(""),[R,A]=(0,u.useState)(""),[L,P]=(0,u.useState)(null),[z,O]=(0,u.useState)(!1),[W,F]=(0,u.useState)("actions"),[D,_]=(0,u.useState)(!1),[B,H]=(0,u.useState)(0),[U,K]=(0,u.useState)(0),[q,V]=(0,u.useState)("inside"),Z=(0,u.useRef)(null),G=(0,u.useRef)(null),X=(0,u.useRef)(null),Q=(0,u.useRef)(null),ee=(0,u.useRef)(null),et=(0,u.useRef)(!1),en=(0,u.useRef)("idle"),er=(0,u.useRef)(v.phase),ei=(0,u.useRef)(v.owner),es=(0,u.useRef)(v.sessionId),el=(0,u.useRef)(void 0),ea=(0,u.useRef)(void 0),eo=(0,u.useRef)(void 0),ec=(0,u.useRef)(null),ed=(0,u.useRef)(!1),eu=function(e,t){let{visible:n,preferred:r,small:i,frozen:s,dragging:l}=t,[a,o]=(0,u.useState)(null),c=(0,u.useRef)(a);return c.current=a,(0,u.useLayoutEffect)(()=>{let t=e.current;if(!n||!t||s)return;let i=null,l=new Set,a=()=>{null===i&&(i=requestAnimationFrame(u))},d=new ResizeObserver(a),u=()=>{i=null;let e=t.getBoundingClientRect(),n=t.querySelector("[data-pet-character]")?.getBoundingClientRect(),s=getComputedStyle(t),a=parseFloat(s.getPropertyValue("--preferred-figure-height"));if(!n||!Number.isFinite(a))return;let u=window.visualViewport,p={x:u?.offsetLeft??0,y:u?.offsetTop??0,width:u?.width??window.innerWidth,height:u?.height??window.innerHeight},h=new Set([t,...document.querySelectorAll(uU)]),m=[];for(let e of h){if(l.has(e)||(d.observe(e),l.add(e)),e===t||e.closest("[data-pet-companion]"))continue;let n=e.getBoundingClientRect();!n.width||!n.height||"hidden"===getComputedStyle(e).visibility||n.bottom<=p.y||n.top>=p.y+p.height||n.right<=p.x||n.left>=p.x+p.width||m.push({x:n.x,y:n.y,width:n.width,height:n.height,priority:e.matches(".chat-input-shell")?3:1})}for(let e of l)h.has(e)||(d.unobserve(e),l.delete(e));let f=e.height-n.height,g={x:p.x+p.width-e.width-Math.max(parseFloat(s.getPropertyValue("--pet-right")),parseFloat(s.getPropertyValue("--pet-safe-right"))||0),y:p.y+p.height-f-a-Math.max(parseFloat(s.getPropertyValue("--pet-bottom")),parseFloat(s.getPropertyValue("--pet-safe-bottom"))||0)},x=function(e,t,n,r,i,s){let l=uH(e,t,r,i),a=t.width<=r.width-16&&t.height<=r.height-16,o={position:l.position,compact:!1};if(0!==l.overlap||!a){let t=uH(e,n,r,i);(t.overlap<l.overlap||!a)&&(o={position:t.position,compact:!0})}if(s?.compact===o.compact){let l=o.compact?n:t,a=uH(e,l,r,[]).position;if(o.position.x!==a.x||o.position.y!==a.y){let e=uH(s.position,l,r,i);if(0===e.overlap&&0===e.distance)return s}}return o}(r??g,{width:e.width,height:f+a},{width:e.width,height:f+Math.min(96,a)},p,m,c.current??void 0);o(e=>e?.compact===x.compact&&1>Math.abs(e.position.x-x.position.x)&&1>Math.abs(e.position.y-x.position.y)?e:x)},p=e=>e instanceof Element&&(e.matches(uU)||e.querySelector(uU)),h=new MutationObserver(e=>{e.some(e=>"attributes"===e.type?e.target instanceof Element&&!t.contains(e.target)&&(e.target.matches(uU)||[...l].some(n=>n!==t&&e.target.contains(n))):[...e.addedNodes,...e.removedNodes].some(p))&&a()});return u(),h.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","hidden"]}),window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),window.visualViewport?.addEventListener("resize",a),window.visualViewport?.addEventListener("scroll",a),()=>{null!==i&&cancelAnimationFrame(i),d.disconnect(),h.disconnect(),window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0),window.visualViewport?.removeEventListener("resize",a),window.visualViewport?.removeEventListener("scroll",a)}},[n,r,i,s,e]),{position:l?r??a?.position:a?.position??r,compact:a?.compact??!1}}(Z,{visible:i,preferred:l,small:h,frozen:D||z,dragging:D}),ep=function(e,t){let{t:n}=(0,ns.s)(),[r,i]=(0,u.useState)(u4),[s,l]=(0,u.useState)(!1),a=(0,u.useRef)(r),o=(0,u.useRef)(t);o.current=t;let c=(0,u.useRef)(""),d=(0,u.useRef)(0),p=(0,u.useRef)(0),h=(0,u.useRef)(0),m=(0,u.useRef)(!1),f=(0,u.useCallback)(()=>{try{let e=localStorage.getItem(uG);if(null!==e)return function(e){let t=u4();try{let n=JSON.parse(e??"null");for(let e of uX){let r=n?.habits?.[e];if(!r||"object"!=typeof r)continue;let i=u1(r.minutes,uQ[e]);t.habits[e]={enabled:!0===r.enabled,minutes:i,elapsedMs:u0(r.elapsedMs,0,0,114e5),targetMs:u0(r.targetMs,6e4*i,3e4,114e5),pausedOn:"string"==typeof r.pausedOn?r.pausedOn.slice(0,10):""}}let r=n?.focus;r&&"object"==typeof r&&(t.focus={minutes:u1(r.minutes,25,120),remainingMs:u0(r.remainingMs,0,0,72e5),phase:["idle","running","paused","done"].includes(r.phase)?r.phase:"idle",pending:!0===r.pending,snoozeMs:u0(r.snoozeMs,0,0,3e5),endsAt:u0(r.endsAt,0,0,Number.MAX_SAFE_INTEGER),notified:!0===r.notified}),t.day="string"==typeof n?.day?n.day.slice(0,10):"",t.cooldownMs=u0(n?.cooldownMs,0,0,12e4),t.leaseOwner="string"==typeof n?.leaseOwner?n.leaseOwner:"",t.leaseUntil=u0(n?.leaseUntil,0,0,Number.MAX_SAFE_INTEGER);let i=n?.notice;if(i&&"string"==typeof i.id&&"string"==typeof i.owner&&Array.isArray(i.kinds)&&"number"==typeof i.expiresAt&&Number.isFinite(i.expiresAt)){let e=[...new Set(i.kinds.filter(e=>uX.includes(e)))];(e.length||!0===i.focusDone)&&(t.notice={id:i.id,owner:i.owner,kinds:e,focusDone:!0===i.focusDone,expiresAt:i.expiresAt,variant:Math.round(u0(i.variant,0,0,2))})}}catch{}return t}(e)}catch{}return a.current},[]),g=(0,u.useCallback)((e,t)=>{if(a.current=e,t)try{localStorage.setItem(uG,JSON.stringify(e))}catch{}i(t=>u9(t)===u9(e)?t:e)},[]),x=(0,u.useCallback)(e=>{let t=Date.now();p.current=t,d.current=t;let n=e(f());n.leaseOwner=c.current,n.leaseUntil=t+3e3,g(n,!0)},[g,f]);(0,u.useEffect)(()=>{c.current||=globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,g(f(),!1);let e=e=>{(e.key===uG||null===e.key)&&g(null===e.newValue?u4():f(),!1)};return window.addEventListener("storage",e),()=>window.removeEventListener("storage",e)},[g,f]),(0,u.useEffect)(()=>{if(!e)return;d.current=Date.now(),p.current=Date.now();let t=()=>{p.current=Date.now()},n=e=>{let n;t(),(n=e.target)instanceof Element&&n.closest('input, textarea, [contenteditable="true"]')&&(h.current=Date.now())},r=()=>{m.current=!0,t()},i=()=>{m.current=!1,h.current=Date.now(),t()},s=()=>{d.current=Date.now();let e=f();e.leaseOwner===c.current&&g({...e,leaseOwner:"",leaseUntil:0},!0),l(!1)},a=()=>{d.current=Date.now(),document.hidden?s():t()},u=()=>{let e=Date.now(),t=d.current;d.current=e;let n=!document.hidden&&document.hasFocus()&&e-p.current<3e5,r=[...document.querySelectorAll('[role="dialog"], [aria-modal="true"]')].some(e=>{let t=e.getBoundingClientRect();return t.width>0&&t.height>0&&"hidden"!==getComputedStyle(e).visibility}),i=n&&!o.current&&!r&&!m.current&&e-h.current>=8e3;l(e=>e===i?e:i);let s=f();if(!n||s.leaseOwner!==c.current&&s.leaseUntil>e)return;let a=s.leaseOwner===c.current&&e-t<=5e3?Math.max(0,e-t):0,u=u8(s,{now:e,day:u2(),activeMs:a,canDeliver:i,owner:c.current});u.leaseOwner=c.current,u.leaseUntil=e+3e3,(uX.some(e=>u.habits[e].enabled)||"idle"!==u.focus.phase||u.notice)&&g(u,!0)};document.addEventListener("pointerdown",t,!0),document.addEventListener("pointermove",t,{passive:!0}),document.addEventListener("scroll",t,{passive:!0,capture:!0}),document.addEventListener("keydown",n,!0),document.addEventListener("input",n,!0),document.addEventListener("focusin",n,!0),document.addEventListener("compositionstart",r,!0),document.addEventListener("compositionend",i,!0),document.addEventListener("visibilitychange",a),window.addEventListener("blur",s),window.addEventListener("focus",a);let x=setInterval(u,1e3);return u(),()=>{clearInterval(x),s(),document.removeEventListener("pointerdown",t,!0),document.removeEventListener("pointermove",t),document.removeEventListener("scroll",t,!0),document.removeEventListener("keydown",n,!0),document.removeEventListener("input",n,!0),document.removeEventListener("focusin",n,!0),document.removeEventListener("compositionstart",r,!0),document.removeEventListener("compositionend",i,!0),document.removeEventListener("visibilitychange",a),window.removeEventListener("blur",s),window.removeEventListener("focus",a)}},[e,g,f]),(0,u.useEffect)(()=>{let e=!1,t=()=>{if(!document.hidden&&document.hasFocus())return;let t=()=>{if(e)return;let t=f(),r=Date.now();if("running"!==t.focus.phase||!t.focus.endsAt||t.focus.endsAt>r)return;let i=u8(t,{now:r,day:u2(),activeMs:0,canDeliver:!1,owner:c.current}),s=!t.focus.notified&&"u">typeof Notification&&"granted"===Notification.permission;s&&(i.focus.notified=!0),g(i,!0),s&&u5({title:n("pet.care.focusDone"),body:n("pet.care.focusRest"),sessionUrl:window.location.href,onClick:()=>window.focus(),tag:`pet-focus-${t.focus.endsAt}`})};navigator.locks?navigator.locks.request("pi-yun-pet-focus-notification",{ifAvailable:!0},e=>{e&&t()}):t()},r=window.setInterval(t,1e3);return document.addEventListener("visibilitychange",t),window.addEventListener("blur",t),()=>{e=!0,clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("blur",t)}},[g,f,n]);let v=(0,u.useCallback)((e,t)=>x(n=>{let r,i;return i=(r=u3(n)).habits[e],void 0!==t.enabled&&(i.enabled=t.enabled),void 0!==t.minutes&&(i.minutes=u1(t.minutes,i.minutes)),(t.restoreToday||!0===t.enabled)&&(i.pausedOn=""),i.elapsedMs=0,i.targetMs=6e4*i.minutes,r.notice?.kinds.includes(e)&&(r.notice.kinds=r.notice.kinds.filter(t=>t!==e),r.notice.kinds.length||r.notice.focusDone||(r.notice=null)),r}),[x]),b=(0,u.useCallback)(e=>x(t=>(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.focus.minutes,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=u3(e),i=u1(t,e.focus.minutes,120);return r.focus={minutes:i,remainingMs:6e4*i,phase:"running",pending:!1,snoozeMs:0,endsAt:n+6e4*i,notified:!1},r.notice=null,r})(t,e)),[x]),y=(0,u.useCallback)(e=>x(t=>(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),r=u3(e);return"pause"===t&&"running"===r.focus.phase&&(r.focus.remainingMs=r.focus.endsAt?Math.max(0,r.focus.endsAt-n):r.focus.remainingMs,0===r.focus.remainingMs?(r.focus.phase="done",r.focus.pending=!0):r.focus.phase="paused",r.focus.endsAt=0),"resume"===t&&"paused"===r.focus.phase&&(r.focus.phase="running",r.focus.endsAt=n+r.focus.remainingMs),"stop"===t&&(r.focus={...r.focus,remainingMs:0,phase:"idle",pending:!1,snoozeMs:0,endsAt:0},r.notice=null),r})(t,e)),[x]),w=(0,u.useCallback)((e,t)=>x(n=>(function(e,t,n,r){let i=u3(e),s=i.notice;if(!s||s.id!==t)return i;for(let e of s.kinds){let t=i.habits[e];t.elapsedMs=0,"today"===n&&(t.pausedOn=r),t.targetMs="snooze"===n?3e5:6e4*t.minutes}return s.focusDone&&(i.focus.pending="snooze"===n,i.focus.snoozeMs=3e5*("snooze"===n),"snooze"!==n&&(i.focus.phase="idle")),i.notice=null,i})(n,e,t,u2())),[x]),j=e&&!t&&s&&r.notice?.owner===c.current&&r.notice.expiresAt>d.current?r.notice:null;return{state:r,notice:j,configure:v,startFocus:b,controlFocus:y,respond:w,focusing:"running"===r.focus.phase}}(i,z||D||N||!!k||"pet.failed"===R&&!!I||y.some(e=>"error"===e.kind)),eh=(0,u.useCallback)(function(e,t){let n,i,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,l=arguments.length>3&&void 0!==arguments[3]&&arguments[3];clearTimeout(ea.current),ec.current??=(n=new Map,i=new Map,e=>{let t=uB[e];if(!t)return e;let r=n.get(e);if(!r?.length){r=[...t];for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}r[r.length-1]===i.get(e)&&([r[0],r[r.length-1]]=[r[r.length-1],r[0]]),n.set(e,r)}let s=r.pop();return i.set(e,s),s}),ed.current=l&&"pet.failed"!==e;let a=ed.current&&(m.quiet||ep.focusing)?"":r(ec.current(e),{name:x});T(a),A(e),P(s),a&&(ea.current=setTimeout(()=>T(""),Math.min(8e3,Math.max(4500,130*Array.from(a).length)))),t&&(clearTimeout(eo.current),$(t),eo.current=setTimeout(()=>$(null),2800))},[r,x,m.quiet,ep.focusing]);(0,u.useEffect)(()=>{(m.quiet||ep.focusing)&&ed.current&&(clearTimeout(ea.current),T(""),P(null))},[m.quiet,ep.focusing]),(0,u.useEffect)(()=>{try{s("1"===localStorage.getItem(pn));let e=localStorage.getItem(pi);("1"===e||"0"===e)&&p("1"===e);let t=JSON.parse(localStorage.getItem(pr)||"null");t&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&a(t)}catch{}},[]),(0,u.useEffect)(()=>{if(!i){el.current=v.result?.sequence;return}let e=v.owner!==ei.current||v.sessionId!==es.current;(C!==en.current||v.phase!==er.current||e)&&"idle"!==C&&(E(!1),clearTimeout(eo.current),$(null));let t="idle"!==v.phase&&"waiting"!==v.phase&&("idle"===er.current||e);if(!k&&(t||"busy"===C&&"idle"===en.current)?eh("sending"===v.phase?"pet.received":"pet.greetRun",void 0,S,!0):(k||"waiting"===en.current&&"waiting"!==C)&&(clearTimeout(ea.current),T(""),P(null)),en.current=C,er.current=v.phase,ei.current=v.owner,es.current=v.sessionId,"idle"===v.phase&&v.result&&v.result.sequence!==el.current){el.current=v.result.sequence,E(!1);let e=v.result.kind;k||(K(0),eh("complete"===e?"pet.greetDone":"stopped"===e?"pet.stopped":"pet.failed","complete"===e?"happy":"wave",v.sessionId,!0))}},[i,C,k,S,v.owner,v.sessionId,v.phase,v.result,eh]),(0,u.useEffect)(()=>{if(!i){clearTimeout(ea.current),clearTimeout(eo.current),T(""),$(null),O(!1),_(!1),ee.current=null;return}return()=>{clearTimeout(ea.current),clearTimeout(eo.current)}},[i]),(0,u.useEffect)(()=>{if(!i||!z)return;let e=G.current;e?.querySelector('button[aria-pressed="true"]')?.focus({preventScroll:!0});let t=e=>{Z.current?.contains(e.target)||O(!1)},n=null,r=e=>{if("Tab"===e.key){null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=null,Z.current?.contains(document.activeElement)||O(!1)});return}"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),O(!1),X.current?.focus())};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",r,!0),()=>{null!==n&&cancelAnimationFrame(n),document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",r,!0)}},[i,z]),(0,u.useEffect)(()=>{if(!i||!z)return;let e=()=>{let e=Z.current?.getBoundingClientRect();V(e&&e.left>=304?"left":e&&window.innerWidth-e.right>=304?"right":"inside")};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[i,z,eu.position,h]),(0,u.useLayoutEffect)(()=>{let e=G.current;if(!i||!z||!e)return;let t=()=>{let t=window.visualViewport,n=(t?.offsetTop??0)+8,r=(t?.offsetLeft??0)+8,i=(t?.offsetLeft??0)+(t?.width??innerWidth)-8,s=(t?.offsetTop??0)+(t?.height??innerHeight)-8;e.style.maxHeight=`${Math.max(80,s-n)}px`,e.style.removeProperty("translate");let l=e.getBoundingClientRect();e.style.translate=`${Math.max(r-l.left,Math.min(0,i-l.right))}px ${Math.max(n-l.top,Math.min(0,s-l.bottom))}px`};t();let n=new ResizeObserver(t);return n.observe(e),window.addEventListener("resize",t),window.visualViewport?.addEventListener("resize",t),window.visualViewport?.addEventListener("scroll",t),()=>{n.disconnect(),window.removeEventListener("resize",t),window.visualViewport?.removeEventListener("resize",t),window.visualViewport?.removeEventListener("scroll",t)}},[i,z,W,q,x,y.length,j.length,eu.position,ep.state.focus.phase]);let em=()=>{E(!1)},ef=()=>{s(!1),pa(pn,"0"),Q.current?.focus()},eg=e=>{em(),O(!1),("cheer"===e||"happy"===e)&&K(e=>e+1),z&&X.current?.focus(),"happy"===e?(H(e=>e+1),eh("pet.patReply1","happy")):eh("wave"===e?"pet.helloReply":"pet.cheerReply",e)},ex=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=ee.current;n&&n.pointerId===e.pointerId&&(et.current=t||n.moved,ee.current=null,_(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),n.moved&&pa(pr,JSON.stringify(n.latest)))},ev="idle"===C&&N,eb=ev?"sleep":M??(ep.notice?ep.notice.focusDone?"happy":"wave":"busy"===C?"thinking":"waiting"===C?"wave":"idle"),ey=ev?"sleeping":C,ew=[...j.map(e=>({sessionId:e,kind:"waiting"})),...y.filter(e=>!j.includes(e.sessionId))],ej=y.find(e=>"error"===e.kind)??(m.quiet?void 0:y[0]),ek=ep.notice,eS=k||ek||I&&"pet.failed"===R?void 0:ej,eC=ek?null:k??eS?.sessionId??L,eN=t.find(e=>e.id===eC),eE=eN?.name?.trim()||eN?.firstMessage?.trim()||r("pet.unnamedSession",{id:eC?.slice(0,8)??""}),eM=e=>{let n=t.find(t=>t.id===e);return n?.name?.trim()||n?.firstMessage?.trim()||r("pet.unnamedSession",{id:e.slice(0,8)})},e$=(e,r)=>{if(!Y(e))return;let i=t.find(e=>e.id===r);i&&(e.preventDefault(),O(!1),w(r),n(i))};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{ref:Q,type:"button",className:"workbench-view-button","data-workspace-action":"pet",onClick:()=>{i?ef():(em(),s(!0),pa(pn,"1"),eh("pet.welcome","wave"))},title:r("pet.title"),"aria-label":r("pet.title"),"aria-pressed":i,children:[(0,d.jsx)(pl,{name:"paw"}),(0,d.jsx)("span",{className:"workbench-settings-label",children:r("pet.title")})]}),i&&(0,g.createPortal)((0,d.jsxs)("div",{ref:Z,className:`${uD().pet} ${h?uD().small:""}`,"data-pet-companion":"","data-pose":eb,"data-status":ey,"data-chat-phase":v.phase,"data-menu-side":q,"data-compact":eu.compact,"data-dragging":D,"data-pet-focusing":ep.focusing,"data-has-notices":ew.length>0,style:eu.position?{left:eu.position.x,top:eu.position.y,right:"auto",bottom:"auto"}:void 0,onBlur:e=>{e.relatedTarget&&!e.currentTarget.contains(e.relatedTarget)&&O(!1)},children:[(0,d.jsx)("div",{className:uD().speech,role:"status","aria-live":"polite","aria-atomic":"true",children:(k||eS||ek||I)&&(0,d.jsxs)("div",{className:uD().bubble,"data-pet-notice":k?"waiting":eS?"result":ek?"care":"transient",children:[ek?(0,d.jsx)(pt,{notice:ek,onRespond:ep.respond}):(0,d.jsx)("span",{children:k?r("pet.attention"):eS?r(`pet.background.${eS.kind}`):I}),j.length>1&&(0,d.jsx)("span",{className:uD().waitingCount,children:r("pet.moreWaiting",{count:j.length-1})}),(ew.length>1||eS)&&(0,d.jsx)("button",{type:"button",className:uD().noticeCount,onClick:()=>{F("notices"),O(!0)},"aria-controls":"pet-actions","aria-expanded":z&&"notices"===W,children:r("pet.noticesCount",{count:ew.length})}),eC&&(0,d.jsxs)("a",{className:uD().sessionLink,href:J(eC),title:eE,onClick:e=>e$(e,eC),children:[(0,d.jsx)("span",{children:eE}),(0,d.jsx)("span",{"aria-hidden":"true",children:" →"}),(0,d.jsx)("span",{className:uD().linkHint,children:r("pet.viewSession")})]})]},k??eS?.id??ek?.id??I)}),(0,d.jsxs)("button",{type:"button","data-pet-character":"",className:uD().character,"aria-label":r("pet.interact",{name:x}),title:r("pet.hint"),onPointerDown:e=>{if(!e.isPrimary||0!==e.button||!Z.current)return;em();let t=Z.current.getBoundingClientRect(),n={x:t.left,y:t.top};ee.current={pointerId:e.pointerId,x:e.clientX,y:e.clientY,origin:n,latest:n,moved:!1},et.current=!1,e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{let t=ee.current;if(!t||t.pointerId!==e.pointerId||!Z.current)return;let n=e.clientX-t.x,r=e.clientY-t.y;if(!t.moved&&6>Math.hypot(n,r))return;t.moved=!0,_(!0),O(!1);let i=Z.current.getBoundingClientRect();t.latest=uH({x:t.origin.x+n,y:t.origin.y+r},i,ps(),[]).position,a(t.latest)},onPointerUp:e=>ex(e),onPointerCancel:e=>ex(e,!0),onLostPointerCapture:()=>{ee.current=null,_(!1)},onClick:e=>{if(et.current&&0!==e.detail){et.current=!1;return}eg("happy")},onDoubleClick:()=>eg("wave"),onKeyDown:e=>{let t={ArrowLeft:[-16,0],ArrowRight:[16,0],ArrowUp:[0,-16],ArrowDown:[0,16]};if(!t[e.key]||!Z.current)return;e.preventDefault();let n=Z.current.getBoundingClientRect(),[r,i]=t[e.key],s=e.shiftKey?2:1,l=uH({x:n.left+r*s,y:n.top+i*s},n,ps(),[]).position;a(l),pa(pr,JSON.stringify(l))},children:[(0,d.jsx)("span",{className:uD().ground,"aria-hidden":"true"}),(0,d.jsx)(u_,{pose:eb,dragging:D,hop:U}),B>0&&(0,d.jsx)("span",{className:uD().hearts,"aria-hidden":"true",children:[0,1,2].map(e=>(0,d.jsx)("span",{style:{"--i":e},children:(0,d.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor",children:(0,d.jsx)("path",{d:"M12 21 3.5 12.7C-2 7.3 5.8-.5 11.2 4.9l.8.8.8-.8C18.2-.5 26 7.3 20.5 12.7Z"})})},e))},B)]}),(0,d.jsxs)("button",{ref:X,type:"button",className:uD().more,"aria-label":r("pet.actions"),title:r("pet.actions"),"aria-expanded":z,"aria-controls":"pet-actions",onClick:()=>{let e=Z.current?.getBoundingClientRect();V(e&&e.left>=304?"left":e&&window.innerWidth-e.right>=304?"right":"inside"),O(e=>!e)},children:[(0,d.jsx)(pl,{name:"more"}),ew.length>0&&(0,d.jsx)("span",{className:uD().badge,"aria-hidden":"true",children:ew.length})]}),z&&(0,d.jsxs)("div",{ref:G,id:"pet-actions",className:uD().actions,role:"group","aria-label":r("pet.actions"),children:[(0,d.jsxs)("div",{className:uD().actionHeading,children:[(0,d.jsxs)("div",{children:[r("pet.menuTitle",{name:x}),"actions"===W&&(0,d.jsx)("span",{children:r("pet.menuHint")})]}),(0,d.jsx)("button",{type:"button","aria-label":r("pet.closeActions"),onClick:()=>{O(!1),X.current?.focus()},children:(0,d.jsx)(pl,{name:"close"})})]}),(0,d.jsx)("div",{className:uD().menuTabs,role:"group","aria-label":r("pet.menuSections"),children:["actions","notices","care","preferences"].map(e=>(0,d.jsxs)("button",{type:"button","aria-pressed":W===e,onClick:()=>F(e),children:[r(`pet.tab.${e}`),"notices"===e&&ew.length>0?` (${ew.length})`:""]},e))}),"notices"===W&&(0,d.jsxs)("div",{className:uD().notices,children:[0===ew.length&&(0,d.jsx)("p",{children:r("pet.noNotices")}),ew.map(e=>(0,d.jsxs)("div",{className:uD().noticeRow,children:[(0,d.jsxs)("a",{href:J(e.sessionId),onClick:t=>e$(t,e.sessionId),title:eM(e.sessionId),children:[(0,d.jsx)("span",{children:r(`pet.notice.${e.kind}`)}),(0,d.jsx)("strong",{children:eM(e.sessionId)})]}),"waiting"!==e.kind&&(0,d.jsx)("button",{type:"button",onClick:()=>w(e.sessionId),"aria-label":r("pet.dismissResult",{session:eM(e.sessionId)}),children:(0,d.jsx)(pl,{name:"close"})})]},e.sessionId))]}),"preferences"===W&&(0,d.jsx)(uY,{preferences:m,defaultName:r("pet.name"),onChange:f}),"care"===W&&(0,d.jsx)(pe,{state:ep.state,configure:ep.configure,startFocus:ep.startFocus,controlFocus:ep.controlFocus}),"actions"===W&&(0,d.jsxs)("div",{className:uD().actionGrid,children:[(0,d.jsxs)("button",{type:"button",onClick:()=>eg("wave"),children:[(0,d.jsx)(pl,{name:"wave"}),r("pet.hello")]}),(0,d.jsxs)("button",{type:"button",onClick:()=>eg("happy"),children:[(0,d.jsx)("span",{className:uD().patIcon,children:(0,d.jsx)(pl,{name:"heart"})}),r("pet.pat")]}),(0,d.jsxs)("button",{type:"button",onClick:()=>eg("cheer"),children:[(0,d.jsx)(pl,{name:"cheer"}),r("pet.encourage")]}),(0,d.jsxs)("button",{type:"button",onClick:()=>{E(!ev),O(!1),X.current?.focus(),eh(ev?"pet.wakeReply":"pet.sleepReply",ev?"wave":"sleep")},children:[(0,d.jsx)(pl,{name:"moon"}),r(ev?"pet.wake":"pet.rest")]})]}),(0,d.jsxs)("div",{className:uD().actionFooter,children:[(0,d.jsxs)("button",{type:"button",onClick:()=>{a(null),O(!1);try{localStorage.removeItem(pr)}catch{}X.current?.focus()},children:[(0,d.jsx)(pl,{name:"reset"}),r("pet.resetPosition")]}),(0,d.jsxs)("button",{type:"button",onClick:()=>{p(!h),pa(pi,h?"0":"1")},children:[(0,d.jsx)(pl,{name:"size"}),r(h?"pet.enlarge":"pet.shrink")]}),(0,d.jsxs)("button",{type:"button",onClick:ef,children:[(0,d.jsx)(pl,{name:"close"}),r("pet.hide")]})]})]})]}),document.body)]})}let pc=/^(\d+)\.(\d+)\.(\d+)$/;function pd(e){let t=pc.exec(e);if(!t)return null;let n=t.slice(1).map(Number);return n.some(e=>!Number.isSafeInteger(e))?null:n}function pu(e){return pd(e)?`https://github.com/Jason-24/pi-web-yun/releases/tag/v${e}`:null}var pp=n(84123),ph=n.n(pp);let pm="0.3.8",pf="1.6.0",pg="pi-yun";function px(e){let{mobile:t}=e,{t:n}=(0,ns.s)(),r=(0,u.useRef)(null),i=(0,u.useRef)(null),s=(0,u.useRef)(0),[l,a]=(0,u.useState)(null),[o,c]=(0,u.useState)(null),[p,h]=(0,u.useState)(!0),[m,f]=(0,u.useState)(!1),g=(0,u.useCallback)(async()=>{if(i.current)return;let e=new AbortController;i.current=e,h(!0),f(!1);try{let t=await fetch("/api/app-update",{cache:"no-store",signal:e.signal});if(!t.ok)throw Error("Update check failed");let n=await t.json();if("string"!=typeof n.latestVersion||!pu(n.latestVersion))throw Error("Invalid version");e.signal.aborted||(c(n.latestVersion),s.current=Date.now())}catch{e.signal.aborted||f(!0)}finally{e.signal.aborted||h(!1),i.current===e&&(i.current=null)}},[]);(0,u.useEffect)(()=>{g();let e=()=>{!document.hidden&&Date.now()-s.current>=432e5&&g()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e);let t=setInterval(e,432e5);return()=>{i.current?.abort(),i.current=null,clearInterval(t),window.removeEventListener("focus",e),document.removeEventListener("visibilitychange",e)}},[g]);let x=null!==o&&function(e,t){let n=pd(e),r=pd(t);if(!n||!r)return!1;for(let e=0;e<n.length;e+=1)if(n[e]!==r[e])return n[e]>r[e];return!1}(o,pm),v=x?pu(o):null,b=p?n("appUpdate.checking"):m?n("appUpdate.failed"):x?n("appUpdate.available",{version:o}):n("appUpdate.current"),y=n("appUpdate.title");return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("button",{ref:r,type:"button",className:`workbench-view-button workbench-utility-start ${ph().trigger}${x?` ${ph().available}`:""}`,"data-workspace-action":"update","data-update-available":x,"aria-label":x?`${y} \xb7 ${n("appUpdate.available",{version:o})}`:y,title:`${pg} v${pm} \xb7 pi v${pf}
|
|
10
|
+
${b}`,"aria-haspopup":"dialog","aria-expanded":!!l,onClick:()=>{if(l)return void a(null);let e=r.current?.getBoundingClientRect();e&&a({kind:"rect",rect:e,align:"start"}),(m||Date.now()-s.current>=432e5)&&g()},children:[(0,d.jsx)("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M12 3v12m-4-4 4 4 4-4M5 16v4h14v-4"})}),(0,d.jsx)("span",{className:"workbench-settings-label",children:n("i18n.update")})]}),(0,d.jsx)(r4,{open:!!l,anchor:l,sheet:t,ariaLabel:y,title:y,width:300,cancelLabel:n("sidebar.cancel"),onClose:()=>a(null),returnFocusTo:r.current,children:(0,d.jsxs)("div",{className:ph().panel,children:[!t&&(0,d.jsx)("strong",{children:y}),(0,d.jsxs)("dl",{className:ph().versions,children:[(0,d.jsx)("dt",{children:pg}),(0,d.jsxs)("dd",{children:["v",pm]}),(0,d.jsx)("dt",{children:"pi"}),(0,d.jsxs)("dd",{children:["v",pf]})]}),(0,d.jsx)("p",{role:"status",children:b}),v&&(0,d.jsx)("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:n("appUpdate.releaseNotes")}),(0,d.jsx)("p",{children:n("appUpdate.installHint")}),(0,d.jsxs)("code",{className:ph().command,children:["npm install -g ",pg,"@latest"]}),(0,d.jsx)("p",{children:n("appUpdate.restartHint")}),(0,d.jsx)("button",{type:"button",className:ph().check,disabled:p,onClick:()=>void g(),children:n("appUpdate.check")})]})})]})}let pv={home:"navigation.home",chat:"navigation.chat",settings:"common.settings",archive:"sidebar.archived",history:"history.full",system:"system.prompt",tools:"tools.title",agents:"agentSwitcher.title",branches:"i18n.branches",session:"session.title",debug:"debug.title"};function pb(e){let t,{view:n}=e;if("agents"===n)return(0,d.jsx)(nW,{size:20,strokeWidth:1.7});if("history"===n)return(0,d.jsx)(nF,{size:20});switch(n){case"home":t=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"m3.5 10 8.5-7 8.5 7v8.5a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2Z"}),(0,d.jsx)("path",{d:"M9 20.5v-6h6v6"})]});break;case"chat":t=(0,d.jsx)("path",{d:"M5 4.5h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H9l-5 3v-14a2 2 0 0 1 1-2Z"});break;case"system":t=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M6 3.5h8l4 4v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-13a2 2 0 0 1 2-2Z"}),(0,d.jsx)("path",{d:"M14 3.5v4h4M8 11l2 2-2 2m4 0h3"})]});break;case"tools":t=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"3.5",y:"7.5",width:"17",height:"13",rx:"2"}),(0,d.jsx)("path",{d:"M9 7.5v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2M3.5 13h17M10.5 13v1.5h3V13"})]});break;case"branches":t=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M14.5 7V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2v2l2.5-2"}),(0,d.jsx)("path",{d:"M11 9h8a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2v2.5L16.5 18H11a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2Z"}),(0,d.jsx)("path",{d:"M12 13.5h5.5"})]});break;case"settings":t=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M4 7h10M18 7h2M4 17h2m4 0h10"}),(0,d.jsx)("circle",{cx:"16",cy:"7",r:"2"}),(0,d.jsx)("circle",{cx:"8",cy:"17",r:"2"})]});break;default:return null}return(0,d.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t})}function py(e){let{petSessions:t,onPetSelectSession:n,activeView:r,conversationAvailable:i,inspectionAvailable:s,sessionAvailable:l,mobile:a,covered:o=!1,homeButtonRef:c,onHomeHover:u,onHomeLeave:p,onNavigate:h}=e,{t:m}=(0,ns.s)(),f=a?["home","chat","history","update","pet","settings"]:["home","chat","project-divider","system","tools","session-divider","agents","branches","history","update","pet","settings"];return(0,d.jsx)("nav",{className:`workbench-settings-navigation${a?" is-mobile":""}`,"aria-label":m("navigation.workspace"),inert:o,children:f.map(e=>{if("project-divider"===e||"session-divider"===e)return(0,d.jsx)("div",{className:"workbench-rail-divider","aria-hidden":"true"},e);if("update"===e)return(0,d.jsx)(px,{mobile:a},"update");if("pet"===e)return(0,d.jsx)(po,{sessions:t,onSelectSession:n},"pet");let o="chat"===e?!i:"system"===e||"tools"===e?!s:("history"===e||"agents"===e||"branches"===e)&&!l,f=m(pv[e]);return(0,d.jsxs)("button",{type:"button",className:`workbench-view-button${"home"===e?" workbench-home-button":""}`,ref:"home"===e?c:void 0,onPointerEnter:"home"!==e||a?void 0:e=>{"mouse"===e.pointerType&&u?.()},onPointerLeave:"home"!==e||a?void 0:p,"data-workspace-view":e,"aria-label":f,title:o?`${f} \xb7 ${m("navigation.sessionRequired")}`:f,"aria-current":r===e?"page":void 0,disabled:o,onClick:()=>h(e),children:[(0,d.jsx)(pb,{view:e}),(0,d.jsx)("span",{className:"workbench-settings-label",children:f})]},e)})})}let pw=null,pj="";function pk(e){let{handleRef:t,context:n,mobile:r,initialFocus:i,onInitialFocusDone:s,onPick:l,onUseDefaultDirectory:a,onOpenFolder:o,onRefreshWorktrees:c,onCreateWorktree:p}=e,{t:h}=(0,ns.s)(),[m,f]=(0,u.useState)(()=>pj),g=(0,u.useRef)(null);(0,u.useImperativeHandle)(t,()=>({openProjectMenu:e=>g.current?.openMenu("project",e)}),[]);let x=(0,u.useRef)(i),v=(0,u.useRef)(s);return v.current=s,(0,u.useEffect)(()=>{if(pj)return;let e=!1;return(pw??=fetch("/api/home").then(e=>e.json()).then(e=>pj=e.home??"").catch(()=>(pw=null,""))).then(t=>{!e&&t&&f(t)}),()=>{e=!0}},[]),(0,u.useEffect)(()=>{let e=x.current;if(!e)return;x.current=null,v.current();let t=g.current;t_(document,("worktree"===e?t?.button("worktree"):null)??t?.button("project")??null)},[]),(0,d.jsx)("div",{className:"new-session-context",children:(0,d.jsx)(iC,{handleRef:g,layout:"inline",context:n,mobile:r,label:h("workspace.newSessionContext"),homeDir:m,newWorktreeTitle:h("sidebar.newWorktreeForSession"),onPick:l,onUseDefaultDirectory:a,onOpenFolder:o,onRefreshWorktrees:c,onCreateWorktree:p})})}function pS(e){return e&&"number"==typeof e.size&&"string"==typeof e.mtime?`${e.size}:${e.mtime}`:null}function pC(e,t){return null===e||null===t||e!==t}let pN=`<script data-pi-web-polyfill="storage">
|
|
11
|
+
(function() {
|
|
12
|
+
function createMemoryStorage() {
|
|
13
|
+
var store = Object.create(null);
|
|
14
|
+
function hasKey(key) { return Object.prototype.hasOwnProperty.call(store, key); }
|
|
15
|
+
var storage = Object.create({
|
|
16
|
+
getItem: function(key) {
|
|
17
|
+
if (arguments.length < 1) throw new TypeError("getItem requires a key");
|
|
18
|
+
key = String(key);
|
|
19
|
+
return hasKey(key) ? store[key] : null;
|
|
20
|
+
},
|
|
21
|
+
setItem: function(key, value) {
|
|
22
|
+
if (arguments.length < 2) throw new TypeError("setItem requires a key and value");
|
|
23
|
+
store[String(key)] = String(value);
|
|
24
|
+
},
|
|
25
|
+
removeItem: function(key) {
|
|
26
|
+
if (arguments.length < 1) throw new TypeError("removeItem requires a key");
|
|
27
|
+
delete store[String(key)];
|
|
28
|
+
},
|
|
29
|
+
clear: function() { store = Object.create(null); },
|
|
30
|
+
key: function(index) {
|
|
31
|
+
if (arguments.length < 1) throw new TypeError("key requires an index");
|
|
32
|
+
var key = Object.keys(store)[(+index) >>> 0];
|
|
33
|
+
return key === undefined ? null : key;
|
|
34
|
+
},
|
|
35
|
+
get length() { return Object.keys(store).length; }
|
|
36
|
+
});
|
|
37
|
+
// Storage also exposes its keys as named properties, apart from the API's
|
|
38
|
+
// own names (which remain callable even if a key has the same name).
|
|
39
|
+
return new Proxy(storage, {
|
|
40
|
+
get: function(target, key, receiver) {
|
|
41
|
+
if (typeof key === "string" && !(key in target)) return store[key];
|
|
42
|
+
return Reflect.get(target, key, receiver);
|
|
43
|
+
},
|
|
44
|
+
set: function(target, key, value, receiver) {
|
|
45
|
+
if (typeof key !== "string") return Reflect.set(target, key, value, receiver);
|
|
46
|
+
target.setItem(key, value);
|
|
47
|
+
return true;
|
|
48
|
+
},
|
|
49
|
+
deleteProperty: function(target, key) {
|
|
50
|
+
if (typeof key !== "string") return Reflect.deleteProperty(target, key);
|
|
51
|
+
target.removeItem(key);
|
|
52
|
+
return true;
|
|
53
|
+
},
|
|
54
|
+
has: function(target, key) {
|
|
55
|
+
return key in target || (typeof key === "string" && hasKey(key));
|
|
56
|
+
},
|
|
57
|
+
ownKeys: function(target) {
|
|
58
|
+
var own = Reflect.ownKeys(target);
|
|
59
|
+
return own.concat(Object.keys(store).filter(function(key) { return own.indexOf(key) === -1; }));
|
|
60
|
+
},
|
|
61
|
+
getOwnPropertyDescriptor: function(target, key) {
|
|
62
|
+
var own = Reflect.getOwnPropertyDescriptor(target, key);
|
|
63
|
+
if (own || typeof key !== "string" || !hasKey(key)) return own;
|
|
64
|
+
return { value: store[key], writable: true, enumerable: true, configurable: true };
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function polyfillStorage(type) {
|
|
70
|
+
try {
|
|
71
|
+
window[type].getItem("__pi_web_storage_probe__");
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error && error.name === "SecurityError") {
|
|
74
|
+
Object.defineProperty(window, type, {
|
|
75
|
+
value: createMemoryStorage(), configurable: true, enumerable: true
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
polyfillStorage("localStorage");
|
|
81
|
+
polyfillStorage("sessionStorage");
|
|
82
|
+
})();
|
|
83
|
+
<\/script>`,pE=/\uFEFF?(?:\s|<!--[\s\S]*?-->|<!doctype\b[^>]*>|<\?[^>]*>)*/iy,pM=/<html(?=[\s/>])(?:[^>"']|"[^"]*"|'[^']*')*>(?:\s|<!--[\s\S]*?-->)*/iy,p$=/<head(?=[\s/>])(?:[^>"']|"[^"]*"|'[^']*')*>/iy;function pI(e,t,n){return e.lastIndex=n,e.exec(t)?e.lastIndex:n}function pT(e){if(!e||e.includes(pN))return e;let t=pI(pE,e,0),n=pI(pM,e,t),r=pI(p$,e,n),i=r>n?r:t;return e.slice(0,i)+pN+e.slice(i)}var pR=n(73620);let pA=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pL(e){let t=function(e){let t=pA.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,pR.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}function pP(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let pz=[",",";"," ","|"];function pO(e){let t=/\.(csv|tsv)$/i.exec(e);return t?"tsv"===t[1].toLowerCase()?" ":",":null}function pW(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.complete??!0,i=n.maxRecords??1/0,s=[],l=[],a=e.length,o=t.charCodeAt(0),c=+(65279===e.charCodeAt(0)),d=1,u=[],p=1,h=!1,m=()=>{(1!==u.length||""!==u[0]||h)&&(s.push(u),l.push(p)),u=[],h=!1};for(;c<a&&s.length<i;){let t="",n=!1;if(34===e.charCodeAt(c)){h=!0,n=!0;let r=c+=1;for(;c<a;){let i=e.indexOf('"',c);if(-1===i)break;if(34===e.charCodeAt(i+1)){t+=e.slice(r,i+1),r=c=i+2;continue}t+=e.slice(r,i),c=i+1,n=!1;break}n&&(t+=e.slice(r),c=a),d+=function(e){let t=0,n=e.indexOf("\n");for(;-1!==n;)t+=1,n=e.indexOf("\n",n+1);return t}(t)}let i=c;for(;i<a;){let t=e.charCodeAt(i);if(t===o||10===t)break;i+=1}let s=i<a?e.charCodeAt(i):-1,l=s!==o&&i>c&&13===e.charCodeAt(i-1)?i-1:i;t+=e.slice(c,l),u.push(t),c=i,s===o?(c+=1)===a&&(u.push(""),r&&m()):10===s?(c+=1,d+=1,m(),p=d):r&&m()}return{records:s,lines:l}}function pF(e){let t=e.indexOf("\n"),n=-1===t?e:e.slice(0,t),r=0;for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);t>=56320&&t<=57343||(r+=t>=11904?2:1)}return r}let pD={display:"flex",height:26,boxSizing:"border-box",borderBottom:"1px solid var(--border)"},p_={position:"sticky",left:0,zIndex:1,boxSizing:"border-box",width:56,flexShrink:0,padding:"0 10px",display:"flex",alignItems:"center",justifyContent:"flex-end",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontSize:11,fontVariantNumeric:"tabular-nums",userSelect:"none"},pB={boxSizing:"border-box",flexShrink:0,padding:"0 10px",lineHeight:"25px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",borderRight:"1px solid var(--border)"};function pH(e){let{content:t,filePath:n,complete:r,scrollRef:i}=e,s=(0,u.useMemo)(()=>(function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2],r=pO(t)??",",i=","===r?function(e){let t=e.slice(0,65536),n=t.length===e.length,r=",",i=0;for(let e of pz){let{records:s}=pW(t,e,{complete:n,maxRecords:20}),l=s[0]?.length??0;if(l<2)continue;let a=1e3*s.filter(e=>e.length===l).length+Math.min(l,999);a>i&&(r=e,i=a)}return r}(e):r,{records:s,lines:l}=pW(e,i,{complete:n});if(0===s.length)return{columns:[],headerLine:0,rows:[],rowLines:[]};let a=0;for(let e of s)e.length>a&&(a=e.length);let o=s[0];return{columns:o.length===a?o:[...o,...Array.from({length:a-o.length},()=>"")],headerLine:l[0],rows:s.slice(1),rowLines:l.slice(1)}})(t,n,r),[r,t,n]),l=(0,u.useMemo)(()=>{var e,t;let n;return e=s.columns,n=Math.max(1,Math.ceil((t=s.rows).length/500)),e.map((e,r)=>{let i=pF(e);for(let e=0;e<t.length;e+=n){let n=t[e][r];if(n){let e=pF(n);e>i&&(i=e)}}return Math.min(Math.max(Math.ceil(7.4*i+22),64),420)})},[s]),a=(0,u.useMemo)(()=>l.reduce((e,t)=>e+t,56),[l]),[o,c]=(0,u.useState)(0),[p,h]=(0,u.useState)(0);if((0,u.useEffect)(()=>{let e=i.current;if(!e)return;let t=null,n=()=>{c(e.scrollTop),h(e.clientHeight)},r=()=>{null===t&&(t=requestAnimationFrame(()=>{t=null,n()}))};n(),e.addEventListener("scroll",r,{passive:!0});let s="u"<typeof ResizeObserver?null:new ResizeObserver(n);return s?.observe(e),()=>{e.removeEventListener("scroll",r),s?.disconnect(),null!==t&&cancelAnimationFrame(t)}},[i]),0===s.columns.length)return null;let{start:m,end:f}=function(e,t,n){if(e<=0)return{start:0,end:0};let r=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(n)&&n>0?n:800,s=Math.max(0,Math.floor(r/26)-20),l=Math.min(e,Math.ceil((r+i)/26)+20);return{start:Math.min(s,l),end:l}}(s.rows.length,o-26,p),g=[];for(let e=m;e<f;e+=1){let t=s.rows[e];g.push((0,d.jsxs)("div",{role:"row","aria-rowindex":e+2,style:{...pD,position:"absolute",top:26*e,left:0,width:a},children:[(0,d.jsx)("div",{role:"rowheader",style:p_,children:s.rowLines[e]}),l.map((e,n)=>{let r=t[n]??"";return(0,d.jsx)("div",{role:"cell",style:{...pB,width:e},title:r||void 0,children:r},n)})]},e))}return(0,d.jsxs)("div",{role:"table","aria-rowcount":s.rows.length+1,"aria-colcount":s.columns.length,style:{width:a,minWidth:"100%",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:12,color:"var(--text-muted)",background:"var(--bg)"},children:[(0,d.jsxs)("div",{role:"row","aria-rowindex":1,style:{...pD,position:"sticky",top:0,zIndex:2,width:a,background:"var(--bg-panel)",color:"var(--text)",fontWeight:600},children:[(0,d.jsx)("div",{role:"rowheader",style:p_,children:s.headerLine}),s.columns.map((e,t)=>(0,d.jsx)("div",{role:"columnheader",style:{...pB,width:l[t]},title:e||void 0,children:e},t))]}),(0,d.jsx)("div",{style:{position:"relative",height:26*s.rows.length},children:g})]})}let pU=["tags","categories","keywords","tag","category"];function pK(e){var t;let{data:n}=e;if(!n)return null;let r=Object.entries(n);if(0===r.length)return null;let i="string"==typeof(t=n.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=pU.find(e=>Array.isArray(n[e])),l=s?n[s].map(pP).filter(Boolean):[],a=r.filter(e=>{let[t]=e;return t!==s&&("title"!==t||!i)});return(0,d.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,d.jsx)("div",{className:"markdown-frontmatter-title",children:i}),l.length>0&&(0,d.jsx)("div",{className:"markdown-frontmatter-tags",children:l.map((e,t)=>(0,d.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),a.length>0&&(0,d.jsx)("dl",{className:"markdown-frontmatter-rows",children:a.map(e=>{let[t,n]=e;return(0,d.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,d.jsx)("dt",{children:t}),(0,d.jsx)("dd",{children:function(e){let t=pP(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,d.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(n)})]},t)})})]})}function pq(e){let{contentRef:t,enabled:n,partial:r,mode:i,prepareSearch:s}=e,{t:l}=(0,ns.s)(),[a,o]=(0,u.useState)(!1),[c,p]=(0,u.useState)(""),[h,m]=(0,u.useState)({ranges:[],limited:!1}),[f,x]=(0,u.useState)(0),[v,b]=(0,u.useState)([]),[y,w]=(0,u.useState)(0),j=(0,u.useRef)(null),k=t.current?.closest(".file-viewer-shell"),S=a&&n,C=(0,u.useCallback)(()=>{s(),o(!0),requestAnimationFrame(()=>{j.current?.focus(),j.current?.select()})},[s]),N=(0,u.useCallback)(()=>{o(!1),t.current?.focus({preventScroll:!0})},[t]);(0,u.useEffect)(()=>{"embedded"===i&&o(!1)},[i]),(0,u.useEffect)(()=>{if(!n)return;let e=e=>{let n=t.current?.closest(".file-viewer-shell");!n||n.closest('[inert], [aria-hidden="true"]')||!n.getClientRects().length||n.contains(e.target)&&((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&"f"===e.key.toLowerCase()?(e.preventDefault(),e.stopPropagation(),C()):a&&"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),N()))};return document.addEventListener("keydown",e,!0),()=>document.removeEventListener("keydown",e,!0)},[N,t,n,a,C]),(0,u.useEffect)(()=>{let e=t.current;if(!S||!e)return;let n=()=>{m(function(e,t){if(!t)return{ranges:[],limited:!1};let n=[],r="",i=null,s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;s.nextNode();){let e=s.currentNode,t=e.parentElement;if(!t||t.closest('button, script, style, svg, [aria-hidden="true"], .react-syntax-highlighter-line-number')||t.closest(".file-source-view, .file-diff-view")&&!t.closest(".file-source-line-content, .file-diff-line-content"))continue;let l=t.closest(".file-source-line-content, .file-diff-line-content, p, li, h1, h2, h3, h4, h5, h6, pre, td, th");l!==i&&(r+="\n"),i=l;let a=r.length;r+=e.data,n.push({node:e,start:a,end:r.length})}let l=RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"giu"),a=[],o=0;for(let e of r.matchAll(l)){if(5e3===a.length)return{ranges:a,limited:!0};let t=e.index,r=t+e[0].length;for(;o<n.length&&n[o].end<=t;)o++;let i=o;for(;i<n.length&&n[i].end<r;)i++;if(!n[o]||!n[i])continue;let s=document.createRange();s.setStart(n[o].node,t-n[o].start),s.setEnd(n[i].node,r-n[i].start),a.push(s)}return{ranges:a,limited:!1}}(e,c)),x(0)};n();let r=new MutationObserver(n);return r.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>r.disconnect()},[S,t,c,i]),(0,u.useEffect)(()=>{let e=t.current;if(!S||!e)return;let n=h.ranges[f];if(!n?.startContainer.isConnected)return;let r=n.getBoundingClientRect(),i=e.getBoundingClientRect();e.scrollBy({top:r.top<i.top+70||r.bottom>i.bottom?r.top-i.top-e.clientHeight/2:0,left:r.left<i.left+48||r.right>i.right?r.left-i.left-e.clientWidth/2:0,behavior:"instant"})},[S,t,f,h]),(0,u.useEffect)(()=>{let e=t.current;if(!S||!e)return;let n=CSS.highlights,r=window.Highlight,i=!!(n&&r);n&&r&&(n.set("file-find",new r(...h.ranges)),n.set("file-find-current",new r(...h.ranges.slice(f,f+1))));let s=0,l=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{if(w(e.offsetTop),i)return void b([]);let t=e.getBoundingClientRect(),n=[];h.ranges.forEach((e,r)=>{if(!e.startContainer.isConnected)return;let i=e.getBoundingClientRect();if(!(i.bottom<t.top)&&!(i.top>t.bottom)&&!(i.right<t.left)&&!(i.left>t.right))for(let i of e.getClientRects())n.push({top:i.top-t.top,left:i.left-t.left,width:i.width,height:i.height,active:r===f})}),b(n)})};l(),e.addEventListener("scroll",l,{passive:!0});let a=new ResizeObserver(l);return a.observe(e),()=>{cancelAnimationFrame(s),a.disconnect(),e.removeEventListener("scroll",l),n?.delete("file-find"),n?.delete("file-find-current")}},[S,t,f,h]);let E=e=>x(t=>h.ranges.length?(t+e+h.ranges.length)%h.ranges.length:0);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:"file-viewer-icon-button",onClick:C,title:`${l("files.find")} (Ctrl+F)`,"aria-label":l("files.find"),"aria-expanded":S,children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"10.5",cy:"10.5",r:"6.5"}),(0,d.jsx)("path",{d:"m16 16 4 4"})]})}),S&&k&&(0,g.createPortal)((0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("style",{children:`::highlight(file-find) { background: color-mix(in srgb, var(--accent) 20%, var(--bg)); color: var(--text); }
|
|
84
|
+
::highlight(file-find-current) { background: var(--accent); color: var(--accent-contrast); }`}),(0,d.jsxs)("div",{className:"file-find-bar",role:"search","aria-label":l("files.find"),style:{top:y+8},children:[(0,d.jsxs)("div",{className:"file-find-row",children:[(0,d.jsx)("input",{ref:j,type:"search",value:c,placeholder:l("files.findPlaceholder"),"aria-label":l("files.findPlaceholder"),spellCheck:!1,onChange:e=>p(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),E(e.shiftKey?-1:1))}}),(0,d.jsx)("span",{className:"file-find-count",role:"status","aria-live":"polite",children:c?`${h.ranges.length?f+1:0} / ${h.ranges.length}${h.limited?"+":""}`:""}),(0,d.jsx)("button",{type:"button",disabled:!h.ranges.length,onClick:()=>E(-1),title:l("files.findPrevious"),"aria-label":l("files.findPrevious"),children:"↑"}),(0,d.jsx)("button",{type:"button",disabled:!h.ranges.length,onClick:()=>E(1),title:l("files.findNext"),"aria-label":l("files.findNext"),children:"↓"}),(0,d.jsx)("button",{type:"button",onClick:N,title:l("files.closeFind"),"aria-label":l("files.closeFind"),children:"\xd7"})]}),(r||"diff"===i)&&(0,d.jsx)("div",{className:"file-find-scope",children:l(r?"files.findLoadedOnly":"files.findDiffOnly")})]}),v.length>0&&(0,d.jsx)("div",{className:"file-find-highlights","aria-hidden":"true",style:{top:y},children:v.map((e,t)=>(0,d.jsx)("span",{className:e.active?"is-current":"",style:{top:e.top,left:e.left,width:e.width,height:e.height}},t))})]}),k)]})}function pV(e){let{filePath:t,cwd:n}=e,r=e0(t),i=e3(r,n),s=i.split("/").filter(Boolean);n&&i!==r?s.unshift(e2(n)):r.startsWith("/")&&s.unshift(r.startsWith("//")?"//":"/");let l=s.pop()??e2(t);return(0,d.jsx)("div",{className:"file-viewer-path",title:t,children:(0,d.jsxs)("div",{className:"file-breadcrumb",role:"group","aria-label":t,children:[s.length>0&&(0,d.jsx)("span",{className:"file-breadcrumb-parents","aria-hidden":"true",children:s.map((e,t)=>(0,d.jsxs)("span",{className:"file-breadcrumb-segment",children:[(0,d.jsx)("span",{children:e}),(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"m9 5 7 7-7 7"})})]},t))}),(0,d.jsx)("strong",{className:"file-breadcrumb-current","aria-current":"location",children:l})]})})}let pZ=new Set(["md","markdown","mdx","mdown","mkd","rst","adoc","txt"]),pJ={source:"Source",preview:"Preview",diff:"Diff"},pY={fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:13,lineHeight:1.6},pG={...lM.xJ,'pre[class*="language-"]':{...lM.xJ['pre[class*="language-"]']}};delete pG['pre[class*="language-"]'].background;let pX={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"},pQ={...pX,position:"sticky",left:0,zIndex:1};function p0(){return(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,d.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function p1(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function p2(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=p1(n.startContainer),i=p1(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(l))return null;if(s<l){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(l=Number((i=e).dataset.lineNumber))}}}return s>l?null:{startLine:s,endLine:l}}function p4(e){let{rows:t,stylesheet:n,useInlineStyles:r,wrapLines:i}=e;return t.map((e,t)=>{let s=e.children??[],l=s[0]?.properties?.className,a=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),o=a?s[0]:null,c=a?s.slice(1):s;return(0,d.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[o&&(0,lN.Ay)({node:o,stylesheet:n,useInlineStyles:r,key:`source-line-number-${t}`}),(0,d.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,i)=>(0,lN.Ay)({node:e,stylesheet:n,useInlineStyles:r,key:`source-token-${t}-${i}`}))})]},`source-line-${t}`)})}function p3(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=e1(e),s=new URLSearchParams({type:t});for(let[e,i]of(n&&s.set("sessionId",n),"watch"===t&&s.set("holder",tH()),Object.entries(r)))void 0!==i&&s.set(e,String(i));return`/api/files/${i}?${s.toString()}`}let p8=0;function p6(e,t,n,r){return(0,u.useMemo)(()=>p3(e,t,n,{v:++p8}),[e,t,n,r])}function p5(){let[e,t]=(0,u.useState)(0),n=(0,u.useRef)(0);return[e,(0,u.useCallback)(e=>{let r,i,s=()=>{clearTimeout(r),e.close(),i??=setTimeout(()=>t(e=>e+1),Math.min(1e3*2**n.current++,3e4))},l=()=>{clearTimeout(r),r=setTimeout(s,75e3)};for(let t of(e.addEventListener("connected",()=>{n.current=0}),["connected","change","ping"]))e.addEventListener(t,l);return e.addEventListener("error",()=>{e.readyState===EventSource.CLOSED&&s()}),l(),()=>{clearTimeout(r),clearTimeout(i)}},[])]}function p9(e){let{filePath:t,sourceSessionId:n}=e,{t:r}=(0,ns.s)();return(0,d.jsx)("a",{href:p3(t,"download",n),download:e2(t),title:r("i18n.downloadFile"),"aria-label":r("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,d.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,d.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function p7(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}let he=(0,u.memo)(function(e){let{text:t,language:n,prismReady:r,isDark:i,wrapLines:s}=e;return r&&"text"!==n&&t?(0,d.jsx)(lE.A,{language:n,style:i?pG:lM.vs,showLineNumbers:!1,wrapLongLines:s,PreTag:"span",CodeTag:"span",customStyle:{margin:0,padding:0,border:0,backgroundColor:"transparent",display:"inline",overflow:"visible",fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",whiteSpace:"inherit",overflowWrap:"inherit"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)"}},children:t}):(0,d.jsx)(d.Fragment,{children:t||"\xa0"})}),ht=(0,u.memo)(function(e){let t,{patch:n,wrapLines:r,language:i="text",prismReady:s=!1,isDark:l=!1}=e,{t:a}=(0,ns.s)(),o=(t=aj(n))?t.flatMap(ak):[],c=e=>"added"===e.type||"removed"===e.type;if(!o.some(c))return(0,d.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:a("i18n.noChanges")});let u=new Set(o.flatMap((e,t)=>c(e)?[t]:[])),p=new Set;for(let e of u)for(let t=Math.max(0,e-3);t<=Math.min(o.length-1,e+3);t++)p.add(t);let h=p.size<=1e3?pQ:pX,m="text"!==i&&s&&p.size<=1e3,f=e=>"gap"!==o[e].type&&p.has(e),g=[],x=0;for(;x<o.length;)if(f(x)){let e=[];for(;x<o.length&&f(x);){let t=o[x];"gap"!==t.type&&e.push(t),x++}g.push({hidden:!1,lines:e})}else{let e=0;for(;x<o.length&&!f(x);){let t=o[x],n="gap"===t.type?t.count:1;e=null===e||null===n?null:e+n,x++}g.push({hidden:!0,count:e})}return(0,d.jsx)("div",{className:"file-diff-view",style:{width:r?"100%":"max-content",minWidth:"100%",...pY},children:g.map((e,t)=>{if(e.hidden)return(0,d.jsx)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:null===e.count?"⋯":`⋯ ${aS(e.count,a)}`},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,d.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,d.jsx)("span",{style:h,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,d.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:o,userSelect:"none",flexShrink:0,fontWeight:600},children:a}),(0,d.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:+!!r,minWidth:0,padding:"0 8px 0 0",whiteSpace:r?"pre-wrap":"pre",overflowWrap:r?"anywhere":"normal",color:"var(--text)"},children:m?(0,d.jsx)(he,{text:e.text||"",language:i,prismReady:s,isDark:l,wrapLines:r}):e.text||"\xa0"})]},t)});return(0,d.jsx)("div",{children:n},t)})})});function hn(e){let{filePath:t,cwd:n,sourceSessionId:r,watchEnabled:i=!0}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(!1),[o,c]=p5(),[p,h]=(0,u.useState)(0),[m,f]=(0,u.useState)(null),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(null),y=(0,u.useRef)(null),w=(0,u.useRef)(0),j=(0,u.useRef)(null),k=e2(t).toLowerCase().split(".").pop()??"";(0,u.useEffect)(()=>{h(0),f(null),x(null),b(null),a(!1),j.current=null},[t,r]),(0,u.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!i)return;let e=!0,n=tV("file-watch",new EventSource(p3(t,"watch",r)),t);y.current=n;let s=c(n);n.addEventListener("connected",()=>{let n;a(!0),n=++w.current,fetch(p3(t,"meta",r)).then(e=>e.json()).then(t=>{if(!e||n!==w.current)return;if(t.error)return void b(t.error);"number"==typeof t.size&&f(t.size),b(null);let r=pS(t);pC(j.current,r)&&(j.current=r,x(null),h(e=>e+1))}).catch(t=>{e&&n===w.current&&b(String(t))})}),n.addEventListener("change",e=>{w.current+=1,j.current=null;try{let t=JSON.parse(e.data);j.current=pS(t),"number"==typeof t.size&&f(t.size)}catch{}x(null),b(null),h(e=>e+1)});let l=()=>{a(!1)};return n.addEventListener("error",l),n.onerror=l,()=>{e=!1,n.close(),s(),y.current===n&&(y.current=null)}},[t,r,i,o,c]);let S=p6(t,"read",r,p),C=null!=m?p7(m):null;return(0,d.jsxs)("div",{className:"file-viewer-shell file-media-viewer",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.jsxs)("div",{className:"file-viewer-toolbar file-media-toolbar",style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,d.jsx)(pV,{filePath:t,cwd:n}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:k||"image"}),g&&(0,d.jsxs)("span",{children:[g.w," \xd7 ",g.h]}),C&&(0,d.jsx)("span",{children:C}),(0,d.jsxs)("span",{title:l?s("i18n.liveSync"):s("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?"live":"static"]}),(0,d.jsx)(p9,{filePath:t,sourceSessionId:r})]}),(0,d.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:v?(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13},children:v}):(0,d.jsx)("img",{src:S,alt:t,onLoad:e=>{let t=e.currentTarget;x({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>b(s("files.imageLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function hr(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function hi(e){let{filePath:t,cwd:n,sourceSessionId:r,watchEnabled:i=!0}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(!1),[o,c]=p5(),[p,h]=(0,u.useState)(0),[m,f]=(0,u.useState)(null),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(null),y=(0,u.useRef)(null),w=(0,u.useRef)(0),j=(0,u.useRef)(null),k=e2(t).toLowerCase().split(".").pop()??"";(0,u.useEffect)(()=>{h(0),f(null),x(null),b(null),a(!1),j.current=null},[t,r]),(0,u.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!i)return;let e=!0,n=tV("file-watch",new EventSource(p3(t,"watch",r)),t);y.current=n;let s=c(n);n.addEventListener("connected",()=>{let n;a(!0),n=++w.current,fetch(p3(t,"meta",r)).then(e=>e.json()).then(t=>{if(!e||n!==w.current)return;if(t.error)return void b(t.error);"number"==typeof t.size&&f(t.size),b(null);let r=pS(t);pC(j.current,r)&&(j.current=r,x(null),h(e=>e+1))}).catch(t=>{e&&n===w.current&&b(String(t))})}),n.addEventListener("change",e=>{w.current+=1,j.current=null;try{let t=JSON.parse(e.data);j.current=pS(t),"number"==typeof t.size&&f(t.size)}catch{}x(null),b(null),h(e=>e+1)});let l=()=>{a(!1)};return n.addEventListener("error",l),n.onerror=l,()=>{e=!1,n.close(),s(),y.current===n&&(y.current=null)}},[t,r,i,o,c]);let S=p6(t,"read",r,p);return(0,d.jsxs)("div",{className:"file-viewer-shell file-media-viewer",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.jsxs)("div",{className:"file-viewer-toolbar file-media-toolbar",style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,d.jsx)(pV,{filePath:t,cwd:n}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:k||"audio"}),null!=g&&(0,d.jsx)("span",{children:hr(g)}),null!=m&&(0,d.jsx)("span",{children:p7(m)}),(0,d.jsxs)("span",{title:l?s("i18n.liveSync"):s("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?"live":"static"]}),(0,d.jsx)(p9,{filePath:t,sourceSessionId:r})]}),(0,d.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,d.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[v&&(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:v}),(0,d.jsx)("audio",{controls:!0,preload:"metadata",src:S,onLoadedMetadata:e=>x(e.currentTarget.duration),onError:()=>b(s("files.audioLoadFailed")),style:{width:"100%"}},S)]})})]})}function hs(e){let{filePath:t,cwd:n,sourceSessionId:r,watchEnabled:i=!0}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(!1),[o,c]=p5(),[p,h]=(0,u.useState)(0),[m,f]=(0,u.useState)(null),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(null),y=(0,u.useRef)(null),w=(0,u.useRef)(0),j=(0,u.useRef)(null),k=e2(t).toLowerCase().split(".").pop()??"";(0,u.useEffect)(()=>{h(0),f(null),x(null),b(null),a(!1),j.current=null},[t,r]),(0,u.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!i)return;let e=!0,n=tV("file-watch",new EventSource(p3(t,"watch",r)),t);y.current=n;let s=c(n);n.addEventListener("connected",()=>{let n;a(!0),n=++w.current,fetch(p3(t,"meta",r)).then(e=>e.json()).then(t=>{if(!e||n!==w.current)return;if(t.error)return void b(t.error);"number"==typeof t.size&&f(t.size),b(null);let r=pS(t);pC(j.current,r)&&(j.current=r,x(null),h(e=>e+1))}).catch(t=>{e&&n===w.current&&b(String(t))})}),n.addEventListener("change",e=>{w.current+=1,j.current=null;try{let t=JSON.parse(e.data);j.current=pS(t),"number"==typeof t.size&&f(t.size)}catch{}x(null),b(null),h(e=>e+1)});let l=()=>{a(!1)};return n.addEventListener("error",l),n.onerror=l,()=>{e=!1,n.close(),s(),y.current===n&&(y.current=null)}},[t,r,i,o,c]);let S=p6(t,"read",r,p);return(0,d.jsxs)("div",{className:"file-viewer-shell file-media-viewer",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.jsxs)("div",{className:"file-viewer-toolbar file-media-toolbar",style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,d.jsx)(pV,{filePath:t,cwd:n}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:k||"video"}),null!=g&&(0,d.jsx)("span",{children:hr(g)}),null!=m&&(0,d.jsx)("span",{children:p7(m)}),(0,d.jsxs)("span",{title:l?s("i18n.liveSync"):s("i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?"live":"static"]}),(0,d.jsx)(p9,{filePath:t,sourceSessionId:r})]}),(0,d.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,d.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[v&&(0,d.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:v}),(0,d.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:S,onLoadedMetadata:e=>x(e.currentTarget.duration),onError:()=>b(s("files.videoLoadFailed")),style:{maxWidth:"100%",maxHeight:"100%"}},S)]})})]})}function hl(e){let{filePath:t,cwd:n,sourceSessionId:r,initialPage:i,watchEnabled:s=!0}=e,{t:l}=(0,ns.s)(),[a,o]=(0,u.useState)(!1),[c,p]=p5(),[h,m]=(0,u.useState)(0),[f,g]=(0,u.useState)(null),[x,v]=(0,u.useState)(null),b=(0,u.useRef)(null),y=(0,u.useRef)(0),w=(0,u.useRef)(null),j=sA(t),k="pdf"===j,S=k&&i&&i>0?`#page=${i}`:"",C=`${p6(t,k?"read":"preview",r,h)}${S}`;return(0,u.useEffect)(()=>{m(0),g(null),v(null),o(!1),w.current=null;let e=!0,n=++y.current;return fetch(p3(t,"meta",r)).then(e=>e.json()).then(t=>{e&&n===y.current&&(t.error&&v(t.error),"number"==typeof t.size&&(g(t.size),!k&&t.size>0xa00000&&v("DOCX too large for preview (>10MB)")))}).catch(t=>{e&&n===y.current&&v(String(t))}),()=>{e=!1}},[t,k,r]),(0,u.useEffect)(()=>{if(o(!1),b.current&&(b.current.close(),b.current=null),!s)return;let e=!0,n=tV("file-watch",new EventSource(p3(t,"watch",r)),t);b.current=n;let i=p(n);n.addEventListener("connected",()=>{let n;o(!0),n=++y.current,fetch(p3(t,"meta",r)).then(e=>e.json()).then(t=>{if(!e||n!==y.current)return;if(t.error)return void v(t.error);if("number"==typeof t.size&&(g(t.size),!k&&t.size>0xa00000))return void v("DOCX too large for preview (>10MB)");v(null);let r=pS(t);pC(w.current,r)&&(w.current=r,m(e=>e+1))}).catch(t=>{e&&n===y.current&&v(String(t))})}),n.addEventListener("change",e=>{y.current+=1,w.current=null;try{let t=JSON.parse(e.data);if(w.current=pS(t),"number"==typeof t.size&&(g(t.size),!k&&t.size>0xa00000))return void v("DOCX too large for preview (>10MB)")}catch{}v(null),m(e=>e+1)});let l=()=>{o(!1)};return n.addEventListener("error",l),n.onerror=l,()=>{e=!1,n.close(),i(),b.current===n&&(b.current=null)}},[t,k,r,s,c,p]),(0,d.jsxs)("div",{className:"file-viewer-shell file-media-viewer",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,d.jsxs)("div",{className:"file-viewer-toolbar file-media-toolbar",style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,d.jsx)(pV,{filePath:t,cwd:n}),(0,d.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===j?"docx preview":"pdf"}),null!=f&&(0,d.jsx)("span",{children:p7(f)}),(0,d.jsx)(p9,{filePath:t,sourceSessionId:r}),(0,d.jsxs)("span",{title:l(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,d.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:x?(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:x}):(0,d.jsx)("iframe",{src:C,sandbox:k?void 0:"allow-same-origin",title:l("i18n.previewFile",{file:e2(t)}),style:{width:"100%",height:"100%",border:"none",background:k?"var(--bg)":"#eef1f5"}},C)})]})}function ha(e){let t,n,{filePath:r,cwd:i,sourceSessionId:s,onOpenFile:l,onMentionLines:a,onAtMention:o,gitRefreshKey:c,initialDisplayMode:p,initialState:h,initialPage:m,onStateChange:f,watchEnabled:g=!0}=e,x=function(){let e=(0,u.useSyncExternalStore)(d4,d3,d8),[t,n]=(0,u.useState)(!1);return(0,u.useEffect)(()=>{if(!e)return void n(!1);let t=setTimeout(()=>n(!0),3e4);return()=>clearTimeout(t)},[3e4,e]),e&&t}(),v=g&&!x;return null!==(Object.hasOwn(sI,t=sA(r))?sI[t]:null)?(0,d.jsx)(hn,{filePath:r,cwd:i,sourceSessionId:s,watchEnabled:v}):sL(r)?(0,d.jsx)(hi,{filePath:r,cwd:i,sourceSessionId:s,watchEnabled:v}):sP(r)?(0,d.jsx)(hs,{filePath:r,cwd:i,sourceSessionId:s,watchEnabled:v}):null!==("pdf"===(n=sA(r))||"docx"===n?n:null)?(0,d.jsx)(hl,{filePath:r,cwd:i,sourceSessionId:s,initialPage:m,watchEnabled:v}):(0,d.jsx)(ho,{filePath:r,cwd:i,sourceSessionId:s,onOpenFile:l,onMentionLines:a,onAtMention:o,gitRefreshKey:c,initialDisplayMode:p,initialState:h,onStateChange:f,watchEnabled:v})}function ho(e){let{filePath:t,cwd:n,sourceSessionId:r,onOpenFile:i,onMentionLines:s,onAtMention:l,gitRefreshKey:a,initialDisplayMode:o,initialState:c,onStateChange:p,watchEnabled:h=!0}=e,{isDark:f}=lH(),{t:g}=(0,ns.s)(),[x,v]=(0,u.useState)(null),[b,y]=(0,u.useState)(null),[w,j]=(0,u.useState)(!1),[k,S]=(0,u.useState)(!1),[C,N]=(0,u.useState)(!0),[E,M]=(0,u.useState)(!1),[$,I]=(0,u.useState)(null),T=c?.displayMode??o??"source",R=c?.wrapLines??function(e){if(!e)return!1;let t=(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??"";return pZ.has(t)}(t),A=c?.scrollTop??0,L=c?.scrollLeft??0,[P,z]=(0,u.useState)(T),[O,W]=(0,u.useState)(R),[F,D]=(0,u.useState)(!1),[_,B]=p5(),H=(0,u.useRef)(null),U=(0,u.useRef)(0),K=(0,u.useRef)(null),q=(0,u.useRef)(0),V=(0,u.useRef)(null),Z=(0,u.useRef)(!1),J=(0,u.useRef)(void 0===c&&void 0===o),Y=(0,u.useRef)(!0),G=(0,u.useRef)({displayMode:T,wrapLines:R,scrollTop:A,scrollLeft:L}),X=(0,u.useRef)(p),[Q,ee]=(0,u.useState)(null),[et,en]=(0,u.useState)(null);X.current=p;let er=(0,u.useRef)(i);er.current=i;let ei=(0,u.useCallback)(e=>{G.current.displayMode=e,z(e)},[]),es=(0,u.useCallback)(()=>{W(e=>{let t=!e;return G.current.wrapLines=t,t})},[]);(0,u.useEffect)(()=>(G.current={displayMode:T,wrapLines:R,scrollTop:A,scrollLeft:L},Y.current=!0,Z.current=!1,z(T),W(R),()=>{X.current?.({...G.current})}),[t,r,T,R,A,L]);let el=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=++U.current;return fetch(p3(e,"read",r,{offset:t||void 0})).then(e=>e.json()).then(e=>n!==U.current?null:e.error?(I(e.error),null):(K.current=pS(e),I(null),v(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(n!==U.current||I(String(e)),null))},[r]),ea=(0,u.useCallback)(async e=>{let t=++q.current;if(j(!0),!n){y(null),j(!1),S(!0);return}try{let r=new URLSearchParams({cwd:n,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(t!==q.current)return;y(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{t===q.current&&y(null)}finally{t===q.current&&(j(!1),S(!0))}},[n]);(0,u.useEffect)(()=>{let e=!0;return N(!0),I(null),v(null),y(null),S(!1),D(!1),K.current=null,el(t).finally(()=>{e&&N(!1)}),()=>{e=!1}},[t,el,r]),(0,u.useEffect)(()=>{if(D(!1),H.current&&(H.current.close(),H.current=null),!h)return;let e=!0,n=()=>{el(t),ea(t)},i=tV("file-watch",new EventSource(p3(t,"watch",r)),t);H.current=i;let s=B(i);i.addEventListener("connected",()=>{(D(!0),null===K.current)?n():fetch(p3(t,"meta",r)).then(e=>e.json()).then(r=>{e&&(pC(K.current,pS(r))?n():ea(t))}).catch(()=>{e&&n()})}),i.addEventListener("change",n);let l=()=>{D(!1)};return i.addEventListener("error",l),i.onerror=l,()=>{e=!1,i.close(),s(),H.current===i&&(H.current=null)}},[t,el,ea,r,h,_,B]),(0,u.useEffect)(()=>{ea(t)},[ea,t,a]);let eo=x?.binary===!0,ec=!eo&&null!==pO(t);(0,u.useEffect)(()=>{J.current&&x&&!x.binary&&(ec||"markdown"===x.language&&!x.truncated||"html"===x.language&&(!x.truncated||x.size<=0xa00000))&&(J.current=!1,ei("preview"))},[x,ec,ei]);let ed="preview"===P&&x?.language==="html"&&x.truncated&&x.size<=0xa00000;(0,u.useEffect)(()=>{if(!ed)return void en(null);let e=new AbortController;return fetch(p3(t,"download",r),{signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);en({text:await e.text()})}).catch(t=>{e.signal.aborted||en({error:String(t)})}),()=>e.abort()},[ed,x,t,r]);let eu=b?.supported===!0&&"string"==typeof b.patch,ep=eu&&"deleted"===b.status;(0,u.useEffect)(()=>{k&&!eu&&"diff"===P&&ei("source")},[P,k,eu,ei]),(0,u.useEffect)(()=>{"diff"===T&&eu&&!Z.current&&(Z.current=!0,ei("diff"))},[T,eu,ei]);let eh=(0,u.useMemo)(()=>x?.language==="markdown"?s0(x.content):"",[x]),em=(0,u.useMemo)(()=>x?.language==="markdown"?pL(x.content):null,[x]),ef=x?.content??"",eg=(0,u.useMemo)(()=>ef.split("\n"),[ef]),ex=x?.language??"text",ev=lV(!!x&&"text"!==ex),eb=!eo&&"html"===ex,ey=!eo&&"markdown"===ex,ew=ec||(eb?!!x&&(!x.truncated||x.size<=0xa00000):ey&&!x?.truncated),ej=ep?"diff":P;m(V,ej);let ek=x?.truncated?et?.text:ef,eS=(0,u.useMemo)(()=>eb&&"preview"===ej?pT(ek??""):"",[eb,ej,ek]),eC=!!x?.truncated&&!(eb&&"preview"===ej),eN=eg.length>1e3&&!("diff"===ej&&eu)&&!("preview"===ej&&ew),eE=(0,u.useMemo)(()=>(0,d.jsx)(lE.A,{className:O?"file-source-view is-wrapped":"file-source-view",language:"text"!==ex&&ev?ex:"plaintext",style:f?pG:lM.vs,showLineNumbers:!0,lineNumberStyle:{...pQ},customStyle:{margin:0,padding:0,border:0,backgroundColor:"var(--bg)",...pY,width:O?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",fontWeight:"var(--font-mono-weight)",overflowWrap:O?"anywhere":"normal"}},renderer:e=>(0,d.jsx)(p4,{...e,wrapLines:O}),wrapLongLines:O,children:ef}),[f,ex,ev,ef,O]),eM=(0,u.useMemo)(()=>eN?eg.map((e,t)=>(0,d.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,d.jsx)("span",{"aria-hidden":"true",style:pX,children:t+1}),(0,d.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:O?"anywhere":"normal",whiteSpace:O?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[eg,eN,O]);(0,u.useEffect)(()=>{let e=()=>{let e=V.current;ee(t=>{let n=s&&"source"===P&&e?p2(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),s&&"source"===P)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[x?.content,P,s]);let e$=(0,u.useCallback)(e=>{s&&e&&s(e3(t,n),e.startLine,e.endLine)},[n,t,s]);(0,u.useEffect)(()=>{if(!s||"source"!==P)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=V.current,r=n?p2(n,window.getSelection()):null;r&&(e.preventDefault(),e$(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[P,e$,s]),(0,u.useEffect)(()=>{if(!Y.current||C||$&&!ep||"diff"===T&&!k||"diff"===T&&eu&&"diff"!==P)return;let e=V.current;e&&(e.scrollTop=G.current.scrollTop,e.scrollLeft=G.current.scrollLeft,Y.current=!1)},[x?.content,P,$,k,eu,ep,C,T]);let eI=!!i,eT=(0,u.useMemo)(()=>{let e=e4(t);return{code(e){let{className:t,children:n,...r}=e,i=t?.replace("language-","").toLowerCase()??"",s=String(n);return t?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,d.jsx)(l1,{code:s.replace(/\n$/,""),defaultPreview:!0}):ly(i)?(0,d.jsx)(an,{code:s.replace(/\n$/,""),lang:i}):(0,d.jsx)(ae,{code:s.replace(/\n$/,""),lang:i}):(0,d.jsx)("code",{className:t,...r,children:n})},pre(e){let{children:t}=e;return(0,d.jsx)(d.Fragment,{children:t})},a(t){let{href:r,children:i,...s}=t;delete s.node;let l=eI?su(r,e,n??e):null;return l&&eI?(0,d.jsx)("a",{href:r,...s,onClick:e=>{si(e)&&(e.preventDefault(),er.current?.(l,sh(r)??void 0))},children:i}):sY(r)?(0,d.jsx)("a",{href:r,...s,target:"_blank",rel:"noopener noreferrer",children:i}):(0,d.jsx)("a",{href:r,...s,onClick:sG,children:i})},img(t){let{src:i,alt:s,...l}=t;delete l.node;let a="string"==typeof i?su(i,e,n??e):null,o=a?p3(a,"read",r):i;return(0,d.jsx)("img",{src:o,alt:s??"",loading:"lazy",...l})}}},[n,t,eI,r]);if(C||"diff"===T&&w&&!x)return(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:g("i18n.loading")});if($&&!ep)return(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:$});if(!x&&!ep)return null;let eR=ep?["diff"]:["source",...ew?["preview"]:[],...eu?["diff"]:[]],eA=ep?g("files.deleted"):eo?`${g("files.binary")} \xb7 ${p7(x.size)}`:`${ex} \xb7 ${eg.length} lines \xb7 ${p7(x.size)}`;return(0,d.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,d.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,d.jsx)(pV,{filePath:t,cwd:n}),(0,d.jsx)("span",{className:"file-viewer-meta",title:eA,children:eA}),!ep&&(0,d.jsx)("span",{title:F?g("i18n.liveSync"):g("i18n.notWatching"),"aria-label":F?g("i18n.liveSync"):g("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:F?"#4ade80":"var(--border)",boxShadow:F?"0 0 4px #4ade80":"none"}}),(0,d.jsxs)("div",{className:"file-viewer-controls",children:[eR.length>1&&(0,d.jsx)("div",{className:"file-viewer-mode-switch","aria-label":g("i18n.fileViewMode"),children:eR.map(e=>{let t=ej===e;return(0,d.jsx)("button",{type:"button",onClick:()=>ei(e),title:"diff"===e?g("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:pJ[e]},e)})}),(0,d.jsxs)("div",{className:"file-viewer-actions",children:[(0,d.jsx)(pq,{contentRef:V,enabled:h,partial:!!x?.truncated&&"diff"!==ej,mode:"preview"===ej&&(eb||ec)?"embedded":ej,prepareSearch:()=>{"preview"===ej&&(eb||ec)&&ei("source")}}),(l||s)&&(0,d.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{Q&&s?e$(Q):l?.(e3(t,n),!1)},title:Q&&s?`${g("i18n.mentionSelectedLines")} (L${Q.startLine}${Q.startLine!==Q.endLine?`-L${Q.endLine}`:""})`:g("files.insertPath"),"aria-label":g("files.mention"),disabled:!l&&!s,className:"file-viewer-icon-button",children:(0,d.jsx)(p0,{})}),("source"===ej||"diff"===ej)&&!eo&&(0,d.jsx)(d.Fragment,{children:(0,d.jsx)("button",{type:"button",onClick:es,title:O?g("i18n.disableWrap"):g("i18n.enableWrap"),"aria-label":O?g("i18n.disableWrap"):g("i18n.enableWrap"),"aria-pressed":O,className:"file-viewer-icon-button",style:{background:O?"var(--bg-selected)":"transparent",color:O?"var(--text)":"var(--text-muted)"},children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 6h18"}),(0,d.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,d.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,d.jsx)("path",{d:"M3 18h7"})]})})})]}),!ep&&(0,d.jsx)(p9,{filePath:t,sourceSessionId:r})]})]}),eC&&x?.truncated&&(0,d.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,d.jsxs)("span",{children:[p7(x.nextOffset)," / ",p7(x.size)]}),(0,d.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:E,onClick:()=>{M(!0),el(t,x.nextOffset).finally(()=>M(!1))},children:E?g("i18n.loading"):g("i18n.loadMore")})]}),(0,d.jsx)("div",{ref:V,className:"file-viewer-content",tabIndex:0,onPointerDown:e=>{e.target.closest("button, a, input, textarea, select, [contenteditable='true']")||e.currentTarget.focus({preventScroll:!0})},onScroll:e=>{G.current.scrollTop=e.currentTarget.scrollTop,G.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:eC?48:void 0},children:"diff"===ej&&eu?(0,d.jsx)(ht,{patch:b.patch,wrapLines:O,language:ex,prismReady:ev,isDark:f}):eb&&"preview"===ej&&x?.truncated&&!et?.text?(0,d.jsx)("div",{style:{padding:24,color:"var(--text-dim)",fontSize:12},children:et?.error??g("i18n.loading")}):eb&&"preview"===ej?(0,d.jsx)("iframe",{srcDoc:eS,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:g("i18n.htmlPreview")}):ey&&"preview"===ej?(0,d.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[em?.data&&(0,d.jsx)(pK,{data:em.data}),(0,d.jsx)(sE.oz,{remarkPlugins:la,rehypePlugins:lh,urlTransform:i?sJ:sZ,components:eT,children:eh})]}):ec&&"preview"===ej?(0,d.jsx)(pH,{content:ef,filePath:t,complete:!x?.truncated,scrollRef:V}):eo?(0,d.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,padding:24,color:"var(--text-muted)",fontSize:13,textAlign:"center"},children:[(0,d.jsx)("span",{children:g("files.binaryNoPreview")}),(0,d.jsx)("a",{href:p3(t,"download",r),download:e2(t),className:"file-viewer-mode-button",style:{display:"inline-flex",alignItems:"center",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",textDecoration:"none"},children:g("files.download")})]}):eN?(0,d.jsx)("div",{className:"file-source-view is-lightweight",style:{width:O?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...pY},children:eM}):eE})]})}function hc(e,t){let n=(0,u.useRef)(null);return(0,u.useEffect)(()=>{let e=n.current;if(!e)return;let t=t=>{t.ctrlKey||Math.abs(t.deltaY)<=Math.abs(t.deltaX)||e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientWidth:1))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[]),(0,u.useEffect)(()=>{let t=n.current,r=t?.querySelector(e);if(!t||!r)return;let i=t.getBoundingClientRect(),{left:s,right:l}=r.getBoundingClientRect();s<i.left?t.scrollLeft-=i.left-s:l>i.right&&(t.scrollLeft+=l-i.right)},[e,t]),n}function hd(e){let{tool:t,size:n=20}=e;return(0,d.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:"files"===t?(0,d.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}):"side"===t?(0,d.jsx)("path",{d:"M21 11a8 8 0 0 1-8 8H5l-3 3v-10a9 9 0 0 1 19-1Z"}):"terminal"===t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"3"}),(0,d.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}):"changes"===t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"5",y:"3",width:"14",height:"18",rx:"3"}),(0,d.jsx)("path",{d:"M9 9h6m-3-3v6m-3 4h6"})]}):(0,d.jsx)("path",{d:"M12 4v16M4 12h16"})})}let hu=[{tool:"changes",label:"panel.changes",shortcut:"Ctrl+Shift+G"},{tool:"terminal",label:"panel.terminal",shortcut:"Ctrl+`"},{tool:"side",label:"sideChat.title",shortcut:"Ctrl+Alt+S"},{tool:"files",label:"panel.files",shortcut:"Ctrl+P"}];function hp(e){let{cwd:t,sideDisabled:n,onOpen:r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)(!1),a=(0,u.useRef)(!1),[o,c]=(0,u.useState)(null),p=(0,u.useRef)(!0);(0,u.useEffect)(()=>(p.current=!0,()=>{p.current=!1}),[]);let h=async e=>{if(!a.current){a.current=!0,l(!0),c(null);try{let t=await r(e);p.current&&t&&c(t)}catch{p.current&&c(i("panel.openFailed"))}finally{a.current=!1,p.current&&l(!1)}}};return(0,d.jsxs)("div",{className:"panel-tool-launcher","aria-label":i("panel.tools"),children:[(0,d.jsxs)("header",{children:[(0,d.jsx)("h2",{children:i("panel.tools")}),t&&(0,d.jsx)("p",{title:t,children:e2(t)||t})]}),(0,d.jsx)("div",{className:"panel-tool-grid",children:hu.map(e=>{let{tool:r,label:l,shortcut:a}=e;return(0,d.jsxs)("div",{children:[(0,d.jsxs)("button",{type:"button","data-panel-tool":r,disabled:s||!t||"side"===r&&!!n,onClick:()=>void h(r),children:[(0,d.jsx)(hd,{tool:r}),(0,d.jsx)("span",{children:i(l)}),(0,d.jsx)("kbd",{children:a})]}),"side"===r&&n&&(0,d.jsx)("p",{className:"panel-tool-unavailable",children:n})]},r)})}),s&&(0,d.jsx)("p",{role:"status",children:i("panel.opening")}),o&&(0,d.jsx)("p",{role:"alert",className:"panel-tool-error",children:o}),!t&&(0,d.jsx)("p",{children:i("panel.chooseProject")})]})}function hh(e){let{tabs:t,activeId:n,mobile:r,covered:i,onSelect:s,onNew:l,onClose:a}=e,{t:o}=(0,ns.s)(),c=(0,u.useRef)(null),[p,h]=(0,u.useState)(null);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{ref:c,type:"button",className:"workspace-files-toggle panel-tab-switcher",disabled:i,tabIndex:i?-1:void 0,"aria-hidden":i||void 0,title:o(t.length?"panel.openTabsCount":"panel.newTab",{count:t.length}),"aria-label":o(t.length?"panel.openTabsCount":"panel.newTab",{count:t.length}),"aria-haspopup":t.length?r?"dialog":"menu":void 0,"aria-expanded":t.length?!!p:void 0,"data-mobile-toolbar-file":r?"true":void 0,onClick:e=>{t.length?h(p?null:{kind:"rect",rect:e.currentTarget.getBoundingClientRect(),align:"end"}):l()},children:t.length?(0,d.jsx)("span",{className:"panel-tab-count","aria-hidden":"true",children:t.length}):(0,d.jsx)(hd,{tool:"launcher"})}),(0,d.jsx)(r4,{open:!!p,anchor:p,sheet:r,ariaLabel:o("panel.openTabs"),title:o("panel.openTabs"),focusKey:t.map(e=>e.id).join("\n"),width:300,cancelLabel:o("chat.close"),returnFocusTo:c.current,onClose:()=>h(null),items:[{type:"header",id:"heading",label:o("panel.openTabs")},...t.map(e=>({type:"item",id:e.id,label:e.label,title:e.filePath||e.label,checked:n===e.id,disabled:e.closing,secondary:{label:`${o("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,disabled:e.closing,revealOnHover:!0,icon:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m3 3 6 6m0-6-6 6"})}),onSelect:n=>{t.length>1&&n.keepOpen(),a(e.id)}},onSelect:()=>s(e.id)})),{type:"separator",id:"separator"},{type:"item",id:"new",label:o("panel.newTab"),icon:(0,d.jsx)(hd,{tool:"launcher",size:16}),onSelect:l}]})]})}function hm(e){let{cwd:t,refreshKey:n,onOpenFile:r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)({}),[a,o]=(0,u.useState)(0),[c,p]=(0,u.useState)(50);(0,u.useEffect)(()=>{let e=new AbortController;l({}),fetch(`/api/git/status?cwd=${encodeURIComponent(t)}`,{signal:e.signal}).then(async t=>{if(!t.ok)throw Error("read failed");let n=await t.json();e.signal.aborted||l({data:n})}).catch(()=>{e.signal.aborted||l({error:!0})});let n=()=>o(e=>e+1);return window.addEventListener("focus",n),()=>{e.abort(),window.removeEventListener("focus",n)}},[t,n,a]);let h=s.data?.files??[];return(0,d.jsxs)("section",{className:"panel-changes","aria-label":i("panel.changes"),children:[(0,d.jsxs)("header",{children:[(0,d.jsx)("h2",{children:i("panel.changes")}),(0,d.jsx)("button",{type:"button",onClick:()=>o(e=>e+1),children:i("overview.refresh")})]}),(0,d.jsx)("p",{children:i("overview.changesHint")}),s.error?(0,d.jsxs)("p",{role:"alert",children:[i("overview.loadFailed")," ",(0,d.jsx)("button",{onClick:()=>o(e=>e+1),children:i("overview.retry")})]}):s.data?s.data.isGitRepository?h.length?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"panel-change-summary",children:[(0,d.jsx)("span",{children:h.length}),(0,d.jsxs)("span",{children:["+",s.data.additions," −",s.data.deletions]})]}),h.slice(0,c).map(e=>(0,d.jsxs)("button",{className:"panel-change-row",type:"button",title:e.filePath,onClick:()=>r(e.filePath),children:[rm(e2(e.filePath)),(0,d.jsx)("span",{children:e3(e.filePath,t)}),(0,d.jsx)("small",{children:e.code})]},e.filePath)),h.length>c&&(0,d.jsx)("button",{onClick:()=>p(e=>e+50),children:i("panel.moreChanges")})]}):(0,d.jsx)("p",{children:i("overview.noChanges")}):(0,d.jsx)("p",{children:i("overview.notGit")}):(0,d.jsx)("p",{role:"status",children:i("overview.loading")})]})}function hf(e){let{tabs:t,activeTabId:n,onSelectTab:r,onCloseTab:i,onOpenFiles:s,onOpenTools:l,onReorderTab:a}=e,{t:o}=(0,ns.s)(),c=hc('[role="tab"][aria-selected="true"]',`${t.length}
|
|
85
|
+
${n}`),p=(0,u.useRef)(null),[h,m]=(0,u.useState)(null);return(0,d.jsxs)("div",{className:"file-tab-strip",children:[(0,d.jsx)("div",{ref:c,role:"tablist",className:"file-tab-list tabbar-scroll",children:t.map(e=>{let s=e.id===n;return(0,d.jsxs)("div",{role:"tab",className:`file-tab${s?" is-active":""}`,"aria-label":"terminal"===e.kind?o("terminal.tabLabel",{name:e.label}):"agent"===e.kind?o("subagent.tabLabel",{name:e.label}):"side"===e.kind?o("sideChat.tabLabel"):e.label,"aria-selected":s,draggable:!!a,onDragStart:t=>{a&&(p.current=e.id,t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.id))},onDragOver:t=>{if(!p.current||p.current===e.id)return;t.preventDefault(),t.dataTransfer.dropEffect="move";let n=t.currentTarget.getBoundingClientRect(),r=t.clientX>=n.left+n.width/2;m(t=>t?.id===e.id&&t.after===r?t:{id:e.id,after:r})},onDrop:t=>{if(!p.current||p.current===e.id)return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();a?.(p.current,e.id,t.clientX>=n.left+n.width/2),p.current=null,m(null)},onDragLeave:t=>{t.currentTarget.contains(t.relatedTarget)||m(t=>t?.id===e.id?null:t)},onDragEnd:()=>{p.current=null,m(null)},tabIndex:s||!n&&t[0].id===e.id?0:-1,onKeyDown:n=>{if(n.target===n.currentTarget){if("Enter"===n.key||" "===n.key)n.preventDefault(),r(e.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(n.key)){n.preventDefault();let i=t.findIndex(t=>t.id===e.id),s="Home"===n.key?0:"End"===n.key?t.length-1:(i+("ArrowRight"===n.key?1:-1)+t.length)%t.length;r(t[s].id),n.currentTarget.parentElement?.children[s]?.focus()}}},onClick:()=>r(e.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),e.closing||i(e.id))},style:{boxShadow:h?.id===e.id?`inset ${h.after?"-2px":"2px"} 0 var(--accent)`:void 0},children:[(0,d.jsx)("span",{className:"file-tab-icon",children:"files"===e.kind||"changes"===e.kind||"launcher"===e.kind?(0,d.jsx)(hd,{tool:e.kind,size:17}):"terminal"===e.kind?(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,d.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"agent"===e.kind?(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,d.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"side"===e.kind?(0,d.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,d.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"})}):rm(e.label,17)}),(0,d.jsx)("span",{className:"file-tab-label",title:e.filePath,children:e.label}),(0,d.jsx)("button",{type:"button",className:"file-tab-close",draggable:!1,onDragStart:e=>e.stopPropagation(),disabled:e.closing,onClick:t=>{t.stopPropagation(),i(e.id)},title:o("terminal"===e.kind?"terminal.close":"i18n.close"),"aria-label":`${o("terminal"===e.kind?"terminal.close":"i18n.close")} ${e.label}`,children:(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,d.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})}),(l||s)&&(0,d.jsx)("button",{type:"button",className:"file-tab-add",onClick:l??s,title:o(l?"panel.newTab":"files.chooseFile"),"aria-label":o(l?"panel.newTab":"files.chooseFile"),children:(0,d.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M12 4v16M4 12h16"})})})]})}function hg(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s}let hx=["general","models","skills","agents","plugins","mcp"],hv="pi-web:settings-navigation",hb=new Set(["skills","agents","plugins"]);function hy(){try{return window.localStorage}catch{return null}}function hw(e){let t=e.getItem(hv);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 hj(e,t){return"models"===e?e:t?JSON.stringify([e,t]):"mcp"===e?e:null}function hk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hy();if(!t)return"general";try{let n=hw(t).section;if(!("string"==typeof n&&hx.includes(n)))return"general";return hb.has(n)&&!e?"general":n}catch{return"general"}}function hS(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:hy();if(t)try{let n=hw(t);n.section=e,t.setItem(hv,JSON.stringify(n))}catch{}}function hC(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:hy();if(!n)return null;let r=hj(e,t);if(!r)return null;try{let e=hw(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function hN(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:hy();if(!r||!t)return;let i=hj(e,n);if(i)try{let e=hw(r);e.selections={...e.selections,[i]:t},r.setItem(hv,JSON.stringify(e))}catch{}}let hE="llama.cpp";function hM(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class h$ extends Error{constructor(e){super(`Context window of ${e} must be a positive number of tokens`),this.name="ContextWindowError",this.model=e}}function hI(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 hT={empty:e=>`Provider ${e} needs a Base URL or at least one model`,baseUrl:e=>`Provider ${e} needs a Base URL`};class hR extends Error{constructor(e,t){super(hT[t](e)),this.name="ProviderEntryError",this.provider=e,this.problem=t}}function hA(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hL(e){return!hA(e)||"string"!=typeof e.id||e.id.trim().length>0}function hP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hz(e){let t=hP(e.inputLimits)?e.inputLimits.images:void 0,n=hP(t)?t.resize:void 0;return hP(n)?n.maxBytes:void 0}function hO(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 hW(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 hF 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 hD=["input","output","cacheRead","cacheWrite"];function h_(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 hB(e){if(!hH(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 hH(e){return hD.some(t=>""!==e[t].trim())}function hU(e,t,n){return{...e,compat:{...e.compat??{},[t]:n}}}function hK(e){return new Map(Object.entries(e.providers??{}).map(e=>{let[t,n]=e;return[t,(n.models??[]).map(e=>e.id)]}))}function hq(e,t,n){if(n<=0)return;let r=e.get(t)??[];e.set(t,[...r,...Array.from({length:n},()=>null)])}function hV(e,t,n,r){let i=e.providers??{},s=i[n],l=s?.models;if(!l||r.every((e,t)=>e===t))return null;let a=t.get(n);return a&&t.set(n,r.map(e=>a[e]??null)),{config:{...e,providers:{...i,[n]:{...s,models:r.map(e=>l[e])}}},providerName:n,order:r}}function hZ(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 hJ(e,t,n){let r=e.trim().toLowerCase();return!r||n.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function hY(e){return e.name?.trim()||e.id}function hG(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 hX(e){let{embedded:t,title:n,subtitle:r,closeLabel:i="Close",onClose:s,children:l,width:a=900,height:o="78vh"}=e,c=t?void 0:{"--config-panel-width":`${a}px`,"--config-panel-height":o};return(0,d.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||s()},children:(0,d.jsxs)("div",{className:"config-panel-surface",style:c,children:[!t&&(0,d.jsxs)("div",{className:"config-panel-header",children:[(0,d.jsx)("strong",{className:"config-panel-title",children:n}),r&&(0,d.jsx)("code",{className:"config-panel-subtitle",title:r,children:r}),(0,d.jsx)("button",{type:"button",className:"config-close-button",onClick:s,title:i,"aria-label":i,children:"\xd7"})]}),l]})})}let hQ=(0,u.createContext)(null);function h0(){return(0,u.useContext)(hQ)??h1}let h1={detailOpen:!1,openDetail:()=>{},closeDetail:()=>{},reportDetailTitle:()=>{}};function h2(e,t){let{detailOpen:n,reportDetailTitle:r}=h0(),i=(0,u.useRef)(null);return(0,u.useLayoutEffect)(()=>{let t=i.current;if(!e||!n||!t||t.closest("[hidden]"))return;let s=(t.querySelector(".config-sidebar-text")??t).textContent?.trim();s&&r(s)}),e=>{i.current=e,"function"==typeof t?t(e):t&&(t.current=e)}}function h4(e){let{children:t}=e,n=(0,u.useContext)(hQ);return(0,d.jsx)("div",{className:"config-split-view","data-pane":n?n.detailOpen?"detail":"list":void 0,children:t})}function h3(e){let{children:t}=e;return(0,d.jsx)("aside",{className:"config-sidebar",children:t})}function h8(e){let{children:t}=e;return(0,d.jsx)("div",{className:"config-sidebar-list",children:t})}function h6(e){let{children:t,aside:n}=e;return(0,d.jsxs)("div",{className:"config-sidebar-group-label",children:[(0,d.jsx)("span",{className:"config-sidebar-group-label-text",children:t}),n]})}function h5(e){let{enabled:t,total:n,checked:r,label:i,disabled:s=!1,loading:l=!1,describedBy:a,onChange:o}=e;return(0,d.jsxs)("span",{className:"config-sidebar-group-switch",children:[(0,d.jsxs)("span",{className:"config-sidebar-group-count",children:[t,"/",n]}),(0,d.jsx)(mj,{checked:r??(n>0&&t===n),disabled:s,loading:l,label:i,describedBy:a,onChange:o})]})}function h9(e){let{error:t,note:n}=e;return t||n?(0,d.jsxs)("div",{className:"config-sidebar-group-status",children:[n&&(0,d.jsx)("div",{role:"status",className:"config-sidebar-group-note",children:n}),t&&(0,d.jsx)("div",{role:"alert",className:"config-sidebar-group-error",children:t})]}):null}function h7(e){let{active:t=!1,className:n,children:r,onClick:i,ref:s,...l}=e,{openDetail:a}=h0(),o=h2(t,s);return(0,d.jsx)("button",{type:"button",...l,ref:o,onClick:e=>{i?.(e),e.defaultPrevented||a()},"aria-current":t?"page":void 0,className:["config-sidebar-item",n].filter(Boolean).join(" "),children:r})}function me(e){let{className:t,...n}=e;return(0,d.jsx)("span",{...n,className:["config-sidebar-text",t].filter(Boolean).join(" ")})}function mt(e){let{className:t,...n}=e;return(0,d.jsx)("div",{...n,className:["config-detail-stack",t].filter(Boolean).join(" ")})}function mn(e){let{className:t,...n}=e;return(0,d.jsx)("div",{...n,className:["config-detail-header",t].filter(Boolean).join(" ")})}function mr(e){let{className:t,...n}=e;return(0,d.jsx)("div",{...n,className:["config-detail-header-info",t].filter(Boolean).join(" ")})}function mi(e){let{className:t,...n}=e;return(0,d.jsx)("div",{...n,className:["config-detail-actions",t].filter(Boolean).join(" ")})}function ms(e){let{children:t}=e;return(0,d.jsx)("div",{className:"config-detail-title",children:t})}function ml(e){let{children:t}=e;return(0,d.jsx)("div",{className:"config-section-title",children:t})}function ma(e){let{label:t,children:n,style:r,ref:i}=e;return(0,d.jsxs)("div",{ref:i,className:"config-field",style:r,children:[(0,d.jsx)("span",{className:"config-field-label",children:t}),n]})}function mo(e){let{children:t}=e;return(0,d.jsx)("div",{className:"config-detail-grid",children:t})}function mc(e){let{label:t,tone:n="muted",mono:r=!1,className:i,style:s,children:l}=e;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"config-detail-grid-label",children:t}),(0,d.jsx)("div",{className:["config-detail-grid-value","plain"===n?null:`is-${n}`,r?"is-mono":null,i].filter(Boolean).join(" "),style:s,children:l})]})}function md(e){let{scope:t,children:n}=e;return(0,d.jsx)("span",{className:`config-scope-tag${"project"===t?" is-project":""}`,children:n})}function mu(e){let{value:t,options:n,label:r,disabledReason:i,size:s="default",onChange:l,children:a}=e,o=(0,u.useId)(),c=i&&n.some(e=>e.disabled)?i:null;return(0,d.jsxs)("div",{className:"config-scope-switch-field",children:[(0,d.jsxs)("div",{className:"config-scope-switch-row",children:[(0,d.jsx)("div",{role:"group","aria-label":r,className:`config-scope-switch${"small"===s?" is-small":""}`,children:n.map(e=>(0,d.jsx)("button",{type:"button","aria-pressed":e.value===t,"aria-describedby":e.disabled&&c?o:void 0,disabled:e.disabled,className:"config-scope-switch-option",onClick:()=>{e.disabled||l(e.value)},children:e.label},e.value))}),a]}),c&&(0,d.jsx)("span",{id:o,className:"config-scope-switch-reason",children:c})]})}function mp(e){let{value:t,options:n,label:r,path:i,disabledReason:s,onChange:l,children:a}=e;return(0,d.jsxs)("div",{className:"config-save-target",children:[(0,d.jsx)(mu,{value:t,options:n,label:r,disabledReason:s,size:"small",onChange:l,children:(0,d.jsx)("span",{className:"config-save-target-path",children:"string"==typeof i?i.split(/([\\/])/).map((e,t)=>"/"===e||"\\"===e?(0,d.jsxs)(u.Fragment,{children:[e,(0,d.jsx)("wbr",{})]},t):e):i})}),a]})}function mh(e){let{title:t,catalogs:n,target:r}=e;return(0,d.jsxs)("div",{className:"config-add-source-heading",children:[(0,d.jsxs)("div",{className:"config-add-source-title-row",children:[(0,d.jsx)(ms,{children:t}),(0,d.jsx)("span",{className:"config-add-source-catalogs",children:n.map(e=>(0,d.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"config-add-source-catalog",children:[e.icon,e.label]},e.href))})]}),r]})}function mm(e){let{title:t,catalogs:n,target:r,inputLabel:i,inputId:s,placeholder:l,value:a,canSubmit:o,normalizeValue:c,onValueChange:p,onSubmit:h,examplesLabel:m,examples:f,error:g,multiline:x=!1,children:v}=e,b=(0,u.useRef)(null),y=(0,u.useRef)(null);(0,u.useEffect)(()=>{x?window.matchMedia?.("(pointer: coarse)").matches||y.current?.focus():b.current?.focus()},[x]);let w=e=>{if(!c)return;let t=e.clipboardData.getData("text"),n=c(t);n!==t&&(e.preventDefault(),p(n))};return(0,d.jsxs)(mt,{className:"is-fill",children:[(0,d.jsx)(mh,{title:t,catalogs:n,target:r}),(0,d.jsx)(ma,{label:i,children:x?(0,d.jsx)("textarea",{id:s,ref:y,value:a,"aria-label":i,className:"config-add-source-input is-multiline",placeholder:l,rows:5,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{c&&p(c(e.currentTarget.value))},onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&e.nativeEvent?.isComposing!==!0&&229!==e.keyCode&&(e.preventDefault(),o&&h())}}):(0,d.jsx)("input",{id:s,ref:b,value:a,"aria-label":i,className:"config-add-source-input",placeholder:l,onChange:e=>p(e.target.value),onPaste:w,onBlur:e=>{c&&p(c(e.currentTarget.value))},onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&"Enter"===e.key&&o&&h()}})}),v,f.length>0&&(0,d.jsxs)("div",{className:"config-add-source-examples",children:[(0,d.jsx)("div",{className:"config-add-source-examples-label",children:m}),(0,d.jsx)("div",{className:"config-add-source-example-list",children:f.map(e=>"string"==typeof e?(0,d.jsx)("button",{type:"button",className:"config-add-source-example",onClick:()=>p(e),children:e},e):(0,d.jsxs)("button",{type:"button",className:"config-add-source-example has-label",onClick:()=>p(e.value),children:[(0,d.jsx)("span",{className:"config-add-source-example-label",children:e.label}),(0,d.jsx)("span",{className:"config-add-source-example-value",children:e.value})]},e.value))})]}),g&&(0,d.jsx)("div",{role:"alert",className:"config-add-source-error",children:g})]})}function mf(e){let{id:t,action:n,children:r}=e;return(0,d.jsxs)("div",{id:t,role:"status",className:`config-notice${n?" has-action":""}`,children:[n?(0,d.jsx)("span",{className:"config-notice-text",children:r}):r,n]})}function mg(e){let{id:t,message:n,trustLabel:r,trusting:i=!1,onTrust:s}=e;return(0,d.jsx)(mf,{id:t,action:s&&r?(0,d.jsx)(mw,{size:"small",onClick:s,disabled:i,children:r}):void 0,children:n})}function mx(e){let{children:t}=e;return(0,d.jsx)("div",{className:"config-empty-state",children:t})}function mv(e){let{children:t,style:n,motionKey:r,resetScrollOnChange:i=!1}=e,s=(0,u.useRef)(null),l=(0,u.useRef)(r);return(0,u.useLayoutEffect)(()=>{i&&l.current!==r&&s.current&&(s.current.scrollTop=0),l.current=r},[r,i]),m(s,r??null,{desktopOnly:!0}),(0,d.jsx)("div",{ref:s,className:"config-detail",style:n,children:t})}function mb(e){let{status:t,children:n}=e;return(0,d.jsxs)("footer",{className:"config-footer",children:[(0,d.jsx)("div",{className:"config-footer-status",children:t}),(0,d.jsx)("div",{className:"config-footer-actions",children:n})]})}function my(e){let{summary:t,tone:n="default",details:r}=e,i=`config-footer-status-summary${"default"===n?"":` is-${n}`}`;return r?.length?(0,d.jsxs)("details",{className:"config-footer-status-details",children:[(0,d.jsx)("summary",{className:i,children:t}),(0,d.jsx)("ul",{className:"config-footer-status-list",children:r.map((e,t)=>(0,d.jsx)("li",{children:e},t))})]}):(0,d.jsx)("span",{className:i,children:t})}function mw(e){let{variant:t="secondary",size:n="default",className:r,children:i,...s}=e;return(0,d.jsx)("button",{type:"button",...s,className:["config-button",`config-button-${t}`,`config-button-${n}`,r].filter(Boolean).join(" "),children:i})}function mj(e){let{checked:t,disabled:n=!1,loading:r=!1,size:i="default",label:s,describedBy:l,onChange:a}=e,o=n||r;return(0,d.jsx)("button",{type:"button",role:"switch","aria-checked":t,"aria-busy":r||void 0,"aria-label":s,"aria-describedby":l,title:s,disabled:o,className:`config-switch${"small"===i?" is-small":""}${r?" is-loading":""}`,onClick:()=>a(!t),children:(0,d.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function mk(e){let{active:t=!1,children:n,className:r,onClick:i,ref:s,...l}=e,{openDetail:a}=h0(),o=h2(t,s);return(0,d.jsx)("div",{className:"config-list-action",children:(0,d.jsxs)("button",{type:"button",...l,ref:o,onClick:e=>{i?.(e),e.defaultPrevented||a()},"aria-current":t?"page":void 0,className:["config-list-action-button",r].filter(Boolean).join(" "),children:[(0,d.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,d.jsx)("path",{d:"M12 5v14M5 12h14"})}),n]})})}function mS(e){let{active:t,color:n}=e;return(0,d.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${t?" is-active":!1===t?" is-inactive":""}`,style:n?{backgroundColor:n}:void 0})}function mC(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 mN(e,t){let n=mC(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 mE(e,t){return t.enabled&&(e?.enabledTotal??0)<=1}function mM(e,t){return e?.providers.find(e=>e.id===t)}function m$(e){let{modelName:t,effective:n,value:r,onChange:i,disabled:s=!1,describedBy:l}=e,{t:a}=(0,ns.s)(),o=void 0!==r&&void 0===hI(r);return(0,d.jsx)("input",{type:"text",inputMode:"numeric",className:"model-context-input",value:void 0===r?"":String(r),placeholder:void 0===n?void 0:String(n),title:a("models.contextWindow"),"aria-label":a("models.contextForModel",{model:t}),"aria-invalid":o||void 0,"aria-describedby":l,disabled:s,onChange:e=>i(""===e.target.value.trim()?void 0:e.target.value)})}let mI={"last-model":"models.enabledLastModel","project-scope":"models.enabledProjectScope"};function mT(e){let{controller:t}=e,{t:n}=(0,ns.s)(),{view:r,pending:i}=t;if(!r)return null;let s=!r.allEnabled,l=r.stalePatterns.length;return s||0!==l?(0,d.jsxs)("div",{className:"enabled-models-banner",children:[(0,d.jsxs)("span",{className:"enabled-models-banner-text",...l>0?{title:n("models.enabledStaleHint")}:{},children:[(0,d.jsx)("code",{className:"enabled-models-banner-key",title:r.settingsPath,children:r.settingsPath}),(0,d.jsxs)("code",{className:"enabled-models-banner-facts",children:[`\xb7 enabledModels ${r.enabledTotal}/${r.availableTotal}`,l>0&&` \xb7 ${n("models.enabledStale",{count:l})}`]})]}),r.editable&&l>0&&(0,d.jsx)(mw,{size:"small",onClick:t.pruneStale,disabled:null!==i,title:n("models.enabledPruneHint"),children:n("models.enabledPrune")}),r.editable&&s&&(0,d.jsx)(mw,{size:"small",onClick:t.clearScope,disabled:null!==i,title:n("models.enabledClearHint"),children:n("models.enabledClear")})]}):null}function mR(e){let{providerId:t,controller:n,noteId:r}=e,{t:i}=(0,ns.s)(),{view:s,loading:l,pending:a,failure:o}=n,c=mM(s,t),u=o?o.messageKey?i(o.messageKey):o.message:null,p=mA(n,t)?r:void 0;if(l&&!s)return null;if(!c)return(0,d.jsx)(mj,{checked:!1,disabled:!0,label:i("models.enabledProviderToggle",{provider:t}),describedBy:p,onChange:()=>{}});let h=mN(s,c);return(0,d.jsxs)(d.Fragment,{children:[u&&(0,d.jsx)("span",{className:"enabled-models-switch-error",children:u}),(0,d.jsx)(mj,{checked:h.checked,loading:a===`provider:${c.id}`,disabled:null!==a||h.blocked,label:i("models.enabledProviderToggle",{provider:c.name}),describedBy:p,onChange:e=>n.setProvider(c.id,e)})]})}function mA(e,t){let{view:n,loading:r}=e;if(r&&!n)return null;let i=mM(n,t);if(!i)return"models.enabledCustomEmpty";let{reason:s}=mN(n,i);return s?mI[s]:null}function mL(e){let{providerId:t,controller:n,id:r}=e,{t:i}=(0,ns.s)(),s=mA(n,t);return s?(0,d.jsx)("div",{id:r,className:"config-detail-heading-note",children:i(s)}):null}function mP(e){var t;let n,{providerId:r,controller:i,contextSettings:s,emptyCatalogHint:l}=e,{t:a}=(0,ns.s)(),[o,c]=(0,u.useState)(""),{view:p,loading:h,pending:m,failure:f}=i,g=mM(p,r)??(l&&!f?{id:r,models:[],enabledCount:0}:void 0),x=function(e,t){let[n,r]=(0,u.useState)(!1),[i,s]=(0,u.useState)(null);return(0,u.useEffect)(()=>s(null),[e]),{refreshing:n,note:i,refresh:(0,u.useCallback)(()=>{r(!0),s(null),(async()=>{try{let n=await fetch("/api/models/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e})}),r=await nE(n);"offline"===r.reason?s("models.catalogOffline"):r.completed?s(r.changed?"models.catalogUpdated":"models.catalogUnchanged"):s("models.catalogUnreachable"),r.changed&&t()}catch{s("models.catalogUnreachable")}finally{r(!1)}})()},[e,t])}}(r,i.refresh),v=(0,u.useId)();if((0,u.useEffect)(()=>c(""),[r]),h&&!p)return(0,d.jsx)("div",{className:"enabled-models-empty",children:a("agents.modelsLoading")});if(!g)return f?.message?(0,d.jsx)("div",{className:"enabled-models-error",children:f.message}):(0,d.jsx)("div",{className:"enabled-models-empty",children:a("models.enabledUnavailable")});let b=(t=g.models,(n=o.trim().toLowerCase())?t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)):[...t]),y=mC(p,b),w=b.length!==g.models.length,j=null!==m,k=`provider:${g.id}`,S=p?.editable===!0,C=`${v}-scope`,N=`${v}-last`,E=`${v}-context`,M=S&&!y.canDisable&&y.disableRefs.length>0,$=M||S&&b.some(e=>mE(p,e)),I=(e,t)=>{w?i.setModels(k,t,e):i.setProvider(g.id,e)};return(0,d.jsxs)("div",{className:"enabled-models-section",children:[(0,d.jsxs)("div",{className:"enabled-models-header",children:[(0,d.jsx)("span",{className:"enabled-models-title",children:a("models.enabledSection")}),(0,d.jsx)("span",{className:"enabled-models-count",children:a("models.enabledCount",{enabled:g.enabledCount,total:g.models.length})}),(0,d.jsx)(mw,{size:"small",disabled:j||!y.canEnable,"aria-describedby":S?void 0:C,onClick:()=>I(!0,y.enableRefs),children:w?a("models.enableShown"):a("models.enableAll")}),(0,d.jsx)(mw,{size:"small",disabled:j||!y.canDisable,"aria-describedby":S?M?N:void 0:C,onClick:()=>I(!1,y.disableRefs),children:w?a("models.disableShown"):a("models.disableAll")}),(0,d.jsx)(mw,{size:"small",disabled:j||x.refreshing,title:a("models.refreshCatalogHint"),onClick:x.refresh,children:x.refreshing?a("models.refreshingCatalog"):a("models.refreshCatalog")})]}),x.note&&(0,d.jsx)("div",{className:"enabled-models-note",children:a(x.note)}),!S&&(0,d.jsx)("div",{id:C,className:"enabled-models-note",children:a("models.enabledProjectScope")}),$&&(0,d.jsx)("div",{id:N,className:"enabled-models-note",children:a("models.enabledLastModel")}),f&&(0,d.jsx)("div",{className:"enabled-models-error",children:f.messageKey?a(f.messageKey):f.message}),g.models.length>8&&(0,d.jsx)("input",{value:o,onChange:e=>c(e.target.value),placeholder:a("models.enabledFilterPlaceholder",{count:g.models.length}),"aria-label":a("models.enabledFilter"),className:"enabled-models-filter"}),s&&g.models.length>0&&(0,d.jsx)("div",{id:E,className:"enabled-models-note",children:a("models.contextOverrideHelp")}),(0,d.jsx)("div",{className:"enabled-models-list",children:0===b.length?(0,d.jsx)("div",{className:"enabled-models-empty",children:0===g.models.length&&l||a("models.enabledNoMatches")}):b.map(e=>{let t=mE(p,e),n=s?.overrides?.[e.id],r=n&&"object"==typeof n&&!Array.isArray(n)?n.contextWindow:void 0;return(0,d.jsxs)("div",{className:"enabled-models-row",children:[(0,d.jsxs)("span",{className:"enabled-models-row-text",children:[(0,d.jsx)("span",{className:"enabled-models-row-name",children:e.name}),(0,d.jsx)("code",{className:"enabled-models-row-id",children:e.id})]}),e.thinkingPin&&(0,d.jsx)("span",{className:"enabled-models-pin",title:a("models.enabledPinHint"),children:e.thinkingPin}),s&&(0,d.jsx)(m$,{modelName:e.name,effective:e.contextWindow,value:r,disabled:s.disabled,describedBy:E,onChange:t=>s.onChange(e.id,t)}),(0,d.jsx)(mj,{checked:e.enabled,loading:m===e.ref,disabled:j||!p?.editable||t,label:a("models.enabledToggle",{model:e.name}),describedBy:S?t?N:void 0:C,onChange:t=>i.setModels(e.ref,[e.ref],t)})]},e.ref)})})]})}function mz(e){let{message:t,hint:n,value:r,placeholder:i,submitLabel:s,inputLabel:l,disabled:a=!1,plainEnterSubmits:o=!0,inputRef:c,onValueChange:u,onSubmit:p}=e,h=!a&&r.trim().length>0;return(0,d.jsxs)("div",{className:"oauth-paste-panel",children:[(0,d.jsx)("p",{className:"oauth-paste-message",children:t}),n&&(0,d.jsx)("p",{className:"oauth-paste-hint",children:n}),(0,d.jsxs)("div",{className:"oauth-paste-row",children:[(0,d.jsx)("input",{ref:c,value:r,className:"oauth-paste-input",placeholder:i,"aria-label":l,disabled:a||void 0,onChange:e=>u(e.target.value),onKeyDown:e=>{var t;t={key:e.key,metaKey:e.metaKey,ctrlKey:e.ctrlKey,isComposing:e.nativeEvent.isComposing,keyCode:e.keyCode},"Enter"===t.key&&!t.isComposing&&229!==t.keyCode&&(o||t.metaKey||t.ctrlKey)&&h&&p()}}),(0,d.jsx)("button",{type:"button",className:"oauth-paste-submit",onClick:p,disabled:!h,children:s})]})]})}let mO={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 mW(e){let{id:t,size:n}=e,r=mO[t];if(r)return(0,d.jsx)("svg",{"aria-hidden":"true",width:n,height:n,viewBox:"0 0 24 24",fill:r.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,d.jsx)("use",{href:`/provider-icons.svg#${r.symbol}`})});let i=t.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,d.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:i})}let mF=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go","kimi-coding"],mD="pi-web:provider-usage:";function m_(e){let{providerId:t,enabled:n}=e;return mF.includes(t)?(0,d.jsx)(mB,{providerId:t,enabled:n}):null}function mB(e){let{providerId:t,enabled:n}=e,[r,i]=(0,u.useState)(null),[s,l]=(0,u.useState)(!1),[a,o]=(0,u.useState)(null),[c,p]=(0,u.useState)(!1),h=(0,u.useRef)(null),{locale:m,t:f}=(0,ns.s)();(0,u.useEffect)(()=>{h.current&&clearTimeout(h.current),p(!1),i(null);try{let e=localStorage.getItem(`${mD}${t}`);if(e){let t=JSON.parse(e);t?.status==="ready"&&t.report&&Array.isArray(t.report.buckets)&&Array.isArray(t.report.metrics)&&i(t)}}catch{try{localStorage.removeItem(`${mD}${t}`)}catch{}}return o(null),()=>{h.current&&clearTimeout(h.current)}},[t]);let g=(0,u.useCallback)(async()=>{l(!0),o(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){i(n);try{localStorage.setItem(`${mD}${t}`,JSON.stringify(n))}catch{}p(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(!1),2e3)}else o(n.message??f("providerUsage.queryFailed"))}catch(e){o(e instanceof Error?e.message:f("providerUsage.queryFailed"))}finally{l(!1)}},[t,f]),x=r?.status==="ready"?r.report:void 0;return(0,d.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,d.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:f("providerUsage.usage")}),(0,d.jsx)("button",{type:"button",onClick:g,disabled:!n||s,title:f(s?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":f(s?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:c?"#4ade80":"var(--text-dim)",cursor:n&&!s?"pointer":"default",borderRadius:5,flexShrink:0,opacity:n?1:.6,transition:"color 0.3s"},children:c?(0,d.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,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:s?{animation:"spin 0.8s linear infinite"}:void 0,"aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"})]})}),x&&(0,d.jsx)("span",{title:new Date(x.capturedAt).toLocaleString(m),style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:f("providerUsage.updated",{time:(0,ii.ob)(x.capturedAt,m)})})]}),!x&&!a&&(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:f("providerUsage.notQueried")}),a&&(0,d.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:a}),x&&(0,d.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,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.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,d.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 ":"$"}${mH(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${mH(e.remaining)} / ${mH(e.limit)}`:e.period??t}(e,f("providerUsage.available"))})]},e.id)),x.metrics.map(e=>{var t;return(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,d.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 mH(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function mU(){let e=hC("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 mK(e){return 1===Object.keys(e).length&&Object.keys(e.modelOverrides??{}).length>0}let mq=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],mV={empty:"models.providerIncomplete",baseUrl:"models.providerNeedsBaseUrl"};function mZ(e){let{label:t,children:n}=e;return(0,d.jsx)(ma,{label:t,children:n})}let mJ={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 mY(e){let{value:t,onChange:n,placeholder:r,mono:i,inputMode:s}=e;return(0,d.jsx)("input",{value:t,onChange:e=>n(e.target.value),placeholder:r,inputMode:s,style:{...mJ,fontFamily:i?"var(--font-mono)":"inherit"}})}function mG(e){let{value:t,onChange:n,placeholder:r,mono:i,onKeyDown:s,autoComplete:l="off",spellCheck:a=!1,enterKeyHint:o,style:c}=e,[p,h]=(0,u.useState)(!1),{t:m}=(0,ns.s)();return(0,u.useEffect)(()=>{t||h(!1)},[t]),(0,d.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,d.jsx)("input",{type:p?"text":"password",value:t,onChange:e=>n(e.target.value),onKeyDown:s,placeholder:r,style:{...mJ,paddingRight:34,fontFamily:i?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:a,enterKeyHint:o}),(0,d.jsx)("button",{type:"button",onClick:()=>h(e=>!e),"aria-label":m(p?"i18n.hideDetails":"i18n.showDetails"),title:m(p?"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:p?(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.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,d.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,d.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,d.jsx)("path",{d:"M1 1l22 22"})]}):(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function mX(e){let{value:t,onChange:n,placeholder:r,invalid:i}=e;return(0,d.jsx)("input",{type:"number",value:t,onChange:e=>n(e.target.value),placeholder:r,"aria-invalid":i||void 0,style:i?{...mJ,borderColor:"#ef4444"}:mJ})}function mQ(e){let{value:t,onChange:n,options:r,required:i}=e,{t:s}=(0,ns.s)();return(0,d.jsxs)("select",{value:t,onChange:e=>n(e.target.value),style:{...mJ,color:t?"var(--text)":"var(--text-dim)"},children:[!i&&(0,d.jsxs)("option",{value:"",children:["— ",s("i18n.default")," / none —"]}),r.map(e=>(0,d.jsx)("option",{value:e,children:e},e))]})}function m0(e){let{label:t,checked:n,onChange:r}=e;return(0,d.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,d.jsx)("input",{type:"checkbox",checked:n,onChange:e=>r(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),t]})}function m1(e){let{children:t}=e;return(0,d.jsx)(ml,{children:t})}function m2(e){let{name:t,editingName:n,fallbackLabel:r,provider:i,onChange:s,onEditingNameChange:l,onRename:a,onDelete:o,onAddModels:c,enabledModels:p}=e,{t:h}=(0,ns.s)(),[m,f]=(0,u.useState)({phase:"idle"}),[g,x]=(0,u.useState)(""),[v,b]=(0,u.useState)([]),y=(0,u.useRef)(0),w=(0,u.useRef)(null),j=(0,u.useId)(),k=(e,t)=>s({...i,[e]:t});(0,u.useEffect)(()=>{y.current+=1,f({phase:"idle"}),x(""),b([])},[t,i.baseUrl,i.api,i.apiKey]);let S=(0,u.useCallback)(async()=>{if("loading"===m.phase)return;let e=++y.current;f({phase:"loading"}),b([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:{...i,models:void 0}})}),r=await n.json();if(e!==y.current)return;if(!n.ok||r.error||!r.models)return void f({phase:"error",message:r.error??`HTTP ${n.status}`});f({phase:"success",models:r.models,endpoint:r.endpoint??i.baseUrl??""})}catch(t){if(e!==y.current)return;f({phase:"error",message:t instanceof Error?t.message:String(t)})}},[m.phase,t,i]),C=new Set((i.models??[]).map(e=>e.id)),N="success"===m.phase?m.models:[],E=g.trim().toLocaleLowerCase(),M=N.filter(e=>!E||e.id.toLocaleLowerCase().includes(E)||e.name?.toLocaleLowerCase().includes(E)),$=M.slice(0,300),I=$.filter(e=>!C.has(e.id)).map(e=>e.id),T=v.filter(e=>!C.has(e)).length,R=I.length>0&&I.every(e=>v.includes(e)),A=!R&&I.some(e=>v.includes(e));return(0,u.useEffect)(()=>{w.current&&(w.current.indeterminate=A)},[A]),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)("div",{className:"config-detail-heading",children:[(0,d.jsxs)(mn,{children:[(0,d.jsx)(mr,{children:(0,d.jsx)(m1,{children:h("i18n.provider")})}),(0,d.jsxs)(mi,{children:[(0,d.jsx)(mR,{providerId:t,controller:p,noteId:j}),(0,d.jsx)(mw,{variant:"danger",size:"small",onClick:o,children:h("i18n.delete")})]})]}),(0,d.jsx)(mL,{providerId:t,controller:p,id:j})]}),(0,d.jsxs)(mZ,{label:h("i18n.providerId"),children:[(0,d.jsx)(mY,{value:n,onChange:l,placeholder:"provider-id",mono:!0}),n!==t&&n.trim()&&(0,d.jsx)("button",{onClick:()=>a(n.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:h("i18n.rename")})]}),(0,d.jsx)(mZ,{label:h("models.providerDisplayName"),children:(0,d.jsx)(mY,{value:i.name??"",onChange:e=>s(function(e,t){if(!t.trim()){let t={...e};return delete t.name,t}return"name"in e?{...e,name:t}:{name:t,...e}}(i,e)),placeholder:r})}),(0,d.jsx)(mZ,{label:"Base URL",children:(0,d.jsx)(mY,{value:i.baseUrl??"",onChange:e=>k("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",inputMode:"url",mono:!0})}),(0,d.jsx)(mZ,{label:"API Key",children:(0,d.jsx)(mG,{value:i.apiKey??"",onChange:e=>k("apiKey",e||void 0),placeholder:h("models.apiKeyPlaceholder"),mono:!0})}),(0,d.jsx)(mZ,{label:"API",children:(0,d.jsx)(mQ,{value:i.api??"",onChange:e=>k("api",e||void 0),options:mq})}),(0,d.jsx)(mZ,{label:"Headers",children:(0,d.jsx)(m7,{headers:i.headers,onChange:e=>k("headers",e)})}),(0,d.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==m.phase&&(0,d.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,d.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,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("input",{value:g,onChange:e=>x(e.target.value),placeholder:h("models.discoveryFilterPlaceholder",{count:m.models.length}),"aria-label":h("models.discoveryFilter"),style:{...mJ,width:"100%",minWidth:0}}),(0,d.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,d.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,d.jsx)("input",{ref:w,type:"checkbox",checked:R,disabled:0===I.length,onChange:()=>{let e=new Set(I);b(t=>R?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),h("models.discoverySelectShown")]}),0===$.length?(0,d.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:h("models.discoveryNoMatches")}):$.map((e,t)=>{let n=C.has(e.id),r=v.includes(e.id);return(0,d.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,d.jsx)("input",{type:"checkbox",checked:r||n,disabled:n,onChange:()=>{var t;return t=e.id,void b(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,d.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,d.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,d.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,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:h("models.discoveryAdded")})]},e.id)})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,d.jsx)("span",{title:m.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:M.length>$.length?h("models.discoveryShowing",{shown:$.length,total:M.length}):h("models.discoveryFetched",{count:m.models.length})}),(0,d.jsx)("button",{onClick:()=>{if("success"!==m.phase)return;let e=new Set(v),t=m.models.filter(t=>e.has(t.id)&&!C.has(t.id));0!==t.length&&(c(t),b([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?h("models.discoveryAddSelectedCount",{count:T}):h("models.discoveryAddSelected")})]})]})]})]})}let m4=["off","minimal","low","medium","high","xhigh","max"],m3={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function m8(e){let{value:t,onChange:n}=e,{t:r}=(0,ns.s)(),i=t??{},s=(e,t)=>{let r={...i};"omit"===t?delete r[e]:r[e]=t,n(Object.keys(r).length?r:void 0)};return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[(0,d.jsx)("p",{style:{margin:"0 0 8px",fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:r("models.thinkingLevelMapHelp")}),m4.map(e=>{let t=i[e],n=e in i?null===t?"null":"string":"omit",l="string"==typeof t?t:"",a=m3[e],o={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,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:a,flexShrink:0,opacity:"null"===n?.3:1}}),(0,d.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,d.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,d.jsx)("button",{onClick:()=>s(e,"omit"),style:{...o,..."omit"===n?c:{}},children:r("xhigh"===e||"max"===e?"models.thinkingDefaultUnavailable":"i18n.default")}),(0,d.jsx)("button",{onClick:()=>s(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===n?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:r("i18n.disabled")})]}),(0,d.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,d.jsx)("button",{onClick:()=>s(e,l||e),style:{...o,..."string"===n?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:r("i18n.custom")}),(0,d.jsx)("input",{value:l,onChange:t=>s(e,t.target.value),onFocus:()=>{"string"!==n&&s(e,l||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 m6={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function m5(e){return e.compat?.thinkingFormat==="deepseek"}function m9(e,t){return{...e.compat??{},...t.compat??{}}}function m7(e){let{headers:t,onChange:n}=e,{t:r}=(0,ns.s)(),[i,s]=(0,u.useState)(()=>Object.entries(t??{}).map((e,t)=>{let[n,r]=e;return{id:t,name:n,value:r}})),l=(0,u.useRef)(i.length),a=e=>{s(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))},o=(e,t)=>{a(i.map(n=>n.id===e?{...n,...t}:n))},c={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,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.map(e=>(0,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)("input",{value:e.name,onChange:t=>o(e.id,{name:t.target.value}),"aria-label":r("models.headerName"),placeholder:"Header-Name",style:{...mJ,fontFamily:"var(--font-mono)",flex:1}}),(0,d.jsx)("input",{value:e.value,onChange:t=>o(e.id,{value:t.target.value}),"aria-label":r("models.headerValue"),placeholder:"value",style:{...mJ,fontFamily:"var(--font-mono)",flex:1}}),(0,d.jsx)("button",{"aria-label":r("models.removeHeader"),onClick:()=>{var t;return t=e.id,void a(i.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,d.jsxs)("button",{onClick:()=>s(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:["+ ",r("models.addHeader")]})]})}function fe(e){let{providerName:t,provider:n,model:r,onChange:i,onDelete:s}=e,[l,a]=(0,u.useState)({phase:"idle"}),{t:o}=(0,ns.s)(),[c,p]=(0,u.useState)({phase:"idle"}),[h,m]=(0,u.useState)(!1),[f,g]=(0,u.useState)(()=>h_(r.cost)),x=(0,u.useRef)(f),[v,b]=(0,u.useState)(!1),y=(0,u.useRef)(0),w=r.baseUrl??n.baseUrl,j=(0,u.useRef)(0),k=(0,u.useRef)(null),S=(0,u.useRef)(r.cost),C=(e,t)=>i({...r,[e]:t}),N=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return o("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?[o("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[o("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,u.useEffect)(()=>(y.current+=1,a({phase:"idle"}),()=>{y.current+=1}),[t,n,r]),(0,u.useEffect)(()=>{j.current+=1,p({phase:"idle"}),k.current=null},[t,w,r.id]);let E=(0,u.useCallback)(async()=>{if(!r.id.trim()||"testing"===l.phase)return;let e=++y.current;a({phase:"testing"});try{let i=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:t,provider:n,model:r})}),s=await i.json();if(e!==y.current)return;if(!i.ok||!s.ok)return void a({phase:"error",message:s.error??`HTTP ${i.status}`,latencyMs:s.latencyMs,status:s.status});a({phase:"success",latencyMs:s.latencyMs,status:s.status,responseText:s.responseText})}catch(t){if(e!==y.current)return;a({phase:"error",message:t instanceof Error?t.message:String(t)})}},[r,n,t,l.phase]),M=(0,u.useCallback)(async()=>{let e=r.id.trim();if(!e||"loading"===c.phase)return;let n=++j.current;p({phase:"loading"});try{let s=new URLSearchParams({q:e,provider:t,limit:"50"});w?.trim()&&s.set("baseUrl",w.trim());let l=await fetch(`/api/models-config/catalog?${s}`),a=await l.json();if(n!==j.current)return;if(!l.ok||a.error||!a.recommendation)return void p({phase:"error",message:a.error??`HTTP ${l.status}`});let o=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let l=hB(h_(i));s>0&&l&&(n.cost={...i,...l},r+=s)}return{model:n,appliedCount:r}}(r,a.recommendation.preset);o.appliedCount>0&&(k.current=r,i(o.model)),m(!1),p({phase:"success",recommendation:a.recommendation,appliedCount:o.appliedCount})}catch(e){if(n!==j.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,r,i,w,t]),$=(()=>{if("success"!==c.phase)return null;let{recommendation:e,appliedCount:n}=c,r=n>0?o("models.catalogFilled",{count:n}):o("models.catalogNoEmptyFields");if("unreliable"===e.price.status){let t="no-exact-match"===e.price.reason?o("models.catalogNoExactMatch"):o("models.catalogPriceUnreliable");return`${r} \xb7 ${t}`}let i="provider"===e.price.method?o("models.catalogPriceProvider",{provider:e.price.providerName??e.price.providerId??t}):"base-url"===e.price.method?o("models.catalogPriceBaseUrl",{provider:e.price.providerName??e.price.providerId??t}):o("models.catalogPriceConsensus",{support:e.price.support,total:e.price.total});return`${r} \xb7 ${i}`})(),I="error"===c.phase?c.message:$,T="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:o("models.costInput")},{key:"output",label:o("models.costOutput")},{key:"cacheRead",label:o("models.costCacheRead")},{key:"cacheWrite",label:o("models.costCacheWrite")}],A=new Set(Object.keys(r.compat??{})),L=0;m5(r)&&(L+=1,A.delete("thinkingFormat"),A.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(r.compat??{},"supportsDeveloperRole")&&(L+=1,A.delete("supportsDeveloperRole")),L+=A.size;let P=hz(r),z=hO(P),O=[r.baseUrl?o("models.baseUrlOverride"):null,r.api?`API: ${r.api}`:null,Object.keys(r.headers??{}).length?o("models.headersSummary",{count:Object.keys(r.headers??{}).length}):null,L?o("models.compatSummary",{count:L}):null,Object.keys(r.thinkingLevelMap??{}).length?o("models.thinkingSummary",{count:Object.keys(r.thinkingLevelMap??{}).length}):null,void 0!==z?o("models.imageMaxBytesSummary",{size:hW(z)}):null].filter(e=>!!e),W=O.length?O.join(" \xb7 "):o("models.providerDefaults");return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)(mn,{children:[(0,d.jsx)(mr,{children:(0,d.jsx)(m1,{children:o("i18n.model")})}),(0,d.jsxs)(mi,{children:[N&&(0,d.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,d.jsxs)(mw,{size:"small",variant:"success"===l.phase?"primary":"secondary",onClick:"success"===l.phase?()=>a({phase:"idle"}):E,disabled:!r.id.trim()||"testing"===l.phase,title:o("i18n.testConnection"),className:"success"===l.phase?"is-success":void 0,children:["success"===l.phase&&(0,d.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?o("i18n.checking"):"success"===l.phase?o("common.ok"):o("i18n.test")]}),(0,d.jsx)(mw,{variant:"danger",size:"small",onClick:s,children:o("i18n.remove")})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,d.jsx)(mZ,{label:"ID *",children:(0,d.jsx)(mY,{value:r.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0})}),(0,d.jsx)(mZ,{label:"Name",children:(0,d.jsx)(mY,{value:r.name??"",onChange:e=>C("name",e||void 0),placeholder:o("models.displayNamePlaceholder")})})]}),(0,d.jsxs)("div",{style:{padding:"2px 0"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,d.jsx)("button",{onClick:()=>void M(),disabled:!r.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:r.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?o("models.catalogFilling"):o("models.catalogFill")}),(0,d.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:o("models.catalogSource")})]}),I&&(0,d.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:T,fontSize:10},children:[(0,d.jsx)("span",{title:I,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:I}),k.current&&(0,d.jsx)("button",{onClick:()=>{let e=k.current;e&&(k.current=null,i(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:o("models.catalogUndo")})]})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)(m1,{children:o("models.capabilities")}),(0,d.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,d.jsx)(m0,{label:o("models.reasoning"),checked:r.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,d.jsx)(m0,{label:o("models.imageInput"),checked:r.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,d.jsxs)("section",{children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,d.jsx)(m1,{children:o("models.modelSpecs")}),(0,d.jsx)("button",{type:"button",onClick:()=>{if(h)return void m(!1);S.current=r.cost;let e=h_(r.cost);x.current=e,g(e),m(!0)},"aria-expanded":h,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:h?o("models.finishEditingCosts"):o("models.editCosts")})]}),(0,d.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,d.jsx)(mZ,{label:o("models.contextWindow"),children:(0,d.jsx)(mX,{value:void 0!==r.contextWindow?String(r.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,d.jsx)(mZ,{label:o("models.maxOutputTokens"),children:(0,d.jsx)(mX,{value:void 0!==r.maxTokens?String(r.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,d.jsxs)("div",{style:{marginTop:16},children:[(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:o("models.costPerMillion")}),h?(0,d.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,d.jsx)(mZ,{label:n,children:(0,d.jsx)(mX,{value:f[t],onChange:e=>{let n,s,l;return s=hB(n={...x.current,[t]:e}),l={...r},void(x.current=n,g(n),s?(l.cost={...S.current??{},...s},S.current=l.cost):delete l.cost,i(l))},placeholder:"0"})},t)}),hH(f)&&!hB(f)&&(0,d.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:o("models.costAllRequired")})]}):(0,d.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,s=r.cost?.[n]===void 0;return(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:i}),(0,d.jsx)("div",{style:{marginTop:3,color:s?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(t=r.cost?.[n])?o("models.notProvided"):`$${String(t)}`})]},n)})})]})]}),(0,d.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,d.jsxs)("button",{type:"button",onClick:()=>b(e=>!e),"aria-expanded":v,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,d.jsxs)("span",{style:{minWidth:0},children:[(0,d.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:o("models.advancedSettings")}),(0,d.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:W})]}),(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:v?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,d.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),v&&(0,d.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,d.jsx)(mZ,{label:o("models.baseUrlOverride"),children:(0,d.jsx)(mY,{value:r.baseUrl??"",onChange:e=>C("baseUrl",e.trim()||void 0),placeholder:n.baseUrl??o("models.providerDefaults"),inputMode:"url",mono:!0})}),(0,d.jsx)(mZ,{label:o("models.apiOverride"),children:(0,d.jsx)(mQ,{value:r.api??"",onChange:e=>C("api",e||void 0),options:mq})}),(0,d.jsxs)(mZ,{label:o("models.headers"),children:[(0,d.jsx)(m7,{headers:r.headers,onChange:e=>C("headers",e)}),(0,d.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:o("models.headersHelp")})]}),(r.input?.includes("image")||void 0!==P)&&(0,d.jsxs)(mZ,{label:o("models.imageMaxBytes"),children:[(0,d.jsx)(mX,{value:void 0===P?"":String(P),onChange:e=>{var t;let n,s,l,a;return i((t=e.trim()||void 0,n={...hP(r.inputLimits)?r.inputLimits:{}},s={...hP(n.images)?n.images:{}},l={...hP(s.resize)?s.resize:{}},void 0===t?delete l.maxBytes:l.maxBytes=hO(t)??t,Object.keys(l).length?s.resize=l:delete s.resize,Object.keys(s).length?n.images=s:delete n.images,a={...r},Object.keys(n).length?a.inputLimits=n:delete a.inputLimits,a))},placeholder:String(4718592),invalid:void 0===z&&void 0!==P}),(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[void 0!==z&&`${hW(z)} \xb7 `,o("models.imageMaxBytesHelp",{size:hW(4718592)})]}),(0,d.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"inputLimits.images.resize.maxBytes"})]}),r.reasoning&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,d.jsx)(m1,{children:o("models.compatibility")}),(0,d.jsx)(m0,{label:o("models.deepSeekThinkingCompat"),checked:m5(r),onChange:e=>i(function(e,t){if(t)return{...e,compat:{...e.compat??{},...m6}};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}}(r,e))}),(0,d.jsx)(m0,{label:o("models.developerRole"),checked:!1!==m9(n,r).supportsDeveloperRole,onChange:e=>i(hU(r,"supportsDeveloperRole",e))}),(r.api??n.api)==="anthropic-messages"&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[(0,d.jsx)(m0,{label:o("models.adaptiveThinking"),checked:!0===m9(n,r).forceAdaptiveThinking,onChange:e=>i(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(n!==r)return hU(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}}(r,"forceAdaptiveThinking",e,n.compat?.forceAdaptiveThinking===!0))}),(0,d.jsx)("code",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",paddingLeft:19},children:"compat.forceAdaptiveThinking"})]}),(0,d.jsxs)("div",{style:{marginTop:4},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,d.jsx)(m1,{children:o("models.thinkingLevelMap")}),r.thinkingLevelMap&&(0,d.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:o("models.clearAll")})]}),(0,d.jsx)(m8,{value:r.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function ft(e){let{provider:t,onRefresh:n,enabledModels:r,contextSettings:i}=e,[s,l]=(0,u.useState)({phase:"idle"}),{t:a}=(0,ns.s)(),[o,c]=(0,u.useState)(""),p=(0,u.useRef)(null),h=(0,u.useRef)(null);(0,u.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,u.useEffect)(()=>{l({phase:"idle"}),c(""),p.current?.close(),p.current=null},[t.id]),(0,u.useEffect)(()=>()=>{p.current?.close()},[]);let m=(0,u.useCallback)(()=>{p.current?.close(),l({phase:"connecting"}),c("");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:a("models.connectionLost")})}},[t.id,n,a]),f=(0,u.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(t.id)}`,{method:"POST"}),l({phase:"idle"}),n()},[t.id,n]),g=(0,u.useCallback)(async(e,n)=>{if(n.trim()){l({phase:"progress",message:a("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??a("models.serverError",{status:r.status})});return}c("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:a("i18n.networkError")})}}},[t.id,a]),x=(0,u.useCallback)(async(e,n)=>{l({phase:"progress",message:a("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??a("models.serverError",{status:r.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:a("i18n.networkError")})}},[t.id,a]),v="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:t.loggedIn&&"idle"===s.phase?0:16},children:[(0,d.jsxs)(mn,{children:[(0,d.jsx)(mr,{children:(0,d.jsx)(m1,{children:a("i18n.subscription")})}),(0,d.jsxs)(mi,{children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,d.jsx)("span",{style:{fontSize:11,color:t.loggedIn?"#4ade80":"var(--text-dim)"},children:t.loggedIn?a("i18n.connected"):a("i18n.notConnected")})]}),v?(0,d.jsx)(mw,{size:"small",onClick:()=>{p.current?.close(),l({phase:"idle"})},children:a("i18n.cancel")}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(mw,{variant:"primary",size:"small",onClick:m,children:t.loggedIn?a("i18n.relogin"):a("i18n.login")}),t.loggedIn&&(0,d.jsx)(mw,{variant:"danger",size:"small",onClick:f,children:a("i18n.disconnect")})]})]})]}),(0,d.jsxs)("div",{style:{minHeight:t.loggedIn&&"idle"===s.phase?0:48},children:["idle"===s.phase&&!t.loggedIn&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a("models.oauthConnect",{provider:t.name})}),"connecting"===s.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a("i18n.openingBrowser")}),"select"===s.phase&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,d.jsx)("button",{onClick:()=>x(s.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"===s.phase||"prompt"===s.phase)&&(0,d.jsx)(mz,{message:"auth"===s.phase?a("models.oauthPasteRedirect"):s.message,hint:"auth"===s.phase?(0,d.jsxs)(d.Fragment,{children:[a("models.oauthNoBrowser")," ",(0,d.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",children:a("models.oauthOpenLoginPage")}),a("models.oauthOpenLoginPageEnd")]}):void 0,value:o,placeholder:"auth"===s.phase?"http://localhost:1455/auth/callback?code=…":s.placeholder??a("models.oauthValuePlaceholder"),submitLabel:a("i18n.submit"),inputRef:h,onValueChange:c,onSubmit:()=>void g(s.token,o)}),"device_code"===s.phase&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a("models.oauthDeviceCode")}),(0,d.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:s.userCode}),(0,d.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,d.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` ${a("models.deviceCodeExpires",{minutes:Math.ceil(s.expiresInSeconds/60)})}`:""]})]}),"progress"===s.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:a("i18n.connectedSuccessfully")}),"error"===s.phase&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,d.jsx)(m_,{providerId:t.id,enabled:t.loggedIn}),t.loggedIn&&(0,d.jsx)(mP,{providerId:t.id,controller:r,contextSettings:i})]})}let fn="http://127.0.0.1:8080";function fr(e){let{provider:t,onRefresh:n,enabledModels:r,contextSettings:i}=e,s=t.id===hE,[l,a]=(0,u.useState)(s&&!t.configured?fn:""),[o,c]=(0,u.useState)(""),[p,h]=(0,u.useState)(!1),[m,f]=(0,u.useState)(!1),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(!1),{t:y}=(0,ns.s)(),w=!!(s?l.trim():o.trim());async function j(){if(w&&!p){h(!0),x(null),b(!1);try{let e=await fetch(`/api/auth/api-key/${encodeURIComponent(t.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o.trim(),...s?{serverUrl:l.trim()}:{}})}),i=await e.json();!e.ok||i.error?x(i.error??`HTTP ${e.status}`):(c(""),s&&(a(""),r.refresh(),i.catalog?.completed||x(y(i.catalog?.reason==="offline"?"models.catalogOffline":"models.catalogUnreachable"))),b(!0),setTimeout(()=>b(!1),2e3),n())}catch(e){x(String(e))}finally{h(!1)}}}let k=(0,u.useCallback)(async()=>{f(!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{f(!1)}},[t.id,n]);return(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,d.jsxs)(mn,{children:[(0,d.jsx)(mr,{children:(0,d.jsx)(m1,{children:s?t.displayName:"API Key"})}),(0,d.jsxs)(mi,{children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,d.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:t.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,d.jsx)("span",{style:{fontSize:11,color:t.configured?"#4ade80":"var(--text-dim)"},children:t.configured?y("i18n.configured"):y("i18n.notConfigured")})]}),t.configured&&(0,d.jsx)(mw,{variant:"danger",size:"small",onClick:k,disabled:m,children:m?y("i18n.removing"):y("i18n.disconnect")})]})]}),s&&(0,d.jsxs)("label",{style:{display:"grid",gap:6},children:[y("models.llamaRouterUrl"),(0,d.jsx)("input",{type:"url",style:mJ,value:l,placeholder:fn,onChange:e=>a(e.target.value),spellCheck:!1})]}),!s&&!t.configured&&(0,d.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,d.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,d.jsx)(mG,{value:o,onChange:c,onKeyDown:e=>{e.nativeEvent.isComposing||229===e.keyCode||"Enter"===e.key&&j()},enterKeyHint:"done",placeholder:s?y("models.optionalApiKey"):t.configured?y("models.replaceApiKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,d.jsxs)("button",{onClick:j,disabled:p||!w||v,style:{padding:"6px 12px",background:v?"#16a34a":w?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:v?"#fff":w?"var(--accent-contrast)":"var(--text-dim)",cursor:p||!w||v?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[v&&(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),v?y("i18n.saved"):p?y("i18n.saving"):y("i18n.save")]})]}),g&&(0,d.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:g}),(0,d.jsx)(m_,{providerId:t.id,enabled:t.configured}),t.configured&&(0,d.jsx)(mP,{providerId:t.id,controller:r,contextSettings:i,emptyCatalogHint:s?y("models.llamaEmptyCatalog"):void 0})]})}function fi(e){let{oauthProviders:t,apiKeyProviders:n,onSelectOAuth:r,onSelectApiKey:i,onAddCustom:s,onClose:l}=e,[a,o]=(0,u.useState)(""),{t:c}=(0,ns.s)(),p=(0,u.useRef)(null);(0,u.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let h=a.trim().toLowerCase(),m=t.filter(e=>!e.loggedIn&&hJ(h,e.id,e.name)),f=n.filter(e=>!e.configured&&hJ(h,e.id,e.displayName)),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=m.length+f.length+ +!!g,v={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,d.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,d.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":c("i18n.addProvider"),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,d.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,d.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,d.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,d.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,d.jsx)("input",{ref:p,value:a,onChange:e=>o(e.target.value),placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,d.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),g&&(0,d.jsxs)("button",{onClick:()=>{s(),l()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,d.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,d.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,d.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,d.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),m.length>0&&(0,d.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),m.map(e=>(0,d.jsxs)("button",{onClick:()=>{r(e.id),l()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,d.jsx)(mW,{id:e.id,size:28})]},e.id)),f.length>0&&(0,d.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"}),f.map(e=>(0,d.jsxs)("button",{onClick:()=>{i(e.id),l()},style:v,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,d.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:e.id===hE?c("models.optionalApiKey"):c(1===e.modelCount?"models.modelCountOne":"models.modelCount",{count:e.modelCount})})]}),(0,d.jsx)(mW,{id:e.id,size:28})]},e.id))]})})]})})}function fs(e){let{cwd:t,revision:n,scope:r,onConfigure:i}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)([]),[o,c]=(0,u.useState)(""),[p,h]=(0,u.useState)(""),[m,f]=(0,u.useState)(!1),[g,x]=(0,u.useState)(!1),[v,b]=(0,u.useState)(0),[y,w]=(0,u.useState)(""),[j,k]=(0,u.useState)("");async function S(){let e=l.find(e=>JSON.stringify([e.provider,e.id])===o);if(e){f(!0),k(""),w("");try{let n=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},provider:e.provider,modelId:e.id})}),r=await n.json();if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);w(s("models.defaultSaved"))}catch(e){k(e instanceof Error?e.message:String(e))}finally{f(!1)}}}async function C(){if(p){f(!0),k(""),w("");try{let e=await fetch("/api/models/default",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t?{cwd:t}:{},thinkingLevel:p})}),n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);w(s("models.thinkingDefaultSaved"))}catch(e){k(e instanceof Error?e.message:String(e))}finally{f(!1)}}}return(0,u.useEffect)(()=>{let e=new AbortController;x(!1);let n=t?`?cwd=${encodeURIComponent(t)}`:"";return fetch(`/api/models${n}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);let n=t.defaultModel?JSON.stringify([t.defaultModel.provider,t.defaultModel.modelId]):"",r=t.modelList??[];a(r),c(e=>r.some(t=>JSON.stringify([t.provider,t.id])===e)?e:n),h(e=>e||t.savedDefaultThinkingLevel||""),k("")}).catch(t=>{e.signal.aborted||k(t instanceof Error?t.message:String(t))}).finally(()=>{e.signal.aborted||x(!0)}),()=>e.abort()},[t,n,r,v]),(0,d.jsxs)("details",{className:"model-defaults",children:[(0,d.jsxs)("summary",{className:"model-defaults-toggle",children:[(0,d.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M4 7h16M4 17h16"}),(0,d.jsx)("circle",{cx:"9",cy:"7",r:"3",fill:"var(--bg-panel)"}),(0,d.jsx)("circle",{cx:"15",cy:"17",r:"3",fill:"var(--bg-panel)"})]}),(0,d.jsx)("span",{children:s("models.newChatDefaults")}),(0,d.jsx)("svg",{className:"model-defaults-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m9 5 7 7-7 7"})})]}),(0,d.jsxs)("div",{className:"model-defaults-body",children:[(0,d.jsxs)("div",{className:"model-defaults-fields",children:[(0,d.jsxs)("div",{className:"model-defaults-field",children:[(0,d.jsx)("label",{htmlFor:"settings-default-model",children:s("models.defaultForNewChats")}),(0,d.jsxs)("div",{className:"model-defaults-control",children:[(0,d.jsxs)("select",{id:"settings-default-model",value:o,disabled:m||0===l.length,onChange:e=>{c(e.target.value),w("")},children:[!o&&(0,d.jsx)("option",{value:"",children:s("models.defaultSelect")}),l.map(e=>(0,d.jsxs)("option",{value:JSON.stringify([e.provider,e.id]),children:[e.provider," / ",e.name||e.id]},JSON.stringify([e.provider,e.id])))]}),(0,d.jsx)(mw,{onClick:S,disabled:m||!o,children:s("models.setDefault")})]})]}),(0,d.jsxs)("div",{className:"model-defaults-field",children:[(0,d.jsx)("label",{htmlFor:"settings-default-thinking",children:s("models.thinkingDefault")}),(0,d.jsxs)("div",{className:"model-defaults-control",children:[(0,d.jsxs)("select",{id:"settings-default-thinking",value:p,disabled:m,onChange:e=>{h(e.target.value),w("")},children:[(0,d.jsx)("option",{value:"",children:s("models.thinkingDefaultSelect")}),["off","minimal","low","medium","high","xhigh","max"].map(e=>(0,d.jsx)("option",{value:e,children:s(`chat.reasoningShort.${e}`)},e))]}),(0,d.jsx)(mw,{"aria-label":s("models.thinkingSetDefault"),onClick:C,disabled:m||!p,children:s("models.setDefault")})]})]})]}),(0,d.jsxs)("div",{className:"model-defaults-meta",children:[(0,d.jsx)("span",{children:s("models.defaultInstant")}),g&&!j&&0===l.length&&(0,d.jsxs)("div",{className:"model-defaults-empty",children:[(0,d.jsx)("p",{children:s("models.noDefaultModels")}),(0,d.jsx)(mw,{size:"small",onClick:i,children:s("i18n.addProvider")})]}),(0,d.jsxs)("details",{className:"model-defaults-help",children:[(0,d.jsx)("summary",{children:s("models.defaultNotes")}),(0,d.jsxs)("p",{children:[s("models.defaultHelp")," ",s("models.thinkingDefaultHelp")]})]}),j&&(0,d.jsx)(mw,{size:"small",onClick:()=>b(e=>e+1),children:s("i18n.refresh")}),(0,d.jsx)("span",{role:"status",className:j?"model-defaults-status is-error":"model-defaults-status",children:j||y})]})]})]})}function fl(e){let{onClose:t,embedded:n=!1,cwd:r=null}=e,{t:i}=(0,ns.s)(),{openDetail:s,closeDetail:l}=h0(),a=function(e){let[t,n]=(0,u.useState)(null),[r,i]=(0,u.useState)(!0),[s,l]=(0,u.useState)(null),[a,o]=(0,u.useState)(null),c=(0,u.useRef)(null),d=(0,u.useRef)(null),p=(0,u.useRef)(null),[h,m]=(0,u.useState)(0);(0,u.useEffect)(()=>{let t=new AbortController;i(!0);let r=e?`?cwd=${encodeURIComponent(e)}`:"";return fetch(`/api/models/enabled${r}`,{signal:t.signal}).then(async e=>{n(await nE(e)),o(null)}).catch(e=>{t.signal.aborted||o({message:e instanceof Error?e.message:String(e)})}).finally(()=>{t.signal.aborted||i(!1)}),()=>t.abort()},[e,h]);let f=(0,u.useCallback)((t,r)=>{if(c.current){d.current={key:t,body:r};return}c.current=t,l(t),o(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?mI[i.reason]:void 0;o(e?{messageKey:e}:{message:i.error??`HTTP ${t.status}`});return}n(i)}catch(e){o({message:e instanceof Error?e.message:String(e)})}finally{c.current=null,l(null);let e=d.current;d.current=null,e&&p.current?.(e.key,e.body)}})()},[e]);p.current=f;let g=(0,u.useCallback)((e,t,n)=>{f(e,{op:"models",refs:t,enabled:n})},[f]),x=(0,u.useCallback)((e,t)=>{f(`provider:${e}`,{op:"provider",provider:e,enabled:t})},[f]),v=(0,u.useCallback)(()=>f("clear",{op:"clear"}),[f]),b=(0,u.useCallback)(()=>f("prune",{op:"prune"}),[f]),y=(0,u.useCallback)(()=>m(e=>e+1),[]),w=(0,u.useCallback)((e,n)=>{f("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)})},[f,t]);return{view:t,loading:r,pending:s,failure:a,setModels:g,setProvider:x,clearScope:v,pruneStale:b,refresh:y,resync:w}}(r),[o,c]=(0,u.useState)({providers:{}}),[p,h]=(0,u.useState)(!0),[m,f]=(0,u.useState)(!1),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(null),[y,w]=(0,u.useState)(!1),[j,k]=(0,u.useState)(null),[S,C]=(0,u.useState)(0),[N,E]=(0,u.useState)(mU),[M,$]=(0,u.useState)([]),[I,T]=(0,u.useState)([]),[R,A]=(0,u.useState)({}),[L,P]=(0,u.useState)(()=>new Map),[z,O]=(0,u.useState)(!1),[W,F]=(0,u.useState)(null),[D,_]=(0,u.useState)(!1),B=(0,u.useRef)(null),[H,U]=(0,u.useState)(!1),K=(0,u.useRef)(new Set),q=(0,u.useRef)(new Map),V=(0,u.useRef)(new Map),Z=(0,u.useRef)(new WeakMap),J=(0,u.useRef)(0),Y=(0,u.useRef)(null),[G,X]=(0,u.useState)(null),[Q,ee]=(0,u.useState)(null),et=(0,u.useCallback)(()=>{B.current?.abort();let e=new AbortController;B.current=e;let t=setTimeout(()=>e.abort(),3e4);return _(!0),fetch("/api/auth/providers",{signal:e.signal,cache:"no-store"}).then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(`HTTP ${t.status}`);if(!Array.isArray(n.oauthProviders)||!Array.isArray(n.apiKeyProviders))throw Error("Invalid provider listing");return B.current===e&&($(n.oauthProviders),T(n.apiKeyProviders),A(n.providerNames??{}),F(null),!0)}).catch(t=>(B.current===e&&F(t instanceof Error?t.message:String(t)),!1)).finally(()=>{clearTimeout(t),B.current===e&&(O(!0),_(!1))})},[]);(0,u.useEffect)(()=>()=>{B.current?.abort(),B.current=null},[]),(0,u.useEffect)(()=>{fetch("/api/models-config").then(e=>nE(e)).then(e=>{let t=e.providers?e:{...e,providers:{}};c(t),k(JSON.stringify(t)),K.current=new Set(Object.keys(t.providers??{})),V.current=hK(t),P(hG(t));let n=Object.keys(t.providers??{});E(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=>b(e instanceof Error?e.message:String(e))).finally(()=>h(!1)),et()},[et]),(0,u.useEffect)(()=>{N&&hN("models",JSON.stringify(N))},[N]),(0,u.useEffect)(()=>{if(N?.type!=="provider")return;let e=o.providers?.[N.name];!(!e||!mK(e)||L.has(N.name))&&(M.some(e=>e.id===N.name)?E({type:"oauth",providerId:N.name}):I.some(e=>e.id===N.name)&&E({type:"apikey",providerId:N.name}))},[I,o.providers,M,L,N]);let en=e=>({overrides:o.providers?.[e]?.modelOverrides,disabled:p||m||null!==v,onChange:(t,n)=>{try{c(function(e,t,n,r){let i={...e.providers},s={...Object.hasOwn(i,t)?i[t]:{}},l={...s.modelOverrides},a=Object.hasOwn(l,n)?l[n]:void 0;if(void 0!==a&&!hM(a))throw Error("Model override must be an object");let o={...a};return void 0===r?delete o.contextWindow:o.contextWindow=r,Object.keys(o).length?Object.defineProperty(l,n,{value:o,enumerable:!0,configurable:!0}):delete l[n],Object.keys(l).length?s.modelOverrides=l:delete s.modelOverrides,Object.keys(s).length?Object.defineProperty(i,t,{value:s,enumerable:!0,configurable:!0}):delete i[t],{...e,providers:i}}(o,e,t,n)),w(!1),x(null)}catch(e){x(String(e))}}}),er=(0,u.useCallback)(()=>{let e="new-provider",t=1;for(;o.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),E({type:"provider",name:e})},[o.providers]),ei=(0,u.useCallback)((e,t)=>{c(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),es=(0,u.useCallback)((e,t,n)=>{let r=function(e,t,n,r){let i=e.providers??{};if(!Object.hasOwn(i,n))return null;if(n===r)return e;if(Object.hasOwn(i,r))return null;let{renames:s,slots:l}=t,a=hZ(t,n);a===r?s.delete(a):null!==a&&s.set(a,r);let o=l.get(n);o&&(l.delete(n),l.set(r,o));let c=Object.entries(i),d=c.findIndex(e=>{let[t]=e;return t===n});return c[d]=[r,c[d][1]],{...e,providers:Object.fromEntries(c)}}(e,{savedProviders:K.current,renames:q.current,slots:V.current},t,n);return r?(c(r),ee(null),E(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},[]),el=(0,u.useCallback)((e,t)=>{es(o,e,t)?x(null):x(i("models.providerIdTaken",{name:t}))},[es,o,i]),ea=(0,u.useCallback)(e=>{var t;let n,r,i=(null!==(n=hZ(t={savedProviders:K.current,renames:q.current,slots:V.current},e))&&(t.renames.delete(n),t.savedProviders.delete(n)),t.slots.delete(e),r={...o.providers??{}},delete r[e],{...o,providers:r}),s=Object.keys(i.providers??{});ee(t=>t?.provider===e?null:t),c(i),E(s.length>0?{type:"provider",name:s[0]}:null),l()},[o,l]),eo=(0,u.useCallback)(e=>{hq(V.current,e,1),c(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),c(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return E({type:"model",providerName:e,index:n}),t})},[]),ec=(0,u.useCallback)((e,t)=>{c(n=>{let r=new Set((n.providers?.[e]?.models??[]).map(e=>e.id));hq(V.current,e,t.filter(e=>!r.has(e.id)).length);let i=n.providers?.[e]??{},s=[...i.models??[]],l=new Set(s.map(e=>e.id));for(let e of t)l.has(e.id)||(l.add(e.id),s.push({...e}));return{...n,providers:{...n.providers??{},[e]:{...i,models:s}}}})},[]),ed=(0,u.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]],l=Z.current.get(s[t]);return l&&Z.current.set(n,l),s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),eu=(0,u.useCallback)(e=>{e&&(c(e.config),w(!1),x(null),E(t=>t?.type==="model"&&t.providerName===e.providerName?{...t,index:e.order.indexOf(t.index)}:t))},[]),ep=(0,u.useCallback)((e,t,n)=>{m||v||eu(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 l=[...s.keys()];return l.splice(r,1),l.splice(i,0,r),hV(e,t,n,l)}(o,V.current,e,t,n))},[eu,o,v,m]),eh=(0,u.useCallback)(e=>{if(!m&&!v){var t;let n,r;eu((t=V.current,n=o.providers?.[e]?.models??[],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),hV(o,t,e,[...n.keys()].sort((e,t)=>r.compare(hY(n[e]),hY(n[t]))))))}},[eu,o,v,m]),em=(0,u.useCallback)((e,t)=>{V.current.get(e)?.splice(t,1),c(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}}}}),E({type:"provider",name:e}),l()},[l]),ef=(0,u.useCallback)(async()=>{if(v)return;f(!0),x(null),w(!1);let e=o,t=Q?.name.trim();if(Q&&t&&o.providers?.[Q.provider]){let n=es(o,Q.provider,t);if(!n){x(i("models.providerIdTaken",{name:t})),f(!1);return}e=n}let n=JSON.stringify(e);try{var r=e=function(e){let t=structuredClone(e);if(!hM(t.providers))return t;for(let[e,n]of Object.entries(t.providers))if(hM(n)&&hM(n.modelOverrides))for(let[t,r]of Object.entries(n.modelOverrides)){if(!hM(r)||!Object.hasOwn(r,"contextWindow"))continue;let n=hI(r.contextWindow);if(void 0===n)throw new h$(`${e}/${t}`);r.contextWindow=n}return t}(e);if(hA(r.providers))for(let[e,t]of Object.entries(r.providers)){if(!hA(t))continue;if(t.oauth&&!t.baseUrl)throw new hR(e,"baseUrl");let n=Array.isArray(t.models)&&t.models.some(hL),r=hA(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 hR(e,"empty")}var s=e;if(hP(s.providers)){for(let[e,t]of Object.entries(s.providers))if(hP(t)&&Array.isArray(t.models))for(let n of t.models){if(!hP(n)||"string"==typeof n.id&&!n.id.trim())continue;let t=hz(n);if(void 0!==t&&void 0===hO(t))throw new hF(`${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(n),w(!0);let t=[...q.current].map(e=>{let[t,n]=e;return{from:t,to:n}}),r=function(e,t,n){let r=e=>{for(let[t,r]of n)if(r===e)return t;return e},i=[];for(let[n,s]of Object.entries(e.providers??{})){let e=t.get(n);e&&(s.models??[]).forEach((t,s)=>{let l=e[s];l&&t.id&&l!==t.id&&i.push({from:`${r(n)}/${l}`,to:`${n}/${t.id}`})})}return i}(e,V.current,q.current);K.current=new Set(Object.keys(e.providers??{})),V.current=hK(e),q.current.clear(),a.resync(t,r),C(e=>e+1);let i=hG(e);et().then(e=>{e&&P(i)})}}catch(e){e instanceof hR?(x(i(mV[e.problem],{provider:e.provider})),E({type:"provider",name:e.provider})):e instanceof h$?x(i("models.contextInvalid",{model:e.model})):x(e instanceof hF?i("models.imageMaxBytesInvalid",{model:e.model}):String(e))}finally{f(!1)}},[es,o,a,v,Q,et,i]),eg=null!==j&&(JSON.stringify(o)!==j||!!(Q&&Q.name.trim()!==Q.provider)),ex=y&&!eg,ev=Object.entries(o.providers??{}).filter(e=>{let[t,n]=e;if(!mK(n)||L.has(t))return!0;let r=M.some(e=>e.id===t)||I.some(e=>e.id===t);return z&&!r}),eb=(e,t)=>{var n,r,i;return n=R[e]??a.view?.providers.find(t=>t.id===e)?.name,i=void 0!==(r=L.get(e))&&n?.trim()===r.trim()?void 0:n,t.name?.trim()||i?.trim()||e},ey=e=>{let t=function(e,t){if(!e||e.allEnabled)return null;let n=mM(e,t);return n?`${n.enabledCount}/${n.models.length}`:null}(a.view,e);return t?(0,d.jsx)("span",{className:"models-sidebar-badge",children:t}):null},ew=M.filter(e=>e.loggedIn),ej=I.filter(e=>e.configured),ek=(()=>{if(!N)return null;if("oauth"===N.type){let e=M.find(e=>e.id===N.providerId);return e?(0,d.jsx)(ft,{provider:e,onRefresh:et,enabledModels:a,contextSettings:en(e.id)},e.id):null}if("apikey"===N.type){let e=I.find(e=>e.id===N.providerId);return e?(0,d.jsx)(fr,{provider:e,onRefresh:et,enabledModels:a,contextSettings:en(e.id)},e.id):null}if("provider"===N.type){let e=o.providers?.[N.name];return e&&ev.some(e=>{let[t]=e;return t===N.name})?(0,d.jsx)(m2,{name:N.name,editingName:Q?.provider===N.name?Q.name:N.name,fallbackLabel:eb(N.name,{}),provider:e,onChange:e=>ei(N.name,e),onEditingNameChange:e=>ee(e===N.name?null:{provider:N.name,name:e}),onRename:e=>el(N.name,e),onDelete:()=>ea(N.name),onAddModels:e=>ec(N.name,e),enabledModels:a},N.name):null}let e=o.providers?.[N.providerName],t=e?.models?.[N.index];return t?(0,d.jsx)(fe,{providerName:N.providerName,provider:e,model:t,onChange:e=>ed(N.providerName,N.index,e),onDelete:()=>em(N.providerName,N.index)},`${N.providerName}-${N.index}`):null})();return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(hX,{embedded:n,title:i("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:i("i18n.close"),onClose:t,children:[W&&(0,d.jsxs)("div",{className:"models-load-notice",role:"alert",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("strong",{children:i("models.providersLoadFailed")}),(0,d.jsx)("p",{children:i("models.providersLoadHelp")})]}),(0,d.jsx)(mw,{size:"small",onClick:()=>{et(),a.refresh(),C(e=>e+1)},disabled:D,children:i(D?"i18n.loading":"i18n.refresh")})]}),(0,d.jsx)(mT,{controller:a}),(0,d.jsxs)(h4,{children:[(0,d.jsxs)(h3,{children:[(0,d.jsxs)(h8,{children:[ew.map(e=>{let t=N?.type==="oauth"&&N.providerId===e.id;return(0,d.jsxs)(h7,{active:t,onClick:()=>E({type:"oauth",providerId:e.id}),children:[(0,d.jsx)(mW,{id:e.id,size:16}),(0,d.jsx)(me,{className:"is-grow",children:e.name}),ey(e.id)]},e.id)}),ej.map(e=>{let t=N?.type==="apikey"&&N.providerId===e.id;return(0,d.jsxs)(h7,{active:t,onClick:()=>E({type:"apikey",providerId:e.id}),children:[(0,d.jsx)(mW,{id:e.id,size:16}),(0,d.jsx)(me,{className:"is-grow",children:e.displayName}),ey(e.id)]},e.id)}),(ew.length>0||ej.length>0)&&ev.length>0&&(0,d.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),p?(0,d.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:i("i18n.loading")}):ev.map(e=>{let[t,n]=e,r=N?.type==="provider"&&N.name===t,s=n.models??[];return(0,d.jsxs)("div",{style:{marginBottom:2},children:[(0,d.jsxs)(h7,{onClick:()=>E({type:"provider",name:t}),active:r,children:[(0,d.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,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,d.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,d.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,d.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,d.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,d.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,d.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,d.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,d.jsx)(me,{className:"is-grow",children:eb(t,n)}),ey(t)]}),s.map((e,n)=>{var r;let s,l,a=N?.type==="model"&&N.providerName===t&&N.index===n,o=Z.current.get(e);o||(o=`model-${++J.current}`,Z.current.set(e,o));let c=G?.providerName===t&&G.index===n?G:null;return(0,d.jsxs)(h7,{active:a,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:()=>E({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(),ep(t,n,n+r))},...(r=e.id,s=e=>{var r;let i,s=Y.current;if(s?.providerName!==t)return null;let l=e.currentTarget.getBoundingClientRect(),a=e.clientY>=l.top+l.height/2;return{from:s.index,to:(r=s.index,r<(i=a?n+1:n)?i-1:i),after:a}},{draggable:!m&&!v,onDragStart:e=>{Y.current={providerName:t,index:n},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",r)},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};X(e=>e?.providerName===i?.providerName&&e?.index===i?.index&&e?.after===i?.after?e:i)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||X(e=>e?.providerName===t&&e.index===n?null:e)},onDrop:e=>{let n=s(e);n&&(e.preventDefault(),ep(t,n.from,n.to),l())},onDragEnd:l=()=>{Y.current=null,X(null)}}),children:[(0,d.jsx)(me,{className:"is-grow",style:{color:e.id?"var(--text-muted)":"var(--text-dim)"},children:hY(e)||i("i18n.newModel")}),e.reasoning&&(0,d.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"})]},o)}),(0,d.jsxs)("div",{className:"models-sidebar-model-footer",children:[(0,d.jsx)(h7,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:e=>{e.stopPropagation(),eo(t)},children:(0,d.jsxs)(me,{children:["+ ",i("i18n.model")]})}),(0,d.jsx)("button",{type:"button",className:"models-sidebar-sort-button","aria-label":i("models.sortByName"),title:i("models.sortByName"),disabled:m||null!==v||s.length<2,onClick:()=>eh(t),children:"A–Z"})]})]},t)})]}),(0,d.jsx)(fs,{cwd:r,revision:S,scope:a.view,onConfigure:()=>U(!0)},r??""),(0,d.jsx)(mk,{onClick:e=>{e.preventDefault(),U(!0)},children:i("i18n.addProvider")})]}),(0,d.jsx)(mv,{motionKey:N?JSON.stringify(N):"",children:(0,d.jsx)(mt,{className:"is-fill",children:p?null:ek??(0,d.jsx)(mx,{children:i("i18n.selectProviderModel")})})})]}),(0,d.jsxs)(mb,{status:v||g?(0,d.jsx)("span",{style:{color:"#f87171"},children:v?i("models.configUnreadable",{error:v}):g}):(0,d.jsxs)("span",{role:"status",children:[i(m?"i18n.saving":eg?"config.unsavedChanges":ex?"i18n.saved":"config.noPendingChanges")," \xb7 ",i("models.applyHelp")]}),children:[!n&&(0,d.jsx)(mw,{onClick:t,children:i("i18n.cancel")}),(0,d.jsxs)(mw,{variant:"primary",onClick:ef,disabled:m||ex&&!eg||null!==v,className:ex?"is-success":void 0,children:[ex&&(0,d.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,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,d.jsx)("span",{children:ex?i("i18n.saved"):m?i("i18n.saving"):i("i18n.save")})]})]})]}),H&&(0,d.jsx)(fi,{oauthProviders:M,apiKeyProviders:I,onSelectOAuth:e=>{E({type:"oauth",providerId:e}),s()},onSelectApiKey:e=>{E({type:"apikey",providerId:e}),s()},onAddCustom:()=>{er(),s()},onClose:()=>U(!1)})]})}let fa=null;async function fo(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(fa)return fa;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 fa=null,!1}})();return fa=t,t.then(e=>{e||fa!==t||(fa=null)}),t}function fc(e,t,n,r){return e.filter(e=>n(e)!==t&&(t||!r?.(e)))}function fd(e){return e?JSON.stringify([e.requiresTrust,e.trusted,e.decision,e.decisionPath??null,e.inherited]):""}function fu(e){let{skill:t,cwd:n,projectResourcesLoaded:r,busy:i,onBusy:s,onApplied:l}=e,{t:a}=(0,ns.s)(),o=(0,u.useId)(),[c,p]=(0,u.useState)(!1),[h,m]=(0,u.useState)(null),[f,g]=(0,u.useState)(!1),[x,v]=(0,u.useState)("move"),[b,y]=(0,u.useState)(null),[w,j]=(0,u.useState)(null);if(!t.install)return null;let k="global"===t.install.scope?"project":"global",S=a(`skills.scope.${k}`),C=e=>{let t=e.code&&["conflict","project-untrusted","unsupported","linked-files","overlap","source-changed","invalid-lock","too-large","undo-expired","undo-changed","recover"].includes(e.code)?e.code:"failed";y(a(`skills.transfer.error.${t}`)),j(e.targetPath??e.details??null)},N=async()=>{p(!0),g(!0),y(null),j(null),m(null);try{let e=await fetch("/api/skills/transfer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"preview",cwd:n,filePath:t.filePath,package:t.install.package})}),r=await e.json();if(!e.ok)return void C(r);m(r)}catch{y(a("skills.transfer.error.failed"))}finally{g(!1)}},E=async()=>{if(h){s(!0),y(null),j(null);try{let e=await fetch("/api/skills/transfer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"apply",cwd:n,filePath:t.filePath,package:t.install.package,mode:x,sharedAcknowledged:!0})}),r=await e.json();if(!e.ok)return void C(r);await l({...r,mode:x}),p(!1)}catch{y(a("skills.transfer.error.failed"))}finally{s(!1)}}};return(0,d.jsxs)("div",{className:"skills-scopeTransfer",children:[(0,d.jsxs)("div",{className:"skills-scopeTrigger",children:[(0,d.jsx)("span",{children:a("skills.transfer.intro")}),(0,d.jsx)(mw,{size:"small",onClick:()=>{c?p(!1):N()},disabled:i||!r,"aria-expanded":c,"aria-controls":o,children:a("skills.transfer.open")})]}),!r&&(0,d.jsx)("p",{className:"skills-transferNote",children:a("skills.transfer.error.project-untrusted")}),c&&(0,d.jsxs)("section",{id:o,className:"skills-transferForm","aria-label":a("skills.transfer.title"),children:[(0,d.jsxs)("div",{className:"skills-transferHeading",children:[(0,d.jsx)("h3",{children:a("skills.transfer.title")}),(0,d.jsxs)("span",{children:[a(`skills.scope.${t.install.scope}`)," → ",S]})]}),"project"===k&&(0,d.jsxs)("p",{className:"skills-transferNote",children:[a("skills.currentProject"),": ",(0,d.jsx)("code",{children:n})]}),f&&(0,d.jsx)("p",{role:"status",children:a("i18n.loading")}),h&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("fieldset",{className:"skills-transferModes",disabled:i,children:[(0,d.jsx)("legend",{children:a("skills.transfer.mode")}),["move","copy"].map(e=>(0,d.jsxs)("label",{className:x===e?"is-selected":void 0,children:[(0,d.jsx)("input",{type:"radio",name:`${o}-mode`,value:e,checked:x===e,onChange:()=>v(e)}),(0,d.jsxs)("span",{children:[(0,d.jsx)("strong",{children:a(`skills.transfer.${e}`)}),(0,d.jsx)("small",{children:a(`skills.transfer.${e}Help`)})]})]},e))]}),(0,d.jsxs)("div",{className:"skills-transferDestination",children:[(0,d.jsx)("span",{children:a("skills.transfer.destination")}),(0,d.jsx)("code",{children:h.targetPath})]}),(0,d.jsx)("p",{className:"skills-transferNote",children:a("skills.transfer.fileVersionHelp")}),(0,d.jsx)("p",{className:"skills-transferImpact",children:a("copy"===x?"skills.transfer.copyImpact":"global"===t.install.scope?"skills.transfer.globalMoveImpact":"skills.transfer.projectMoveImpact")})]}),b&&(0,d.jsxs)("div",{role:"alert",className:"skills-error",children:[b,w&&(0,d.jsx)("pre",{className:"skills-transferErrorDetail",children:w})]}),(0,d.jsxs)("div",{className:"skills-transferActions",children:[(0,d.jsx)(mw,{size:"small",onClick:()=>p(!1),disabled:i,children:a("i18n.cancel")}),h&&(0,d.jsx)(mw,{variant:"primary",size:"small",onClick:()=>void E(),disabled:i,children:i?a("skills.transfer.working"):a("move"===x?"skills.transfer.confirmMove":"skills.transfer.confirmCopy",{scope:S})})]})]})]})}function fp(e){if(e.install)return e.install.scope;let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function fh(e,t){return t("project"===e?"skills.scope.project":"global"===e?"skills.scope.global":"skills.scope.path")}function fm(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function ff(e,t){return e?e.slice(0,8):t}function fg(e){let{skill:t,cwd:n,onToggle:r,toggling:i,saveError:s,saved:l,updateStatus:a,checkingUpdate:o,updating:c,updateError:p,onCheckUpdate:h,onUpdate:m,onRemove:f,removing:g,collisions:x,projectResourcesLoaded:v,transferBusy:b,onTransferBusy:y,onTransferApplied:w}=e,{t:j}=(0,ns.s)(),k=fp(t),S=!t.disableModelInvocation,[C,N]=(0,u.useState)(null),[E,M]=(0,u.useState)(null),$=t.filePath.split(/[\\/]/).pop(),[I,T]=(0,u.useState)([]),R=I.at(-1)??$,A=(0,u.useRef)(null),L=(0,u.useRef)(null),[P,z]=(0,u.useState)(0),O=(0,u.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,R);L.current=t.anchor,t.document===R?z(e=>e+1):T(e=>[...e,t.document])},[R]);return(0,u.useLayoutEffect)(()=>{let e=L.current,t=A.current;null!==e&&(null!==C||E)&&t&&(L.current=null,((e?t.querySelector(`[data-heading-anchor="${CSS.escape(e)}"]`):null)??t).scrollIntoView({block:"start"}))},[C,E,P]),(0,u.useEffect)(()=>{let e=new AbortController;return N(null),M(null),(async()=>{try{let r=new URLSearchParams({cwd:n,filePath:t.filePath,management:"1"});R!==$&&r.set("document",R);let i=await fetch(`/api/skills/content?${r}`,{signal:e.signal}),s=await nE(i);if("string"!=typeof s.content)throw Error(`HTTP ${i.status}`);N(function(e,t){let n=pL(e).rest.trim();if(!t)return n;let r=n.match(/^#{1,6}[ \t]+(.*?)[ \t]*#*[ \t]*(?:\r?\n|$)/);return r&&r[1].trim().toLowerCase()===t.trim().toLowerCase()?n.slice(r[0].length).trim():n}(s.content,R===$?t.name:void 0))}catch(t){if(e.signal.aborted)return;M(t instanceof Error?t.message:String(t))}})(),()=>e.abort()},[n,t.filePath,t.name,R,$]),(0,d.jsxs)(mt,{className:"skills-detail",children:[(0,d.jsxs)("header",{className:"skills-hero",children:[(0,d.jsxs)("div",{className:"skills-heroTitle",children:[(0,d.jsx)("span",{className:"skills-skillIcon","aria-hidden":"true",children:(0,d.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[(0,d.jsx)("path",{d:"m12 3 9 5-9 5-9-5 9-5Z"}),(0,d.jsx)("path",{d:"m3 12 9 5 9-5M3 16l9 5 9-5"})]})}),(0,d.jsxs)("div",{className:"skills-heroIdentity",children:[(0,d.jsxs)("div",{className:"skills-eyebrow",children:[j("common.skills")," ",(0,d.jsx)(md,{scope:k,children:fh(k,j)}),!1===t.loaded&&(0,d.jsx)("span",{className:"skills-shadowBadge",children:j("skills.transfer.shadowed")})]}),(0,d.jsx)("h2",{children:t.name})]})]}),t.description&&(0,d.jsx)("p",{className:"skills-description",children:t.description})]}),(0,d.jsxs)("section",{className:"skills-visibility","aria-label":j("skills.visibilityTitle"),children:[(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"skills-visibilityTitle",children:[j("skills.visibilityTitle")," ",(0,d.jsx)("span",{className:S?"skills-enabled":"skills-hidden",children:j(S?"skills.visible":"skills.hidden")})]}),(0,d.jsx)("p",{children:j("skills.visibilityHelp")})]}),(0,d.jsx)(mj,{checked:S,loading:i,disabled:g||b,label:S?j("i18n.visibleInPrompt"):j("i18n.hiddenFromPrompt"),onChange:()=>r(t)})]}),(0,d.jsx)("p",{className:"skills-save-status",role:"status",children:j(i?"i18n.saving":l?"i18n.saved":"config.switchAutoSave")}),s&&(0,d.jsx)("p",{role:"alert",className:"skills-error",children:s}),x.length>0&&(0,d.jsx)("div",{className:"skills-collision",children:(0,d.jsxs)(ma,{label:j("skills.collisionTitle"),children:[(0,d.jsx)("p",{children:j("skills.collisionHelp")}),x.map(e=>(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{children:[j("skills.collisionWinner"),": ",(0,d.jsx)("code",{children:e.winnerPath})]}),(0,d.jsxs)("div",{children:[j("skills.collisionLoser"),": ",(0,d.jsx)("code",{children:e.loserPath})]})]},e.loserPath))]})}),(0,d.jsxs)("div",{className:"skills-metadata",children:[(0,d.jsx)(ma,{label:j("config.source"),children:t.install?.skillsShUrl?(0,d.jsx)("a",{href:t.install.skillsShUrl,target:"_blank",rel:"noreferrer",className:"skill-source-link",children:(0,d.jsxs)("span",{className:"skill-source-link-text",children:[t.install.source," ↗"]})}):(0,d.jsx)("span",{children:t.install?.source??t.sourceInfo?.source??fh(k,j)})}),t.install&&(0,d.jsxs)(ma,{label:j("i18n.version"),children:[(0,d.jsxs)("div",{className:"skill-version-row",children:[(0,d.jsx)("span",{className:"skill-version-value",children:ff(a?.currentVersion??t.install.versionHash,j("i18n.unknown"))}),t.install.canCheckForUpdates&&(0,d.jsx)(mw,{size:"small",onClick:h,disabled:o||c||b,children:j("i18n.check")}),a?.state==="update-available"&&(0,d.jsx)("span",{className:"skill-version-value is-update",children:ff(a.latestVersion,j("i18n.unknown"))}),(o||a&&"update-available"!==a.state)&&(0,d.jsx)("span",{className:`skill-update-status ${o?"is-checking":a?.state==="up-to-date"?"is-success":a?.state==="error"?"is-error":"is-muted"}`,children:o?j("i18n.checking"):a?.state==="up-to-date"?j("i18n.upToDate"):a?.state==="unsupported"?j("i18n.automaticChecksUnavailable"):a?.message||j("i18n.checkFailed")}),a?.state==="update-available"&&(0,d.jsx)(mw,{variant:"primary",size:"small",onClick:m,disabled:c||o||b,children:c?j("i18n.updating"):j("i18n.update")})]}),p&&(0,d.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:p})]}),(0,d.jsxs)("div",{className:"skills-pathField",children:[(0,d.jsx)(ma,{label:j("skills.location"),children:(0,d.jsx)("code",{children:t.filePath})}),(0,d.jsx)(fu,{skill:t,cwd:n,projectResourcesLoaded:v,busy:b||g||c||i,onBusy:y,onApplied:w})]})]}),(0,d.jsx)("section",{className:"skills-instructionsCard",children:(0,d.jsxs)(ma,{label:j("skills.instructions"),ref:A,children:[I.length>0&&(0,d.jsx)(mn,{children:(0,d.jsxs)(mr,{children:[(0,d.jsx)(mw,{size:"small",onClick:()=>{L.current="",T(e=>e.slice(0,-1))},children:j("skills.documentBack")}),(0,d.jsx)("span",{className:"config-detail-path",title:R,children:R})]})}),E?(0,d.jsx)("span",{role:"alert",className:"skill-instructions-status is-error",children:E}):null===C?(0,d.jsx)("span",{role:"status",className:"skill-instructions-status",children:j("i18n.loading")}):C?(0,d.jsx)(ah,{className:"skill-instructions",cwd:[t.baseDir,...R.split("/").slice(0,-1)].join("/"),onNavigateLink:O,children:C}):(0,d.jsx)("span",{className:"skill-instructions-status",children:j("skills.noInstructions")})]})}),t.install&&(0,d.jsxs)("section",{className:"skills-uninstall","aria-label":j("skills.removeTitle"),children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("h3",{children:j("skills.removeTitle")}),(0,d.jsx)("p",{children:j("skills.removeHelp")})]}),(0,d.jsx)(mw,{variant:"danger",size:"small",onClick:f,disabled:g||i||c||b,children:g?j("skills.removing"):j("skills.remove")})]})]})}function fx(e){let{cwd:t,installedPackages:n,projectResourcesLoaded:r,onInstalled:i}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(""),[o,c]=(0,u.useState)([]),[p,h]=(0,u.useState)(!1),[m,f]=(0,u.useState)(!1),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(null),[y,w]=(0,u.useState)(null),[j,k]=(0,u.useState)(new Set),[S,C]=(0,u.useState)("global"),N=(0,u.useRef)(null);(0,u.useEffect)(()=>{N.current?.focus()},[]);let E=(0,u.useCallback)(async e=>{if(e.trim()){h(!0),f(!0),x(null),c([]);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 x(n.error);c(n.results??[])}catch(e){x(String(e))}finally{h(!1)}}},[]),M=(0,u.useCallback)(async e=>{b(e),w(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:e,scope:S,cwd:t})}),r=await n.json();if(!n.ok||r.error)return void w(r.error??`HTTP ${n.status}`);k(t=>new Set(t).add(`${S}:${e}`)),i()}catch(e){w(String(e))}finally{b(null)}},[i,S,t]),$="global"===S?"~/.agents/skills/":`${tS(t)}/.agents/skills/`;return(0,d.jsxs)(mt,{className:"is-full-height skills-addPanel",children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,d.jsx)(mh,{title:s("i18n.addSkill"),catalogs:[{href:"https://skills.sh",label:"skills.sh"}],target:(0,d.jsx)(mp,{value:S,label:s("config.saveTo"),options:[{value:"global",label:fh("global",s)},{value:"project",label:fh("project",s),disabled:!r}],path:$,disabledReason:s("trust.projectScopeUnavailable"),onChange:C})}),(0,d.jsx)("p",{style:{fontSize:12,color:"var(--text-muted)",margin:0},children:s("skills.onlineSearchHelp")}),(0,d.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,d.jsx)("input",{ref:N,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&229!==e.keyCode&&("Enter"!==e.key||p||E(l))},"aria-label":s("skills.onlineSearch"),placeholder:s("skills.onlineSearchPlaceholder"),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,d.jsx)(mw,{variant:"primary",onClick:()=>E(l),disabled:p||!l.trim(),children:p?s("i18n.searching"):s("skills.onlineSearch")})]}),(0,d.jsx)("p",{className:"skills-installHint",children:s("skills.customInstallHint")}),g&&(0,d.jsxs)("div",{role:"alert",style:{fontSize:12,color:"#f87171"},children:[s("skills.searchFailed"),(0,d.jsxs)("details",{children:[(0,d.jsx)("summary",{children:s("skills.errorDetails")}),(0,d.jsx)("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:g})]})]}),y&&(0,d.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:y})]}),m&&!p&&!g&&0===o.length&&(0,d.jsx)(mx,{children:s("i18n.noSkills")}),o.length>0&&(0,d.jsx)("div",{style:{flex:1,overflowY:"auto"},children:o.map(e=>{let t=n[S].has(e.package)||j.has(`${S}:${e.package}`),r="global"===S?"project":"global",i=n[r].has(e.package)||j.has(`${r}:${e.package}`),l=v===e.package,a=e.package.indexOf("@"),o=a>-1?e.package.slice(0,a):e.package,c=a>-1?e.package.slice(a+1):null;return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:c??o}),i&&(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:s("skills.installedElsewhere",{scope:fh(r,s)})}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,d.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,d.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,d.jsx)(mw,{size:"small",onClick:()=>!t&&!l&&M(e.package),disabled:t||l||null!==v,style:{flexShrink:0,background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":l?"var(--accent)":"var(--text-muted)"},children:t?`✓ ${s("i18n.installed")}`:l?s("i18n.installing"):s("i18n.install")})]},e.package)})})]})}function fv(e){let{cwd:t,onClose:n,embedded:r=!1,trust:i,onTrustProject:s}=e,{t:l}=(0,ns.s)(),[a,o]=(0,u.useState)([]),[c,p]=(0,u.useState)(""),[h,m]=(0,u.useState)(!0),[f,g]=(0,u.useState)(null),[x,v]=(0,u.useState)(()=>hC("skills",t)),[b,y]=(0,u.useState)(new Set),[w,j]=(0,u.useState)(null),[k,S]=(0,u.useState)(null),[C,N]=(0,u.useState)(null),[E,M]=(0,u.useState)(null),[$,I]=(0,u.useState)(!1),[T,R]=(0,u.useState)({}),[A,L]=(0,u.useState)(new Set),[P,z]=(0,u.useState)(!1),[O,W]=(0,u.useState)(null),[F,D]=(0,u.useState)(null),[_,B]=(0,u.useState)(!0),[H,U]=(0,u.useState)([]),[K,q]=(0,u.useState)(!1),[V,Z]=(0,u.useState)(null),[J,Y]=(0,u.useState)(null),[G,X]=(0,u.useState)(!1),[Q,ee]=(0,u.useState)(!1),[et,en]=(0,u.useState)(null);(0,u.useEffect)(()=>{if(!et)return;let e=setTimeout(()=>en(null),3e5);return()=>clearTimeout(e)},[et]),(0,u.useEffect)(()=>{en(null),Z(null),Y(null)},[t]);let er=(0,u.useCallback)(async()=>{m(!0),g(null);try{let e=await fetch(`/api/skills?cwd=${encodeURIComponent(t)}&management=1`),n=await nE(e),r=n.skills??[];return o(r),U(n.diagnostics??[]),B(n.projectResourcesLoaded??!0),v(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 g(String(e)),[]}finally{m(!1)}},[t]);(0,u.useEffect)(()=>{R({}),D(null),er()},[t]);let ei=fd(i),es=(0,u.useRef)(ei);(0,u.useEffect)(()=>{es.current!==ei&&(es.current=ei,er())},[ei,er]),(0,u.useEffect)(()=>{x&&hN("skills",x,t)},[t,x]);let el=(0,u.useCallback)(async e=>{let n=(e?[e]:a.filter(e=>!!e.install)).map(fm).filter(e=>!!e);if(0!==n.length){D(null),L(e=>new Set([...e,...n])),e||z(!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 nE(n);R(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){D(e instanceof Error?e.message:String(e))}finally{L(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),e||z(!1)}}},[t,a]),ea=(0,u.useCallback)(async e=>{if(!e.install)return;let n=fm(e);W(n),D(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 er();let s=i.skill?.install?.versionHash;R(t=>({...t,[n]:{package:e.install.package,scope:e.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){D(e instanceof Error?e.message:String(e))}finally{W(null)}},[t,er]),eo=(0,u.useCallback)(async e=>{let t=!e.disableModelInvocation;y(t=>new Set(t).add(e.filePath)),j(null),S(null),M(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 j(r.error??`HTTP ${n.status}`);o(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),S(e.filePath)}catch(e){j(String(e))}finally{y(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),ec=(0,u.useCallback)(async(e,t,n)=>{let r=fc(t,n,e=>!e.disableModelInvocation);if(0===r.length)return;let i=r.map(e=>e.filePath),s=!n;y(e=>new Set([...e,...i])),N(e),S(null),j(null),M(null);try{let t=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePaths:i,disableModelInvocation:s})}),n=await nE(t);if(!n.results)throw Error(`HTTP ${t.status}`);let a=n.results;o(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 c=a.filter(e=>e.error);if(c.length>0){let t=new Map(r.map(e=>[e.filePath,e.name]));M({group:e,error:[l("skills.bulkFailed",{count:c.length,total:a.length}),...c.map(e=>`${t.get(e.filePath)??e.filePath}: ${e.error}`)].join("\n")})}}catch(t){M({group:e,error:t instanceof Error?t.message:String(t)})}finally{N(null),y(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t})}},[l]),ed=a.find(e=>e.filePath===x)??null,eu=async e=>{if(e.install&&window.confirm(l("skills.removeConfirm",{name:e.name,scope:fh(e.install.scope,l),path:e.filePath}))){q(!0),en(null),Z(null),Y(null),X(!1);try{let n=await fetch("/api/skills/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,filePath:e.filePath,package:e.install.package,scope:e.install.scope,sharedAcknowledged:!0})}),r=await n.json();if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);await er(),!0===r.remains?Z(l(r.failed?"skills.removeFailedStillLoaded":"skills.removeShared")):null===r.remains?Z(l("skills.removeUnknown")):r.failed?Z(l("skills.removeFailedGone")):(Z(l("skills.removeDone",{name:e.name})),X(!0)),r.backupPath?Y(l("skills.removeBackup",{path:r.backupPath})):r.details&&Y(r.details)}catch(e){Z(e instanceof Error?e.message:String(e))}finally{q(!1)}}},ep=async(e,n)=>{await er(),v(e.targetPath),R({}),X(!0),Y(null),Z(l("move"===e.mode?"skills.transfer.moved":"skills.transfer.copied",{name:n.name,scope:fh("global"===n.install.scope?"project":"global",l)})),en({token:e.undoToken,cwd:t})},eh=async()=>{if(et){ee(!0);try{let e=await fetch("/api/skills/transfer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"undo",cwd:t,undoToken:et.token})}),n=await e.json();if(!e.ok)throw Error(l(`skills.transfer.error.${["conflict","undo-expired","undo-changed","project-untrusted"].includes(n.code??"")?n.code:"failed"}`));await er(),v(n.targetPath??null),en(null),X(!0),Z(l("skills.transfer.undone")),Y(null)}catch(e){X(!1),Z(e instanceof Error?e.message:String(e))}finally{ee(!1)}}},em=h||b.size>0||null!==O||K||Q;return(0,d.jsx)("div",{className:"skills-panel",children:(0,d.jsxs)(hX,{embedded:r,title:l("common.skills"),subtitle:tS(t),closeLabel:l("i18n.close"),onClose:n,children:[!_&&(0,d.jsx)(mg,{message:l("trust.skillsNotLoaded"),trustLabel:l("mcp.trust.trustButton"),onTrust:i?.requiresTrust&&!i.trusted?s:void 0}),V&&(0,d.jsxs)("div",{className:`skills-notice ${G?"skills-noticeSuccess":"skills-noticeWarning"}`,role:G?"status":"alert",children:[(0,d.jsx)("span",{className:"skills-noticeIcon","aria-hidden":"true",children:G?"✓":"!"}),(0,d.jsxs)("div",{className:"skills-noticeBody",children:[(0,d.jsx)("div",{children:V}),et&&(0,d.jsx)("small",{className:"skills-undoHint",children:l("skills.transfer.undoWindow")}),J&&(0,d.jsxs)("details",{children:[(0,d.jsx)("summary",{children:l("skills.removeDetails")}),(0,d.jsx)("pre",{children:J})]})]}),et&&et.cwd===t&&(0,d.jsx)(mw,{size:"small",disabled:Q,onClick:()=>void eh(),children:l("skills.transfer.undo")}),(0,d.jsx)("button",{className:"skills-dismiss","aria-label":l("skills.dismissNotice"),onClick:()=>{Z(null),Y(null),en(null)},children:"\xd7"})]}),(0,d.jsxs)(h4,{children:[(0,d.jsxs)(h3,{children:[(0,d.jsxs)("div",{className:"skills-sidebarContext",children:[(0,d.jsx)("span",{children:l("skills.currentProject")}),(0,d.jsx)("code",{children:tS(t)})]}),(0,d.jsxs)("div",{className:"skills-filter",children:[(0,d.jsxs)("svg",{"aria-hidden":"true",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[(0,d.jsx)("circle",{cx:"8.5",cy:"8.5",r:"5.5"}),(0,d.jsx)("path",{d:"m13 13 4 4"})]}),(0,d.jsx)("input",{value:c,onChange:e=>p(e.target.value),placeholder:l("skills.filterInstalled"),"aria-label":l("skills.filterInstalled")})]}),(0,d.jsx)(h8,{children:h?(0,d.jsx)("div",{className:"config-sidebar-message",children:l("i18n.loading")}):f?(0,d.jsx)("div",{className:"config-sidebar-message is-error",children:f}):0!==a.length&&a.some(e=>e.name.toLowerCase().includes(c.trim().toLowerCase()))?(()=>{let e=[],t={project:l("skills.scope.project"),global:l("skills.scope.global"),path:l("skills.scope.path")};for(let{label:n,matches:r}of[{label:t.project,matches:e=>"project"===fp(e)},{label:t.global,matches:e=>"global"===fp(e)},{label:t.path,matches:e=>"path"===fp(e)}]){let t=a.filter(r);t.some(e=>e.name.toLowerCase().includes(c.trim().toLowerCase()))&&e.push({label:n,skills:t})}let n=e=>{let t,n,r=!$&&x===e.filePath,i=e.disableModelInvocation;return(0,d.jsxs)(h7,{active:r,onClick:()=>{v(e.filePath),I(!1)},children:[(0,d.jsx)(mS,{active:!i&&!1!==e.loaded}),(0,d.jsx)(me,{className:`is-grow${i?" is-muted":""}`,children:e.name}),!1===e.loaded&&(0,d.jsx)("span",{className:"skills-shadowBadge",children:l("skills.transfer.shadowed")}),(n=(t=fm(e))?T[t]:void 0,n?.state!=="update-available"?null:(0,d.jsx)("span",{title:l("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(e=>{let{label:t,skills:r}=e,i=r.filter(e=>!e.disableModelInvocation).length,s=i===r.length;return(0,d.jsxs)("div",{className:"config-sidebar-group",children:[(0,d.jsx)(h6,{aside:(0,d.jsx)(h5,{enabled:i,total:r.length,disabled:em||!!c.trim(),loading:C===t,label:l(s?"skills.groupSwitchOn":"skills.groupSwitchOff",{group:t}),onChange:e=>void ec(t,r,e)}),children:t}),E?.group===t&&(0,d.jsx)(h9,{error:E.error}),[...r.filter(e=>!e.disableModelInvocation),...r.filter(e=>e.disableModelInvocation)].filter(e=>e.name.toLowerCase().includes(c.trim().toLowerCase())).map(n)]},t)})})():(0,d.jsx)("div",{className:"config-sidebar-message is-empty",children:l(c.trim()?"skills.noMatch":"i18n.noSkills")})}),(0,d.jsx)(mk,{onClick:()=>I(!0),active:$,children:l("i18n.addSkill")})]}),(0,d.jsx)(mv,{motionKey:$?"add":x??"",children:(0,d.jsx)(mt,{className:"is-fill",children:$?(0,d.jsx)(fx,{cwd:t,projectResourcesLoaded:_,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{er()}}):h?null:ed?(0,d.jsx)(fg,{skill:ed,cwd:t,onToggle:eo,toggling:b.has(ed.filePath),saveError:w,saved:k===ed.filePath,updateStatus:fm(ed)?T[fm(ed)]:void 0,checkingUpdate:!!fm(ed)&&A.has(fm(ed)),updating:O===fm(ed),updateError:F,onCheckUpdate:()=>void el(ed),onUpdate:()=>void ea(ed),onRemove:()=>void eu(ed),removing:K,collisions:H.flatMap(e=>e.collision?.resourceType==="skill"&&(e.collision.winnerPath===ed.filePath||e.collision.loserPath===ed.filePath)?[e.collision]:[]),projectResourcesLoaded:_,transferBusy:Q,onTransferBusy:ee,onTransferApplied:e=>ep(e,ed)},ed.filePath):(0,d.jsx)(mx,{children:l("i18n.selectSkill")})})})]}),(0,d.jsxs)(mb,{status:Object.values(T).filter(e=>"update-available"===e.state).length>0&&(0,d.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(T).filter(e=>"update-available"===e.state).length," ",1===Object.values(T).filter(e=>"update-available"===e.state).length?l("i18n.update"):l("i18n.updates")]}),children:[!r&&(0,d.jsx)(mw,{onClick:n,children:l("i18n.close")}),a.some(e=>!!e.install)&&(0,d.jsx)(mw,{variant:"secondary",onClick:()=>void el(),disabled:P||null!==O||Q||K,children:P?l("i18n.checking"):l("i18n.checkUpdates")})]})]})})}let fb={builtin:0,global:1,workspace:2,project:3},fy=["read","bash","edit","write","grep","find","ls"],fw=["","off","minimal","low","medium","high","xhigh","max"],fj={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},fk={width:"100%",minWidth:0,height:38,padding:"0 11px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},fS={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function fC(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 fN(e){return`${e.scope}:${e.name}`}function fE(e){return"global"===e||"project"===e}function fM(e){return fE(e)||"builtin"===e}function f$(e){let{label:t,children:n}=e;return(0,d.jsx)(ma,{label:t,children:n})}function fI(e){let{checked:t,disabled:n,label:r,onChange:i}=e;return(0,d.jsxs)("label",{className:`agents-option${t?" is-selected":""}`,children:[(0,d.jsx)("input",{type:"checkbox",checked:t,disabled:n,onChange:e=>i(e.target.checked)}),r]})}function fT(e){let{profile:t}=e,{t:n}=(0,ns.s)();return(0,d.jsxs)("div",{className:"agents-profile-overview",children:[(0,d.jsxs)("section",{className:"agents-profile-section",children:[(0,d.jsx)("h4",{children:n("agents.prompt")}),(0,d.jsx)("pre",{className:"agents-prompt-preview",children:t.systemPrompt||n("agents.promptEmpty")})]}),(0,d.jsxs)("section",{className:"agents-profile-section",children:[(0,d.jsx)("h4",{children:n("agents.permissions")}),(0,d.jsxs)("div",{className:"agents-summary-group",children:[(0,d.jsx)("span",{children:n("agents.tools")}),(0,d.jsx)("div",{className:"agents-tags",children:t.tools.length?t.tools.map(e=>(0,d.jsx)("code",{children:e},e)):(0,d.jsx)("span",{children:n("agents.noTools")})})]}),(0,d.jsxs)("div",{className:"agents-summary-group",children:[(0,d.jsx)("span",{children:n("agents.resources")}),(0,d.jsx)("div",{className:"agents-tags",children:[["agents.loadSkills",t.loadSkills],["agents.loadExtensions",t.loadExtensions],["agents.mcp","on"===t.mcp]].map(e=>{let[t,r]=e;return(0,d.jsxs)("span",{className:r?"":"is-muted",children:[n(t)," \xb7 ",n(r?"agents.on":"agents.off")]},t)})})]}),t.loadSkills&&void 0!==t.skills&&(0,d.jsx)("p",{className:"agents-help",children:t.skills.length?n("agents.skillsOnly",{skills:t.skills.join(", ")}):n("agents.skillsNone")}),t.loadExtensions&&void 0!==t.extensions&&(0,d.jsx)("p",{className:"agents-help",children:t.extensions.length?n("agents.extensionsOnly",{extensions:t.extensions.join(", ")}):n("agents.extensionsNone")})]}),(0,d.jsxs)("section",{className:"agents-profile-section",children:[(0,d.jsx)("h4",{children:n("agents.runtime")}),(0,d.jsx)("dl",{className:"agents-summary-grid",children:[[n("agents.model"),t.model||n("agents.inherit")],[n("agents.thinking"),t.thinking||n("agents.inherit")],[n("agents.maxTurns"),t.maxTurns??n("agents.unlimited")],[n("agents.codemode"),n(`agents.codemode.${t.codemode??"off"}`)],[n("agents.inheritContext"),n(t.inheritContext?"agents.on":"agents.off")],[n("agents.background"),n(t.runInBackground?"agents.on":"agents.off")]].map(e=>{let[t,n]=e;return(0,d.jsxs)("div",{children:[(0,d.jsx)("dt",{children:t}),(0,d.jsx)("dd",{children:n})]},t)})})]})]})}function fR(e){let{onCancel:t,onConfirm:n,deleteName:r}=e,{t:i}=(0,ns.s)(),s=(0,u.useRef)(null),l=(0,u.useRef)(t);return l.current=t,(0,u.useLayoutEffect)(()=>{let e=s.current;e?.showModal();let t=tW(document,()=>l.current());return()=>{t(),e?.open&&e.close()}},[]),(0,d.jsxs)("dialog",{ref:s,className:"agents-discard-dialog","aria-labelledby":"agents-discard-title",onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&e.stopPropagation()},children:[(0,d.jsx)("h3",{id:"agents-discard-title",children:r?i("agents.deleteConfirm",{name:r}):i("agents.unsavedTitle")}),(0,d.jsx)("p",{children:i(r?"agents.deleteHint":"agents.unsavedHint")}),(0,d.jsxs)("div",{children:[(0,d.jsx)(mw,{autoFocus:!0,onClick:t,children:i(r?"i18n.cancel":"agents.keepEditing")}),(0,d.jsx)(mw,{variant:"danger",onClick:n,children:i(r?"agents.delete":"agents.discard")})]})]})}function fA(e){let{cwd:t,sessionId:n=null,onClose:r,onReloaded:i,embedded:s=!1,trust:l}=e,{t:a}=(0,ns.s)(),[o,c]=(0,u.useState)([]),[p,h]=(0,u.useState)([]),[m,f]=(0,u.useState)(!0),[g,x]=(0,u.useState)(null),[v,b]=(0,u.useState)(()=>hC("agents",t)),[y,w]=(0,u.useState)(fj),[j,k]=(0,u.useState)(JSON.stringify(fj)),[S,C]=(0,u.useState)(null),[N,E]=(0,u.useState)(!1),M=(0,u.useRef)(null),$=(0,u.useRef)("global"),I=(0,u.useRef)(null),T=()=>requestAnimationFrame(()=>I.current?.focus({preventScroll:!0})),[R,A]=(0,u.useState)("view"),[L,P]=(0,u.useState)("global"),[z,O]=(0,u.useState)(!0),[W,F]=(0,u.useState)(!1),[D,_]=(0,u.useState)(!1),[B,H]=(0,u.useState)(!1),[U,K]=(0,u.useState)(null),[q,V]=(0,u.useState)(!1),[Z,J]=(0,u.useState)(10),Y=(0,u.useRef)(10),[G,X]=(0,u.useState)(!0),[Q,ee]=(0,u.useState)(!1),[et,en]=(0,u.useState)(null),[er,ei]=(0,u.useState)(!1),[es,el]=(0,u.useState)(!1),ea=(0,u.useMemo)(()=>o.find(e=>fN(e)===v)??null,[o,v]),eo=(0,u.useMemo)(()=>p.map(e=>({provider:e.provider,providerName:e.providerName,modelId:e.id,name:e.name})),[p]),ec=(0,u.useCallback)(async e=>{O(!0),K(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(t)}`,{cache:"no-store"}),r=(await nE(n)).profiles??[];c(r);let i=e??hC("agents",t),s=r.find(e=>fN(e)===i)??r.find(e=>"project"===e.scope)??r.find(e=>"global"===e.scope)??r[0]??null;b(s?fN(s):null),s&&(w(fC(s)),k(JSON.stringify(fC(s))),A("view"),fE(s.scope)&&P(s.scope))}catch(e){K(e instanceof Error?e.message:String(e))}finally{O(!1)}},[t]);(0,u.useEffect)(()=>{ec()},[ec]),(0,u.useEffect)(()=>{let e=new AbortController;return X(!0),en(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await nE(t);if("boolean"!=typeof n.enabled)throw Error(`HTTP ${t.status}`);V(n.enabled),"number"==typeof n.maxConcurrent&&(J(n.maxConcurrent),Y.current=n.maxConcurrent)}catch(t){if(e.signal.aborted)return;en(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||X(!1)}})(),()=>e.abort()},[]),(0,u.useEffect)(()=>{v&&hN("agents",v,t)},[t,v]);let ed=fd(l);(0,u.useEffect)(()=>{let e=new AbortController;return f(!0),x(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(t)}`,{signal:e.signal}),r=await nE(n);h(r.modelList??[]),x(r.modelError??null)}catch(t){if(e.signal.aborted)return;x(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||f(!1)}})(),()=>e.abort()},[t,ed]);let eu=e=>{_(!1),b(fN(e)),w(fC(e)),k(JSON.stringify(fC(e))),A("view"),fE(e.scope)&&P(e.scope),K(null)},ep=()=>{_(!1),M.current=v,$.current="global";let e="custom-agent",t=2;for(;o.some(t=>t.name===e);)e=`custom-agent-${t++}`;b(null),w({...fj,name:e,displayName:e}),k(JSON.stringify({...fj,name:e,displayName:e})),A("create"),P("global"),K(null)},eh=async()=>{if(ev&&!W&&!B&&(eg||ex)){F(!0),K(null),_(!1);try{let e=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:L,profile:y})}),n=await nE(e);if(!n.profile)throw Error(`HTTP ${e.status}`);await ec(fN(n.profile)),_(!0),T()}catch(e){K(e instanceof Error?e.message:String(e))}finally{F(!1)}}},em=async()=>{if(ea&&fE(ea.scope)){F(!0),K(null);try{let e=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:ea.scope,name:ea.name})});await nE(e),await ec(),T()}catch(e){K(e instanceof Error?e.message:String(e))}finally{F(!1)}}},ef="view"!==R,eg="create"===R,ex=ef&&(JSON.stringify(y)!==j||eg&&L!==$.current),ev=!!y.name.trim()&&(void 0===y.maxTurns||Number.isInteger(y.maxTurns)&&y.maxTurns>0),eb=e=>{W||B||(ex?C(()=>e):e())},ey=!ef||W||B,ew=eg?L:ea?.scope,ej=eg?"global"===L?`~/.pi/agent/agents/${y.name||"..."}.md`:`./.pi/agents/${y.name||"..."}.md`:ea?(ea.filePath?"project"===ea.scope||"workspace"===ea.scope?tC(ea.filePath,t):tS(ea.filePath):null)??a("agents.builtinPath"):"",ek=eg?ej:ea?.filePath??ej,eS=e=>p.some(t=>`${t.provider}/${t.id}`===e),eC=y.model&&function(e,t){if(t(e))return e;let n=e.lastIndexOf(":"),r=e.slice(n+1);return n>0&&r&&fw.includes(r)?e.slice(0,n):e}(y.model,eS),eN=!eC||eS(eC),eE=(()=>{if(!eC)return null;let e=eC.indexOf("/");return e<0?{provider:"",modelId:eC}:{provider:eC.slice(0,e),modelId:eC.slice(e+1)}})(),eM=ey?{...fk,...fS}:fk,e$=eg?ey:!ea||!fM(ea.scope)||W||B,eI=(e,t)=>{_(!1),w(n=>({...n,[e]:t}))},eT=0===y.tools.length&&!y.loadSkills&&!y.loadExtensions,eR=async e=>{if(ef)return void eI("enabled",e);if(ea&&fM(ea.scope)){H(!0),K(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t,scope:ea.scope,name:ea.name,enabled:e})}),r=await nE(n);if(!r.profile)throw Error(`HTTP ${n.status}`);let i=r.profile;c(e=>e.map(e=>fN(e)===fN(i)?i:e)),w(e=>({...e,enabled:i.enabled}))}catch(e){K(e instanceof Error?e.message:String(e))}finally{H(!1)}}},eA=async e=>{ee(!0),en(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await nE(t);if("boolean"!=typeof r.enabled)throw Error(`HTTP ${t.status}`);V(r.enabled),ei(!!n)}catch(e){en(e instanceof Error?e.message:String(e))}finally{ee(!1)}},eL=async e=>{if(!Number.isInteger(e)||e<1||e>32)return void en(a("agents.concurrentInvalid"));if(en(null),e!==Y.current&&!Q){ee(!0),J(e),en(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await nE(t);if("number"!=typeof n.maxConcurrent)throw Error(`HTTP ${t.status}`);J(n.maxConcurrent),Y.current=n.maxConcurrent}catch(e){en(e instanceof Error?e.message:String(e))}finally{ee(!1)}}},eP=async()=>{if(n){el(!0),en(null);try{await dA(n,{type:"reload"}),ei(!1),i?.()}catch(e){en(e instanceof Error?e.message:String(e))}finally{el(!1)}}};return(0,d.jsx)(hX,{embedded:s,title:a("common.agents"),subtitle:tS(t),closeLabel:a("agents.close"),onClose:r,children:(0,d.jsxs)("div",{className:"agents-panel",children:[(0,d.jsxs)("div",{className:"agents-feature-setting",children:[(0,d.jsxs)("div",{className:"agents-feature-copy",children:[(0,d.jsx)("strong",{children:a("agents.featureTitle")}),(0,d.jsx)("span",{children:a("agents.featureHint")}),er&&(0,d.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:a("agents.reloadRequired")})]}),(0,d.jsxs)("div",{className:"agents-feature-actions",children:[er&&n&&(0,d.jsx)(mw,{size:"small",onClick:()=>void eP(),disabled:es||Q,children:es?a("agents.reloading"):a("agents.reloadSession")}),(0,d.jsxs)("label",{className:"agents-concurrency-control",title:a("agents.maxConcurrentDescription"),children:[(0,d.jsx)("span",{children:a("agents.maxConcurrent")}),(0,d.jsx)("input",{"aria-label":a("agents.maxConcurrent"),type:"number",min:1,max:32,value:Z,"aria-invalid":!Number.isInteger(Z)||Z<1||Z>32||void 0,disabled:G||Q,onChange:e=>J(Number(e.target.value)),onBlur:()=>void eL(Z)})]}),(0,d.jsx)(mj,{checked:q,disabled:G||es,loading:Q,label:a("agents.builtInTitle"),onChange:e=>void eA(e)})]})]}),(0,d.jsxs)(h4,{children:[(0,d.jsxs)(h3,{children:[(0,d.jsx)(h8,{children:z?(0,d.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:a("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=o.filter(t=>t.scope===e);return 0===t.length?null:(0,d.jsxs)("div",{className:"config-sidebar-group",children:[(0,d.jsx)(h6,{children:a(`agents.scope.${e}`)}),t.map(e=>{let t,n,r=(t=e.name.toLowerCase(),n=fb[e.scope],o.some(e=>e.name.toLowerCase()===t&&fb[e.scope]>n));return(0,d.jsxs)(h7,{active:v===fN(e)&&!eg,disabled:W||B,onClick:()=>{(v!==fN(e)||eg)&&eb(()=>eu(e))},children:[(0,d.jsx)(mS,{active:e.enabled}),(0,d.jsx)(me,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),r&&(0,d.jsx)("span",{className:"agents-overridden-label",children:a("agents.overridden")})]},fN(e))})]},e)})}),(0,d.jsx)(mk,{active:eg,onClick:()=>{eg||eb(ep)},disabled:W||B,children:a("agents.new")})]}),(0,d.jsx)(mv,{motionKey:JSON.stringify([v,R]),resetScrollOnChange:!0,children:(0,d.jsx)(mt,{className:"is-fill",children:ea||eg?(0,d.jsxs)(mt,{className:"agents-profile-content",children:[(0,d.jsxs)(mn,{children:[(0,d.jsxs)(mr,{children:[eg?(0,d.jsx)(mp,{value:L,label:a("config.saveTo"),options:["global","project"].map(e=>({value:e,label:a(`agents.scope.${e}`),disabled:W})),path:ej,onChange:P}):(0,d.jsxs)(d.Fragment,{children:[ew&&(0,d.jsx)(md,{scope:ew,children:a(`agents.scope.${ew}`)}),ea?.filePath&&(0,d.jsx)("span",{title:ek,className:"config-detail-path",children:ej})]}),(0,d.jsx)("h3",{ref:I,tabIndex:-1,className:"agents-profile-title",children:eg?a("agents.new"):y.displayName||y.name}),!eg&&(0,d.jsx)("code",{className:"agents-profile-id",children:y.name}),!ef&&y.description&&(0,d.jsx)("p",{className:"agents-profile-description",children:y.description})]}),(0,d.jsxs)(mi,{children:[ea&&"view"===R&&(0,d.jsx)(mw,{variant:fE(ea.scope)?"secondary":"primary",size:"small",onClick:()=>{if(!ea)return;_(!1),M.current=v,$.current=fE(ea.scope)?ea.scope:"global";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}(ea.name,o);b(null),w({...fC(ea),name:e,displayName:a("agents.copyName",{name:ea.displayName})}),k(JSON.stringify({...fC(ea),name:e,displayName:a("agents.copyName",{name:ea.displayName})})),A("create"),P(fE(ea.scope)?ea.scope:"global"),K(null)},disabled:W||B,children:a("agents.duplicate")}),ea&&fE(ea.scope)&&"view"===R&&(0,d.jsx)(mw,{variant:"primary",size:"small",onClick:()=>{_(!1),k(JSON.stringify(y)),A("edit")},children:a("agents.edit")}),(0,d.jsxs)("span",{className:"agents-enabled-control",children:[(0,d.jsx)("span",{children:a(y.enabled?"agents.on":"agents.off")}),(0,d.jsx)(mj,{checked:y.enabled,disabled:e$,label:y.enabled?a("agents.disable"):a("agents.enable"),onChange:e=>void eR(e)})]})]})]}),!ef&&(0,d.jsxs)(d.Fragment,{children:[ea&&!fE(ea.scope)&&(0,d.jsx)("p",{className:"agents-readonly-note",children:a("builtin"===ea.scope?"agents.builtinHint":"agents.readonlyHint")}),(0,d.jsx)(fT,{profile:y}),ea&&fE(ea.scope)&&(0,d.jsx)("div",{className:"agents-delete-row",children:(0,d.jsx)(mw,{variant:"danger",size:"small",disabled:W||B,onClick:()=>E(!0),children:a("agents.delete")})})]}),ef&&(0,d.jsxs)("form",{id:"agents-profile-form",className:"agents-profile-form",onSubmit:e=>{e.preventDefault(),eh()},onKeyDown:e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&!e.nativeEvent.isComposing&&229!==e.nativeEvent.keyCode&&(e.preventDefault(),eh())},children:[(0,d.jsxs)("section",{className:"agents-profile-section",children:[(0,d.jsx)("h4",{children:a("agents.basic")}),(0,d.jsxs)("div",{className:"agents-identity-grid",children:[(0,d.jsx)(f$,{label:a("agents.name"),children:eg?(0,d.jsx)("input",{autoFocus:!0,"aria-label":a("agents.name"),value:y.name,disabled:ey,onChange:e=>eI("name",e.target.value),style:fk}):(0,d.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:y.name})}),(0,d.jsx)(f$,{label:a("agents.displayName"),children:(0,d.jsx)("input",{autoFocus:!eg,"aria-label":a("agents.displayName"),value:y.displayName,disabled:ey,onChange:e=>eI("displayName",e.target.value),style:eM})})]}),(0,d.jsx)(f$,{label:a("agents.description"),children:(0,d.jsx)("input",{"aria-label":a("agents.description"),value:y.description,disabled:ey,onChange:e=>eI("description",e.target.value),style:eM})})]}),(0,d.jsx)("section",{className:"agents-profile-section",children:(0,d.jsx)(f$,{label:a("agents.prompt"),children:(0,d.jsx)("textarea",{className:"agents-system-prompt","aria-label":a("agents.prompt"),value:y.systemPrompt,disabled:ey,onChange:e=>eI("systemPrompt",e.target.value),style:{...eM,height:180,minHeight:140,maxHeight:"60vh",padding:9,overflow:"auto",resize:ey?"none":"vertical",lineHeight:1.5}})})}),(0,d.jsxs)("section",{className:"agents-profile-section",children:[(0,d.jsx)("h4",{children:a("agents.permissions")}),(0,d.jsx)("div",{className:"agents-tool-presets",children:[["agents.toolsReadOnly",["read","grep","find","ls"]],["agents.toolsAll",fy],["agents.toolsClear",[]]].map(e=>{let[t,n]=e;return(0,d.jsx)(mw,{size:"small",disabled:ey,onClick:()=>eI("tools",[...y.tools.filter(e=>!fy.includes(e)),...n]),children:a(t)},t)})}),(0,d.jsx)(f$,{label:a("agents.tools"),children:(0,d.jsx)("div",{className:"agents-tool-options",children:[...fy,...y.tools.filter(e=>"powershell"===e)].map(e=>(0,d.jsx)(fI,{label:e,disabled:ey,checked:y.tools.includes(e),onChange:t=>eI("tools",t?[...y.tools,e]:y.tools.filter(t=>t!==e))},e))})}),(0,d.jsxs)(f$,{label:a("agents.resources"),children:[(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,d.jsx)(fI,{label:a("agents.loadSkills"),disabled:ey,checked:y.loadSkills,onChange:e=>eI("loadSkills",e)}),(0,d.jsx)(fI,{label:a("agents.loadExtensions"),disabled:ey,checked:y.loadExtensions,onChange:e=>eI("loadExtensions",e)}),(0,d.jsx)(fI,{label:a("agents.mcp"),disabled:ey||eT&&"on"!==y.mcp,checked:"on"===y.mcp,onChange:e=>eI("mcp",e?"on":"off")})]}),y.loadSkills&&void 0!==y.skills&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:y.skills.length>0?a("agents.skillsOnly",{skills:y.skills.join(", ")}):a("agents.skillsNone")}),y.loadExtensions&&void 0!==y.extensions&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere"},children:y.extensions.length>0?a("agents.extensionsOnly",{extensions:y.extensions.join(", ")}):a("agents.extensionsNone")}),!ey&&eT?(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:a("agents.mcpChatOnly")}):"on"===y.mcp&&(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:a("agents.mcpHint")})]})]}),(0,d.jsxs)("section",{className:"agents-profile-section",children:[(0,d.jsx)("h4",{children:a("agents.runtime")}),(0,d.jsxs)("div",{className:"agents-runtime-grid",children:[(0,d.jsx)(f$,{label:a("agents.model"),children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsx)(cT,{options:eo,value:eE,onChange:(e,t)=>eI("model",`${e}/${t}`),onClear:()=>eI("model",void 0),emptyLabel:m?a("agents.modelsLoading"):a("agents.inherit"),selectedLabel:y.model&&!eN?a("agents.modelUnavailable",{model:y.model}):y.model!==eC?y.model:void 0,disabled:ey||m||0===p.length&&!y.model,ariaLabel:a("agents.model"),variant:"field",placement:"auto"}),g&&(0,d.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:g})]})}),(0,d.jsx)(f$,{label:a("agents.thinking"),children:(0,d.jsx)("select",{"aria-label":a("agents.thinking"),value:y.thinking??"",disabled:ey,onChange:e=>eI("thinking",e.target.value||void 0),style:eM,children:fw.map(e=>(0,d.jsx)("option",{value:e,children:e||a("agents.inherit")},e||"default"))})}),(0,d.jsx)(f$,{label:a("agents.maxTurns"),children:(0,d.jsx)("input",{"aria-label":a("agents.maxTurns"),placeholder:a("agents.unlimited"),type:"number",min:1,step:1,value:y.maxTurns??"",disabled:ey,onChange:e=>eI("maxTurns",e.target.value?Number(e.target.value):void 0),style:eM})})]}),(0,d.jsxs)("details",{className:"agents-advanced",children:[(0,d.jsx)("summary",{children:a("agents.advanced")}),(0,d.jsx)(f$,{label:a("agents.codemode"),children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,d.jsxs)("select",{"aria-label":a("agents.codemode"),value:y.codemode??"off",disabled:ey,onChange:e=>eI("codemode",e.target.value),style:{...eM,width:"auto",minWidth:180,alignSelf:"flex-start"},children:[(0,d.jsx)("option",{value:"inherit",children:a("agents.codemode.inherit")}),(0,d.jsx)("option",{value:"on",children:a("agents.codemode.on")}),(0,d.jsx)("option",{value:"off",children:a("agents.codemode.off")})]}),(0,d.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,lineHeight:1.4},children:a("agents.codemodeHint")})]})}),(0,d.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,d.jsx)(fI,{label:a("agents.inheritContext"),disabled:ey,checked:y.inheritContext,onChange:e=>eI("inheritContext",e)}),(0,d.jsx)(fI,{label:a("agents.background"),disabled:ey,checked:y.runInBackground,onChange:e=>eI("runInBackground",e)})]})]})]})]})]}):(0,d.jsx)(mx,{children:a("agents.empty")})})})]}),(0,d.jsx)(mb,{status:et||U?(0,d.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:et||U}):(0,d.jsx)("span",{role:"status",children:ef&&!ev?a("agents.invalidDraft"):ex?a("agents.unsaved"):D?a("i18n.saved"):ef?a("agents.saveHint"):a("agents.viewHint")}),children:ef&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(mw,{onClick:()=>{let e=ea??o.find(e=>fN(e)===M.current)??o[0];e?eu(e):(A("view"),b(null)),_(!1),T()},disabled:W||B,children:a("i18n.cancel")}),(0,d.jsxs)(mw,{variant:"primary",type:"submit",form:"agents-profile-form",disabled:W||B||!ev||!eg&&!ex,className:D?"is-success":void 0,children:[D&&(0,d.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,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,d.jsx)("span",{children:D?a("i18n.saved"):W?a("agents.saving"):a("agents.save")})]})]})}),S&&(0,d.jsx)(fR,{onCancel:()=>C(null),onConfirm:()=>{C(null),S()}}),N&&ea&&(0,d.jsx)(fR,{deleteName:ea.displayName,onCancel:()=>E(!1),onConfirm:()=>{E(!1),em()}})]})})}let fL=["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"];function fP(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function fz(e){return`${e.scope}\0${e.source}`}function fO(e){return`extension\0${e.path}`}function fW(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function fF(e,t){return t(`plugins.status.${e}`)}function fD(e){return`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`}function f_(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function fB(e){let{pkg:t}=e,{t:n}=(0,ns.s)(),r=[["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===r.length?(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n("i18n.noResolvedResources")}):(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:r.map((e,t)=>(0,d.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,d.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,d.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.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,d.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 fH(e){let{cwd:t,source:n,scope:r,projectResourcesLoaded:i,busy:s,actionError:l,onSourceChange:a,onScopeChange:o,onInstall:c}=e,{t:u}=(0,ns.s)();return(0,d.jsx)(mm,{title:u("i18n.addPlugin"),catalogs:[{href:"https://pi.dev/packages",label:"pi.dev/packages",icon:(0,d.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",children:[(0,d.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,d.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]})}],target:(0,d.jsx)(mp,{value:r,label:u("config.saveTo"),options:[{value:"global",label:fW("global",u)},{value:"project",label:fW("project",u),disabled:!i}],path:"project"===r?`${tS(t)}/.pi/{npm,git}`:"~/.pi/agent/{npm,git}",disabledReason:u("trust.projectScopeUnavailable"),onChange:o}),inputLabel:u("config.source"),inputId:"plugin-source",placeholder:"npm:@scope/package",value:n,canSubmit:!s&&!!n.trim(),normalizeValue:fP,onValueChange:a,onSubmit:c,examplesLabel:u("config.examples"),examples:fL,error:l,children:(0,d.jsx)(mw,{variant:"primary",onClick:c,disabled:s||!n.trim(),className:"is-pushed-right",children:u(s?"i18n.installing":"i18n.install")})})}function fU(e){let t,n,{pkg:r,cwd:i,busyKey:s,actionError:l,actionMessage:a,sessionId:o,updateStatus:c,checkingUpdate:p,updateError:h,onAction:m,onCheckUpdate:f,onReloadSession:g}=e,{t:x}=(0,ns.s)(),v=fz(r),b=(s?.endsWith(v)||s?.startsWith("bulk:"))??!1,y="reload"===s,w=!r.disabled,j=r.canCheckForUpdates,k=c?.state==="update-available",S=r.description?.trim(),C=(0,u.useId)();return(0,d.jsxs)(mt,{children:[(0,d.jsxs)("div",{className:"config-detail-heading",children:[(0,d.jsxs)(mn,{className:"is-top-aligned",children:[(0,d.jsxs)(mr,{children:[(0,d.jsx)(md,{scope:r.scope,children:fW(r.scope,x)}),!r.disabled&&r.filtered&&(0,d.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:x("i18n.filtered")}),(0,d.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.source})]}),(0,d.jsxs)(mi,{children:[(0,d.jsx)(mw,{size:"small",variant:k?"primary":void 0,onClick:k||!j?()=>m("update",r):f,disabled:b||y||p,title:k?x("i18n.updateAvailable"):void 0,children:x(s===`update:${v}`?"i18n.updating":p?"i18n.checking":k||!j?"i18n.update":"i18n.check")}),(0,d.jsx)(mw,{size:"small",onClick:g,disabled:!o||y||b,"aria-describedby":o?void 0:C,children:x(y?"i18n.reloading":"i18n.reloadSession")}),(0,d.jsx)(mw,{variant:"danger",size:"small",onClick:()=>m("remove",r),disabled:b||y,children:x(s===`remove:${v}`?"i18n.removing":"i18n.remove")}),(0,d.jsx)(mj,{checked:w,loading:b||y,onChange:()=>m(r.disabled?"enable":"disable",r),label:x(r.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),!o&&(0,d.jsx)("div",{id:C,className:"config-detail-heading-note",children:x("i18n.openSessionToReload")})]}),(0,d.jsxs)(mo,{children:[S&&(0,d.jsx)(mc,{label:x("i18n.description"),children:S}),(0,d.jsx)(mc,{label:x("i18n.status"),tone:"plain",style:{color:f_(r.status),textTransform:"capitalize"},children:fF(r.status,x)}),(0,d.jsxs)(mc,{label:x("i18n.version"),tone:"plain",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,d.jsxs)("div",{className:"skill-version-row",children:[(0,d.jsx)("span",{className:"skill-version-value",children:(t=[],r.version&&t.push(x("i18n.installedVersion",{version:r.version})),r.configuredVersion&&t.push(x("i18n.configuredVersion",{version:r.configuredVersion})),t.length?t.join(" \xb7 "):x("i18n.unknown"))}),k&&(0,d.jsx)("span",{className:"skill-version-value is-update",title:c.displayName,children:x("i18n.updateAvailable")}),j&&(p||c&&!k)&&(0,d.jsx)("span",{className:`skill-update-status ${p?"is-checking":c?.state==="up-to-date"?"is-success":c?.state==="error"?"is-error":"is-muted"}`,children:p?x("i18n.checking"):c?.state==="up-to-date"?x("i18n.upToDate"):c?.state==="unsupported"?x("i18n.automaticChecksUnavailable"):c?.message||x("i18n.checkFailed")})]}),h&&(0,d.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:h})]}),!(r.packageName&&r.source.endsWith(r.packageName))&&(0,d.jsx)(mc,{label:x("i18n.package"),mono:!0,children:r.packageName??x("i18n.unknown")}),!r.disabled&&(0,d.jsx)(mc,{label:x("i18n.resources"),children:(n=[r.counts.extensions?x("i18n.resourceCount",{count:r.counts.extensions,label:x("i18n.extensionShort")}):"",r.counts.skills?x("i18n.resourceCount",{count:r.counts.skills,label:x("i18n.skillShort")}):"",r.counts.prompts?x("i18n.resourceCount",{count:r.counts.prompts,label:x("i18n.promptShort")}):"",r.counts.themes?x("i18n.resourceCount",{count:r.counts.themes,label:x("i18n.themeShort")}):""].filter(Boolean)).length?n.join(" \xb7 "):x("i18n.noResources")}),(0,d.jsx)(mc,{label:x("i18n.installedPath"),tone:r.installedPath?"muted":"error",mono:!0,children:r.installedPath?tS(r.installedPath):x("i18n.notFound")}),(0,d.jsx)(mc,{label:x("i18n.cwd"),tone:"dim",mono:!0,children:tS(i)})]}),!r.disabled&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,d.jsx)(ml,{children:x("i18n.resolvedResources")}),(0,d.jsx)(fB,{pkg:r})]}),a&&(0,d.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),l&&(0,d.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:l})]})}function fK(e){let{extension:t}=e,{t:n}=(0,ns.s)(),r=t.enabled?"loaded":"disabled";return(0,d.jsxs)(mt,{children:[(0,d.jsx)(mn,{children:(0,d.jsxs)(mr,{children:[(0,d.jsx)(md,{scope:t.scope,children:fW(t.scope,n)}),(0,d.jsx)(ms,{children:t.name})]})}),(0,d.jsxs)(mo,{children:[(0,d.jsx)(mc,{label:n("i18n.status"),tone:"plain",style:{color:t.enabled?"var(--accent)":"var(--text-dim)"},children:fF(r,n)}),(0,d.jsx)(mc,{label:n("i18n.installedPath"),mono:!0,children:tS(t.path)})]})]})}function fq(e){var t;let{cwd:n,sessionId:r,onClose:i,onReloaded:s,embedded:l=!1,trust:a}=e,{t:o}=(0,ns.s)(),[c,p]=(0,u.useState)(null),[h,m]=(0,u.useState)(!0),[f,g]=(0,u.useState)(null),[x,v]=(0,u.useState)(()=>hC("plugins",n)),[b,y]=(0,u.useState)(!1),[w,j]=(0,u.useState)(""),[k,S]=(0,u.useState)("global"),[C,N]=(0,u.useState)(null),[E,M]=(0,u.useState)(null),[$,I]=(0,u.useState)(null),[T,R]=(0,u.useState)(null),[A,L]=(0,u.useState)({}),[P,z]=(0,u.useState)(new Set),[O,W]=(0,u.useState)(!1),[F,D]=(0,u.useState)(null),[_,B]=(0,u.useState)(!1),H=(0,u.useMemo)(()=>c?.packages??[],[c?.packages]),U=(0,u.useMemo)(()=>c?.standaloneExtensions??[],[c?.standaloneExtensions]),K=H.find(e=>fz(e)===x)??null,q=U.find(e=>fO(e)===x)??null,V=c?.projectResourcesLoaded??!0,Z=(0,u.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:H.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[H]),J=(0,u.useCallback)(async()=>{m(!0),g(null),R(null);try{let e=await fetch(`/api/plugins?cwd=${encodeURIComponent(n)}`),t=await nE(e);p(t),y(e=>0===t.packages.length&&0===t.standaloneExtensions.length||e),v(e=>e&&(t.packages.some(t=>fz(t)===e)||t.standaloneExtensions.some(t=>fO(t)===e))?e:t.packages[0]?fz(t.packages[0]):t.standaloneExtensions[0]?fO(t.standaloneExtensions[0]):null)}catch(e){g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[n]);(0,u.useEffect)(()=>{L({}),D(null),J()},[n]);let Y=fd(a),G=(0,u.useRef)(Y);(0,u.useEffect)(()=>{G.current!==Y&&(G.current=Y,J())},[Y,J]),(0,u.useEffect)(()=>{x&&hN("plugins",x,n)},[n,x]);let X=(0,u.useCallback)(async e=>{let t=(e?[e]:H.filter(e=>e.canCheckForUpdates)).map(fz);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 nE(t);L(e=>{let t={...e};for(let e of r.updates??[])t[fz(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,u.useCallback)(async()=>{B(!0),M(null),I(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 nE(e);p(t),L({}),I(o("i18n.packagesUpdated")),r&&I(`${o("i18n.packagesUpdated")} ${o("agents.reloadRequired")}`)}catch(e){M(e instanceof Error?e.message:String(e))}finally{B(!1)}},[n,r,o]),ee=(0,u.useCallback)(async(e,t)=>{let r=fz(t);N(`${e}:${r}`),M(null),I(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 nE(i);if(p(s),"remove"===e)v(s.packages[0]?fz(s.packages[0]):s.standaloneExtensions[0]?fO(s.standaloneExtensions[0]):null),0===s.packages.length&&0===s.standaloneExtensions.length&&y(!0),I(o("i18n.packageRemoved")),L(e=>{let t={...e};return delete t[r],t});else{let t={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabled"),enable:o("i18n.packageEnabled")};I(t[e]),"update"===e&&L(e=>{let t={...e};return delete t[r],t})}}catch(e){M(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,o]),et=(0,u.useCallback)(async(e,t,i)=>{let s=fc(t,i,e=>!e.disabled,e=>e.filtered),l=i?0:t.filter(e=>!e.disabled&&e.filtered).length,a=l>0?o("plugins.bulkKeptFiltered",{count:l}):void 0;if(M(null),I(null),R(a?{scope:e,note:a}:null),0!==s.length){N(`bulk:${e}`);try{let t=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:i?"enable":"disable",cwd:n,packages:s.map(t=>{let{source:n}=t;return{source:n,scope:e}})})}),l=await nE(t);if(!l.results)throw Error(`HTTP ${t.status}`);let{results:c,...d}=l;p(d);let u=c.filter(e=>e.error);if(u.length<c.length){let e=i?o("plugins.bulkEnabled"):o("plugins.bulkDisabled");I(r?`${e} ${o("agents.reloadRequired")}`:e)}u.length>0&&R({scope:e,note:a,error:[o("plugins.bulkFailed",{count:u.length,total:c.length}),...u.map(e=>`${e.source}: ${e.error}`)].join("\n")})}catch(t){R({scope:e,note:a,error:t instanceof Error?t.message:String(t)})}finally{N(null)}}},[n,r,o]),en=(0,u.useCallback)(async()=>{let e=fP(w).trim();if(!e)return;j(e);let t=`${k}\0${e}`;N(`install:${t}`),M(null),I(null),R(null);try{var r;let i,s,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:e,scope:k,cwd:n})}),a=await nE(l);p(a);let c=(r=a.packages,s=(i=e.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===k&&e.source===i)??r.find(e=>e.scope===k&&e.source===`npm:${s}`)??r.find(e=>e.scope===k&&e.source.endsWith(i)));v(c?fz(c):t),y(!1),j(""),I(o("i18n.packageInstalled"))}catch(e){M(e instanceof Error?e.message:String(e))}finally{N(null)}},[n,k,w,o]),er=(0,u.useCallback)(async()=>{if(r){N("reload"),M(null),I(null),R(null);try{await dA(r,{type:"reload"}),s?.(),await J(),I(o("i18n.sessionReloaded"))}catch(e){M(e instanceof Error?e.message:String(e))}finally{N(null)}}},[J,s,r,o]),ei=C?.startsWith("install:")??!1,es=Object.values(A).filter(e=>"update-available"===e.state).length,el=H.some(e=>e.canCheckForUpdates),ea=h||null!==C||P.size>0||_;return(0,d.jsxs)(hX,{embedded:l,title:o("common.plugins"),subtitle:tS(n),closeLabel:o("i18n.close"),onClose:i,children:[!V&&(0,d.jsx)(mg,{message:o("trust.pluginsNotLoaded")}),(0,d.jsxs)(h4,{children:[(0,d.jsxs)(h3,{children:[(0,d.jsx)(h8,{children:h?(0,d.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")}):f?(0,d.jsx)("div",{className:"config-sidebar-message is-error",children:f}):0===H.length&&0===U.length?(0,d.jsx)("div",{className:"config-sidebar-message is-empty",children:o("i18n.noPlugins")}):(0,d.jsxs)(d.Fragment,{children:[U.length>0&&(0,d.jsxs)("div",{className:"config-sidebar-group",children:[(0,d.jsx)(h6,{children:o("i18n.extensions")}),U.map(e=>{let t=fO(e);return(0,d.jsxs)(h7,{active:!b&&x===t,title:e.path,onClick:()=>{v(t),y(!1),M(null),I(null)},children:[(0,d.jsx)(mS,{active:e.enabled}),(0,d.jsx)(me,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),Z.map(e=>{let t=e.packages.filter(e=>!e.disabled).length,n=t===e.packages.length;return(0,d.jsxs)("div",{className:"config-sidebar-group",children:[(0,d.jsx)(h6,{aside:(0,d.jsx)(h5,{enabled:t,total:e.packages.length,disabled:ea,loading:C===`bulk:${e.scope}`,label:o(n?"plugins.groupSwitchOn":"plugins.groupSwitchOff",{group:fW(e.scope,o)}),onChange:t=>void et(e.scope,e.packages,t)}),children:fW(e.scope,o)}),T?.scope===e.scope&&(0,d.jsx)(h9,{error:T.error,note:T.note}),e.packages.map(e=>{let t=fz(e),n=!b&&x===t;return(0,d.jsxs)(h7,{active:n,title:e.description??e.source,onClick:()=>{v(t),y(!1),M(null),I(null)},children:[(0,d.jsx)(mS,{active:!e.disabled,color:f_(e.status)}),(0,d.jsx)(me,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),A[fz(e)]?.state==="update-available"&&(0,d.jsx)("span",{title:o("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope)})]})}),(0,d.jsx)(mk,{active:b,onClick:()=>{y(!0),M(null),I(null)},children:o("i18n.addPlugin")})]}),(0,d.jsx)(mv,{motionKey:b?"add":x??"",children:(0,d.jsx)(mt,{className:"is-fill",children:b?(0,d.jsx)(fH,{cwd:n,source:w,scope:k,projectResourcesLoaded:V,busy:ei,actionError:E,onSourceChange:j,onScopeChange:S,onInstall:en}):h?null:q?(0,d.jsx)(fK,{extension:q}):K?(0,d.jsx)(fU,{pkg:K,cwd:n,busyKey:C,actionError:E,actionMessage:$,sessionId:r,updateStatus:A[fz(K)],checkingUpdate:P.has(fz(K)),updateError:F,onAction:ee,onCheckUpdate:()=>void X(K),onReloadSession:er},fz(K)):(0,d.jsx)(mx,{children:o("i18n.selectPackage")})})})]}),(0,d.jsxs)(mb,{status:es>0?(0,d.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[es," ",1===es?o("i18n.update"):o("i18n.updates")]}):c?.diagnostics.length?(0,d.jsx)(my,{tone:c.diagnostics.some(e=>"error"===e.type)?"error":"warning",summary:1===c.diagnostics.length?o("plugins.diagnostic"):o("plugins.diagnostics",{count:c.diagnostics.length}),details:c.diagnostics.map(fD)}):(0,d.jsx)(my,{summary:c?[o("i18n.resourceCount",{count:(t=c.totals).extensions,label:o("i18n.extensionShort")}),o("i18n.resourceCount",{count:t.skills,label:o("i18n.skillShort")}),o("i18n.resourceCount",{count:t.prompts,label:o("i18n.promptShort")}),o("i18n.resourceCount",{count:t.themes,label:o("i18n.themeShort")})].join(" \xb7 "):""}),children:[!l&&(0,d.jsx)(mw,{onClick:i,children:o("i18n.close")}),el&&(0,d.jsx)(mw,{variant:es>0?"primary":"secondary",onClick:()=>void(es>0?Q():X()),disabled:ea,title:es>0?o("i18n.updateAllPluginsHint"):void 0,children:_?o("i18n.updating"):O?o("i18n.checking"):es>0?`${o("i18n.updateAllPlugins")} (${es})`:o("i18n.checkUpdates")}),(0,d.jsx)(mw,{variant:"secondary",onClick:()=>void J(),disabled:ea,children:o("i18n.refresh")})]})]})}let fV="\\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",fZ=RegExp(`[${fV}]`,"gu"),fJ=RegExp(`[${fV}]`,"u");function fY(e){return e.replace(fZ,e=>{let t=e.codePointAt(0)??0;return`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`})}let fG=/[\s"'`$|&;<>()*?#~]/;function fX(e){let t=fJ.test(e),n=fY(e);return""===n||t||fG.test(n)?`"${n.replace(/"/g,'\\"')}"`:n}function fQ(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return[e,...t].map(fX).join(" ")}function f0(e){let t=void 0!==e.command?fQ(e.command,e.args):void 0,n=void 0!==e.url?fY(e.url):void 0;return"http"===e.transport?n:"stdio"===e.transport?t:n??t}function f1(e){return[e.name,e.command,e.cwd,e.url,...e.args??[],...e.envNames,...e.headerNames].some(e=>void 0!==e&&fJ.test(e))}function f2(e){return"oauth-client-secret"===e.kind?{key:"mcp.field.oauthClientSecret"}:{key:"env"===e.kind?"mcp.field.env":"mcp.field.header",params:{name:fY(e.name??"")}}}function f4(e){return"http"===e.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables"}function f3(e){return e.length>0?{key:"mcp.server.overridesGlobal",params:{keys:e.join(", ")}}:{key:"mcp.server.overridesGlobalNothing"}}function f8(e){return e.flatMap(e=>{let{variables:t,...n}=e;return t.map(e=>({variable:e,field:n}))})}function f6(e,t){return"unparsable"===e.reason||"unreadable"===e.reason?fY(e.error):"link-outside"===e.reason?void 0===t?void 0:fY(t):void 0}function f5(e){let{server:t,cwd:n,onCancel:r,onSaved:i}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(null),[o,c]=(0,u.useState)({}),[p,h]=(0,u.useState)([]),[m,f]=(0,u.useState)(null),[g,x]=(0,u.useState)(!1),v=(0,u.useRef)(0),b=(0,u.useRef)(null),y=(0,u.useRef)(!0);(0,u.useEffect)(()=>{y.current=!0;let e=!1,r=new AbortController;b.current=r;let i=setTimeout(()=>r.abort(),15e3);return fetch("/api/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"read-edit",scope:t.scope,name:t.name,...n?{cwd:n}:{}}),signal:r.signal}).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.reason??"internal");e||r.signal.aborted||(a(n),h(n.names.map(e=>({id:v.current++,name:e,existing:!0,configured:n.values?.[e],action:"keep",value:""}))))}).catch(t=>{e||f("AbortError"===t.name?"network":t.message)}).finally(()=>clearTimeout(i)),()=>{e=!0,y.current=!1,r.abort(),b.current?.abort()}},[t.scope,t.name,n]);let w=p.some((e,t)=>"remove"!==e.action&&(!e.name.trim()||p.some((n,r)=>r!==t&&n.name===e.name)))||p.some(e=>"reference"===e.action&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.value)),j=Object.keys(o).length>0||p.some(e=>"keep"!==e.action),k=async()=>{if(!l||g||w||!j)return;let e={fields:o,values:p.filter(e=>"keep"!==e.action).map(e=>({name:e.name,action:e.action,..."remove"!==e.action?{value:e.value}:{}}))};x(!0),f(null);let r=new AbortController;b.current=r;let s=setTimeout(()=>r.abort(),15e3);try{let s=await fetch("/api/mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",scope:t.scope,name:t.name,version:l.version,patch:e,...n?{cwd:n}:{}}),signal:r.signal}),a=await s.json();if(!s.ok)throw Error(a.reason??"internal");y.current&&i()}catch(e){y.current&&f(e instanceof Error&&"AbortError"!==e.name?e.message:"network")}finally{clearTimeout(s),y.current&&x(!1)}},S=(e,t)=>h(n=>n.map(n=>n.id===e?{...n,...t}:n));return(0,d.jsxs)("section",{className:"mcp-edit","aria-label":s("mcp.edit.title"),children:[(0,d.jsx)("header",{className:"mcp-edit-heading",children:(0,d.jsxs)("div",{children:[(0,d.jsx)(md,{scope:t.scope,children:s("global"===t.scope?"skills.scope.global":"skills.scope.project")}),(0,d.jsxs)("h3",{children:[s("mcp.edit.title")," \xb7 ",fY(t.name)]})]})}),(0,d.jsx)("p",{className:"mcp-edit-hint",children:s("mcp.edit.hint")}),(0,d.jsx)("p",{className:"mcp-edit-path",children:t.sourcePath}),m&&(0,d.jsx)("p",{role:"alert",className:"mcp-config-line is-error",children:["config-changed","invalid-request","server-invalid","secret-global-only","network"].includes(m)?s(`mcp.edit.error.${m}`):s(`mcp.reason.${m}`)}),!l&&!m&&(0,d.jsx)("p",{children:s("i18n.loading")}),l&&(0,d.jsx)("form",{onSubmit:e=>{e.preventDefault(),k()},children:(0,d.jsxs)("fieldset",{disabled:g,children:[Object.entries(l.fields).map(e=>{let[t,n]=e,r=Object.hasOwn(o,t),i=r?o[t]:n.value;return(0,d.jsxs)("div",{className:"mcp-edit-field",children:[(0,d.jsx)("label",{htmlFor:`mcp-edit-${t}`,children:s(`mcp.edit.field.${t}`)}),n.hidden&&(0,d.jsxs)("label",{className:"mcp-edit-replace",children:[(0,d.jsx)("input",{type:"checkbox",checked:r,onChange:e=>c(n=>{let r={...n};return e.target.checked?r[t]="":delete r[t],r})}),s("mcp.edit.replaceHidden")]}),(!n.hidden||r)&&("args"===t||"description"===t?(0,d.jsx)("textarea",{id:`mcp-edit-${t}`,rows:"description"===t?3:4,value:i,spellCheck:"description"===t,onChange:e=>c({...o,[t]:e.target.value})}):(0,d.jsx)("input",{id:`mcp-edit-${t}`,value:i,autoComplete:"off",spellCheck:!1,onChange:e=>c({...o,[t]:e.target.value})})),"args"===t&&(0,d.jsx)("span",{className:"mcp-edit-hint",children:s("mcp.edit.argsHint")})]},t)}),(0,d.jsxs)("div",{className:"mcp-edit-values-heading",children:[(0,d.jsx)("h4",{children:s("http"===l.transport?"mcp.detail.headers":"mcp.detail.env")}),(0,d.jsx)(mw,{size:"small",onClick:()=>h([...p,{id:v.current++,name:"",existing:!1,action:"literal",value:""}]),children:s("mcp.edit.addValue")})]}),(0,d.jsx)("div",{className:"mcp-edit-values",children:p.map(e=>(0,d.jsxs)("div",{className:"mcp-edit-value",children:[(0,d.jsx)("input",{"aria-label":s("mcp.edit.valueName"),placeholder:s("mcp.edit.valueName"),value:e.name,readOnly:e.existing,onChange:t=>S(e.id,{name:t.target.value})}),(0,d.jsxs)("select",{"aria-label":s("mcp.edit.valueAction",{name:fY(e.name)}),value:e.action,onChange:t=>S(e.id,{action:t.target.value,value:""}),children:[e.existing&&(0,d.jsx)("option",{value:"keep",children:s("mcp.edit.keep")}),(0,d.jsx)("option",{value:"literal",children:s("mcp.edit.literal")}),(0,d.jsx)("option",{value:"reference",children:s("mcp.edit.reference")}),e.existing&&(0,d.jsx)("option",{value:"remove",children:s("mcp.edit.remove")})]}),"keep"===e.action&&(0,d.jsx)("input",{readOnly:!0,autoComplete:"off",spellCheck:!1,"aria-label":s("mcp.edit.currentValue",{name:fY(e.name)}),value:e.configured?.hidden===!1?e.configured.value:"",placeholder:s("mcp.edit.hiddenValue")}),("literal"===e.action||"reference"===e.action)&&(0,d.jsx)("input",{type:"literal"===e.action?"password":"text",autoComplete:"new-password","aria-label":s("mcp.edit.value",{name:fY(e.name)}),placeholder:s("reference"===e.action?"mcp.edit.variableName":"mcp.edit.newValue"),value:e.value,onChange:t=>S(e.id,{value:t.target.value})}),!e.existing&&(0,d.jsx)(mw,{size:"small",onClick:()=>h(p.filter(t=>t.id!==e.id)),children:s("i18n.remove")})]},e.id))}),w&&(0,d.jsx)("p",{className:"mcp-edit-hint",children:s("mcp.edit.valuesInvalid")}),(0,d.jsxs)("footer",{className:"mcp-edit-footer",children:[(0,d.jsx)(mw,{onClick:r,children:s("i18n.cancel")}),(0,d.jsx)(mw,{type:"submit",disabled:!j||w,children:s(g?"mcp.edit.saving":"mcp.edit.save")})]})]})}),!l&&(0,d.jsx)(mw,{onClick:r,children:s("i18n.cancel")})]})}let f9="codemode";function f7(e){return`${e.scope}\0${e.name}`}function ge(e){return e?.trust?.decision===!0}function gt(e){return"test"===e.origin?e.state:void 0!==e.closedAt||"not-trusted"===e.state?"on":e.state}function gn(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?gt(e.status):"on":"mcp-off":"not-trusted":"disabled"}let gr={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"},gi={connected:"mcp.state.session.connected",failed:"mcp.state.session.failed"};function gs(e,t){return(t?.origin==="session"?gi[e]:void 0)??gr[e]}let gl={disconnected:"mcp.stateDetail.disconnected",conflict:"mcp.stateDetail.conflict"},ga={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 go(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 gc(e){return"on"===e?{active:!0}:"off"===e?{active:!1}:{color:"error"===e?"#ef4444":"#f59e0b"}}function gd(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 gu={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"},gp={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"},gh={connecting:"off",connected:"on","needs-auth":"warning",failed:"error",disconnected:"warning",conflict:"error","not-trusted":"warning"},gm={codemode:"mcp.exposure.codemode",deferred:"mcp.exposure.deferred",direct:"mcp.exposure.direct",hidden:"mcp.exposure.hidden"},gf=["codemode","deferred","direct","hidden"],gg={codemode:"mcp.exposureShort.codemode",deferred:"mcp.exposureShort.deferred",direct:"mcp.exposureShort.direct",hidden:"mcp.exposureShort.hidden"};function gx(e){return"auto-enable-codemode-invalid"!==e.reason}function gv(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 gb(e){return{enabled:e.filter(e=>e.enabled).length,total:e.length}}function gy(e,t){let n=e.flatMap(e=>e.servers.map(f7));return t===f9||null!==t&&n.includes(t)?t:n[0]??null}function gw(e){let t=e?.trust;return void 0!==t&&t.requiresTrust&&!t.trusted}function gj(e){return e.projectOverride?.preference??e.preference}let gk={always:"mcp.codemode.projectOverride.always",automatic:"mcp.codemode.projectOverride.automatic"},gS={on:"mcp.codemode.toolMode.onDescription",only:"mcp.codemode.toolMode.onlyDescription"},gC={on:"mcp.codemode.toolMode.projectOverride.on",only:"mcp.codemode.toolMode.projectOverride.only"},gN={automatic:"mcp.codemode.automatic",always:"mcp.codemode.always",unavailable:"mcp.codemode.unavailable",unknown:"i18n.unknown"};function gE(e){return"unavailable"===e?"error":"unknown"===e?"off":"on"}let gM=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);async function g$(e,t,n,r){var i,s;let l,a,o,c,d;try{l=await n(e,{...t,cache:"no-store"})}catch(e){return{ok:!1,error:{error:e instanceof Error?e.message:String(e)}}}try{a=await l.json()}catch{return{ok:!1,error:{error:`HTTP ${l.status}`}}}let u=l.ok?r(a):void 0;return void 0!==u?{ok:!0,data:u}:{ok:!1,error:(i=a,s=l.status,c=(o=i??{}).breadth,d=o.trust,{error:"string"==typeof o.error?o.error:`HTTP ${s}`,..."string"==typeof o.reason?{reason:o.reason}:{},..."string"==typeof o.path?{path:o.path}:{},..."string"==typeof o.name?{name:o.name}:{},..."string"==typeof o.suggestedName?{suggestedName:o.suggestedName}:{},...gM(o.names)?{names:o.names}:{},...gM(o.fields)?{fields:o.fields}:{},...Array.isArray(o.notes)?{notes:o.notes.filter(e=>"string"==typeof e?.code)}:{},..."string"==typeof c?.kind&&"string"==typeof c.path?{breadth:c}:{},..."boolean"==typeof d?.requiresTrust&&"boolean"==typeof d.trusted?{trust:d}:{},...!0===o.trustKept?{trustKept:!0}:{}})}}function gI(e,t,n){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n}}async function gT(e,t,n,r){let i,{abortAtDeadline:s=!0}=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},l=new AbortController,a=()=>l.abort();r?.aborted?l.abort():r?.addEventListener("abort",a,{once:!0});let o=new Promise(e=>{i=setTimeout(()=>{e(t()),s&&l.abort()},n)});try{return await Promise.race([e(l.signal),o])}finally{clearTimeout(i),r?.removeEventListener("abort",a)}}function gR(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 gA(e,t,n){return g$(e?`/api/mcp?cwd=${encodeURIComponent(e)}`:"/api/mcp",{signal:n},t,e=>gR(e)?e:void 0)}let gL=new Set(["cwd-invalid","cwd-denied","cwd-not-directory"]);async function gP(e,t,n){let r=await gA(e,t,n);if(r.ok||!e||!r.error.reason||!gL.has(r.error.reason))return r;let i=await gA(null,t,n);return i.ok?{...i,projectError:r.error}:i}async function gz(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 gT(n=>gP(e,t,n),()=>({ok:!1,error:{error:`GET /api/mcp did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function gO(e,t,n,r){let i=await g$("/api/tools/settings",gI("PUT",e,r),n,e=>null!==e&&"object"==typeof e?t(e):void 0);return i.ok?{ok:!0,stored:i.data}:i}async function gW(e,t,n){let r=await gO({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 gF(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 gT(n=>gW(e,t,n),()=>({ok:!1,error:{error:`PUT /api/tools/settings did not answer within ${r} ms`,timedOut:!0}}),r,n)}async function gD(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 gT(async n=>{let r=await gO({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 g_(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 gT(async n=>{let r=await gO({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 gB(e){return!e.available&&"builtin-disabled"!==e.reason}function gH(e,t){if(gB(t.mcp))return"mcp-off";if("project"===e){if(!t.project?.trust)return"trust-unreadable";if(!ge(t.project))return"project-untrusted"}}let gU={"mcp-off":"mcp.readOnly.mcp-off","project-untrusted":"mcp.readOnly.project-untrusted","trust-unreadable":"mcp.readOnly.trust-unreadable"};function gK(e){return!0!==e.notAnObject}function gq(e){return gK(e)&&void 0===e.webPasswordField}async function gV(e,t,n){return g$("/api/mcp",gI("POST",e,n),t,e=>gR(e)?e:void 0)}async function gZ(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 gT(e=>gV(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp did not answer within ${i} ms`,timedOut:!0}}),i,r)}let gJ={"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 gY(e,t){let n=gH(e.scope,t);return n||(void 0===e.invalidError&&e.validated?e.webPasswordField?"web-password":void 0:"invalid")}let gG={"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"},gX={connected:"mcp.test.state.connected","needs-auth":"mcp.test.state.needs-auth",failed:"mcp.test.state.failed",timedOut:"mcp.test.state.timedOut"},gQ={connected:"mcp.test.summary.connected","needs-auth":"mcp.test.summary.needs-auth",failed:"mcp.test.summary.failed",timedOut:"mcp.test.summary.timedOut"},g0={connected:"mcp.signIn.summary.connected","needs-auth":"mcp.signIn.summary.needs-auth",failed:"mcp.signIn.summary.failed",timedOut:"mcp.signIn.summary.timedOut"};function g1(e){return(Math.max(0,e)/1e3).toFixed(1)}async function g2(e,t,n){return g$("/api/mcp/test",gI("POST",e,n),t,e=>!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}(e)?void 0:e)}async function g4(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 gT(e=>g2(s,n,e),()=>({ok:!1,error:{error:`POST /api/mcp/test did not answer within ${i} ms`,timedOut:!0}}),i,r,{abortAtDeadline:!1})}let g3="•••",g8=new Set(["key","apikey","token","secret","password","passwd","passphrase","pwd","pass","credential","credentials","authorization","bearer","jwt","cookie","signature","pat"]),g6=new Set([...g8,"auth","sig","code","pw"]),g5=["token","secret","password","passwd","apikey"],g9=new Set(["file","path","dir","url","uri","endpoint","id","name","type","header","env","var","length","ttl","expiry","expires","timeout","mode","format"]),g7=new Set(["-k"]);function xe(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 xt(e,t){let n=xe(e);return!(n.length>1&&g9.has(n[n.length-1]))&&n.some(e=>t.has(e)||g5.some(t=>e.length>t.length&&e.endsWith(t)))}function xn(e){return xt(e,g8)}let xr=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,})"),xi=/^eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*$/,xs=/^[A-Za-z0-9_\-+/=.~]+$/;function xl(e){return!(/\s/.test(e)||xu(e))&&(!!(xr.test(e)||xi.test(e))||!(e.length<24||!xs.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 xa=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Za-z_][A-Za-z0-9_]*/,xo=RegExp(xa.source,"g"),xc=/^(?:bearer|basic|token)\s+/i;function xd(e,t,n){let r=e.replace(xc,"");return t.test(r)&&/^[^A-Za-z0-9]*$/.test(r.replace(n,""))}function xu(e){return xd(e.replace(/\$[$!]/g,"_x"),xa,xo)}let xp=/\$\{[A-Za-z_][A-Za-z0-9_]*\}|\$[A-Z_][A-Z0-9_]*(?![A-Za-z0-9_])/,xh=RegExp(xp.source,"g");function xm(e){return xd(e,xp,xh)}function xf(e,t){if(!e||""===t)return;e.push(t);let n=xv(t);n!==t&&e.push(n)}let xg=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#]*)/;function xx(e,t,n){let r=!1,i=e,s="",l=xg.exec(e);if(l){let[a,o,c]=l,d=c.lastIndexOf("@");if(d>=0&&!t(xv(c.slice(0,d)))){s=`${o}${g3}${c.slice(d)}`,r=!0;let e=c.slice(0,d);xf(n,e);let t=e.indexOf(":");t>=0&&xf(n,e.slice(t+1))}else s=a;i=e.slice(a.length)}let a=i.search(/[?#]/),o=a<0?i:i.slice(0,a),c=a<0?"":i.slice(a),d=o.split("/").map(e=>xl(xv(e))?(r=!0,xf(n,e),g3):e).join("/");return c=c.replace(/([?&#;])([^&#;]*)/g,(e,i,s)=>{let l=s.indexOf("=");if(l<0){let l=xv(s);return!xl(l)||t(l)?e:(r=!0,xf(n,s),`${i}${g3}`)}let a=s.slice(0,l),o=xv(s.slice(l+1));return""===o||t(o)||!function(e){let t=e;try{t=decodeURIComponent(e)}catch{}return xt(t,g6)}(a)&&!xl(o)?e:(r=!0,xf(n,s.slice(l+1)),`${i}${a}=${g3}`)}),{value:`${s}${d}${c}`,masked:r}}function xv(e){try{return decodeURIComponent(e)}catch{return e}}let xb=/^(\s*[A-Za-z][A-Za-z0-9 _.-]*=)([\s\S]*)$/;function xy(e,t,n){let r=/^([A-Za-z0-9_-]+):(\s*)([\s\S]*)$/.exec(e);if(r&&""!==r[3]&&!r[3].startsWith("//")&&xn(r[1])){let[,i,s,l]=r;return t(l)?{value:e,masked:!1}:(xf(n,l.trim()),{value:`${i}:${s}${g3}`,masked:!0})}let i=e.includes(";")?function(e,t,n){let r=e.split(";");if(r.length<2||!r.every(e=>""===e.trim()||xb.test(e)))return;let i=!1;return{value:r.map(e=>{let r=xb.exec(e);if(!r)return e;let[,s,l]=r;if(""===l.trim()||t(l))return e;if(xn(s.slice(0,-1).trim()))return i=!0,xf(n,l.trim()),`${s}${g3}`;let a=xy(l,t,n);return i||=a.masked,`${s}${a.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]&&xn(s[1]))return t(s[2])?{value:e,masked:!1}:(xf(n,s[2]),{value:`${s[1]}=${g3}`,masked:!0});if(/\s/.test(e)){var l,a,o;let r,i;return l=e,a=t,o=n,i=xk((r=l.split(/(\s+)/)).filter((e,t)=>t%2==0),a,!0,o),{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 xx(e,t,n);if(s&&""!==s[2]){let e=xy(s[2],t,n);return{value:`${s[1]}=${e.value}`,masked:e.masked}}return xl(e)&&!t(e)?(xf(n,e),{value:g3,masked:!0}):{value:e,masked:!1}}function xw(e){if(g7.has(e))return!0;if(!/^--?[A-Za-z]/.test(e))return!1;let t=e.replace(/^-+/,"");return xn(t)||"auth"===xe(t).at(-1)}let xj=/^(?:bearer|basic|token)$/i;function xk(e,t,n,r){let i=!1,s=!1;return{values:e.map(e=>{if(""===e)return e;if(s){if(n&&xj.test(e))return e;if(s=!1,!/^-[A-Za-z-]/.test(e))return t(e)?e:(i=!0,xf(r,e),g3)}let l=/^(--?[A-Za-z][A-Za-z0-9_.-]*)=([\s\S]*)$/.exec(e);if(l){let[,e,n]=l;if(""!==n&&xw(e)&&!t(n))return i=!0,xf(r,n),`${e}=${g3}`;let s=xy(n,t,r);return i||=s.masked,`${e}=${s.value}`}if(/^--?[A-Za-z][A-Za-z0-9_.-]*$/.test(e))return s=xw(e),e;if(n){let t=/^([A-Za-z0-9_-]+):$/.exec(e);if(xj.test(e)||t&&xn(t[1]))return s=!0,e}let a=xy(e,t,r);return i||=a.masked,a.value}),masked:i}}function xS(e){let{values:t,masked:n}=xk(e,xm,!1);return{args:t,masked:n}}function xC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xN(e){return!e.startsWith("!")&&!xu(e)}function xE(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 xM={"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(xM);let x$={dollarBrace:!1,bareDollar:!1,percent:!1,braceEnv:!1},xI={dollarBrace:!0,bareDollar:!1,percent:!0,braceEnv:!0},xT={...xI,bareDollar:!0},xR={...x$,braceEnv:!0},xA=/^[A-Za-z_][A-Za-z0-9_]*$/,xL=/\$\{([^{}]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([A-Za-z_][A-Za-z0-9_]*)%|\{(env|file):([^{}]*)\}/g;function xP(e,t){if(!t)return;let n=e[e.length-1];n?.kind==="text"?n.text+=t:e.push({kind:"text",text:t})}function xz(e,t,n){let r=[],i=0;xL.lastIndex=0;for(let s=xL.exec(e);s;s=xL.exec(e)){let[l,a,o,c,d,u]=s,p=l;if(void 0!==a&&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(xA.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}(a,l);else if(void 0!==o&&t.bareDollar)p={kind:"env",name:o,from:l};else if(void 0!==c&&t.percent&&n)p={kind:"env",name:c,from:l};else if(void 0!==d&&t.braceEnv)p="env"===d&&xA.test(u)?{kind:"env",name:u,from:l}:{kind:"unsupported",from:l};else if(void 0!==c||void 0!==d){xP(r,e.slice(i,s.index+1)),i=s.index+1,xL.lastIndex=s.index+1;continue}xP(r,e.slice(i,s.index)),"string"==typeof p?xP(r,p):r.push(p),i=s.index+l.length}return xP(r,e.slice(i)),r}function xO(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 xW(e){return e.startsWith("!")}function xF(e){if(xW(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);xA.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 xD=/<[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,x_=/^(?:\.\.\.|…|\*{3,}|x{3,}|TODO|FIXME|changeme|change[-_]me|replace[-_]?me|placeholder|redacted|\[[^\]]+\])$/i,xB=/(?:^|[\\/])(?:path[\\/]to(?:[\\/]|$)|Users[\\/](?:username|yourname|your[-_][A-Za-z_-]+|user[-_]?name|<[^>]+>)(?:[\\/]|$)|home[\\/](?:username|yourname|your[-_][A-Za-z_-]+|<[^>]+>)(?:[\\/]|$))/i,xH=/^(Bearer|Basic|Token|Bot|ApiKey|Api-Key)\s+(.+)$/i;function xU(e){return e.join("\0")}function xK(e){return"args"===e[0]?`args[${e[1]}]`:e.join(".")}function xq(e){return"env"===e[0]||"headers"===e[0]||"oauth"===e[0]&&"clientSecret"===e[1]}function xV(e){return"command"===e[0]||"args"===e[0]||"cwd"===e[0]}let xZ=new Set(["HOME","USERPROFILE"]);class xJ{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 xY(e){return e.map(e=>"text"in e?e.text:e.from).join("")}let xG=/\$\{[^{}]*\}/g,xX=new Set(["variable","home","workspace-basename","unsupported-variable","input"]);class xQ{constructor(e){this.draft=e,this.fields=new Map,this.argTexts=e.args.map(xY),this.urlText=xY(e.url??[])}encode(e,t){let n,r=xq(e),i=xK(e),s=xY(t),l=[],a=!1,o=()=>l.every(e=>""===e),c=e=>{if(!r)return void l.push(e);let t=/\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e);t&&this.draft.note("bare-dollar-literal",{field:i,name:t[1]});let n=xO(e,{atStart:o()});n!==e&&(a=!0),l.push(n)},d=e=>l.push(e),u=e=>l.push({field:e});if(!r&&xV(e)&&1===t.length&&"text"in t[0]&&xB.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(xB.test(n))return t&&d(t),u(this.field(e,"placeholder-path",n,n,"text")),this.target(e,l,void 0)}let p=0;return t.forEach((l,a)=>{let h=t[a+1],m=void 0===h||"text"in h&&/^[\\/]/.test(h.text),f=(t,r,i)=>{let l=0;for(let[c,d]of function(e){let t=e.trim();if(x_.test(t)){let n=e.indexOf(t);return[[n,n+t.length]]}let n=xH.exec(t);if(n&&x_.test(n[2].trim())){let t=e.lastIndexOf(n[2].trim());return[[t,t+n[2].trim().length]]}let r=[];xD.lastIndex=0;for(let t=xD.exec(e);t;t=xD.exec(e))/^your[-_]/.test(t[0])&&/[@/]/.test(e[t.index-1]??"")||r.push([t.index,t.index+t[0].length]);return r}(t)){var a,o;if(i.some(e=>{let[t,n]=e;return c<n&&d>t}))continue;c>l&&r(t.slice(l,c)),"url"===e[0]&&x0(s,p+c)&&(n="uri-component");let h=t.slice(c,d);u(this.field(e,"placeholder",(a=e,o=h,"env"===a[0]||"headers"===a[0]?a[1]:o.replace(/^[<{\s]+|[>}\s]+$/g,"")||xK(a)),h)),l=d}l<t.length&&r(t.slice(l))};switch(l.kind){case"text":f(l.text,c,[]);break;case"pi":{var g;let e=h?(g=l.text,(/\$+$/.exec(g)?.[0].length??0)%2==1?`${g}$`:g):l.text;if(r&&o()&&xW(e)){this.draft.note("shell-command-value",{field:i}),d(e);break}let t=[...e.matchAll(xG)].map(e=>[e.index,e.index+e[0].length]);f(e,d,t);break}case"env":r?(d(`$\{${l.name}}`),void 0!==l.fallback&&this.draft.note("variable-fallback-dropped",{field:i,name:l.name,fallback:l.fallback}),l.shell?this.draft.note("shell-variable",{field:i,name:l.name}):l.from!==`$\{${l.name}}`&&this.draft.note("variable-translated",{field:i,from:l.from,to:`$\{${l.name}}`})):xV(e)&&o()&&xZ.has(l.name)&&m?(d("~"),this.draft.note("home-translated",{field:i,from:l.from})):(u(this.field(e,"variable",l.name,l.from,void 0,l.fallback)),this.draft.note(l.shell?"shell-variable":"variable-unsupported-here",{field:i,name:l.name}));break;case"input":u(this.inputField(e,l));break;case"home":r?(d("${HOME}"),this.draft.note("home-variable-translated",{field:i,from:l.from,to:"${HOME}"})):xV(e)&&o()&&m?(d("~"),this.draft.note("home-translated",{field:i,from:l.from})):u(this.field(e,"home","userHome",l.from,"text"));break;case"workspace":"url"===e[0]||"oauth"===e[0]?u(this.field(e,"variable","workspaceFolder",l.from,"text")):(d("."),this.draft.note("workspace-folder-relative",{field:i,from:l.from}));break;case"workspace-basename":u(this.field(e,"workspace-basename","workspaceFolderBasename",l.from,"text"));break;case"unsupported":u(this.field(e,"unsupported-variable",l.from,l.from)),this.draft.note("unsupported-variable",{field:i,variable:l.from});break;case"prompt":"url"===e[0]&&x0(s,p)&&(n="uri-component"),u(this.promptField(e,l))}p+=("text"in l?l.text:l.from).length}),a&&this.draft.note("escaped-value",{field:i}),this.target(e,l,n)}target(e,t,n){let r=t.filter(e=>""!==e);for(let t of new Set(r.flatMap(e=>"string"==typeof e?[]:[e.field]))){let i=this.fields.get(t);i.targets.some(t=>xU(t.path)===xU(e))||i.targets.push({path:e,parts:r,...n?{encoding:n}:{}})}return r.map(e=>"string"==typeof e?e:this.fields.get(e.field).placeholder??"").join("")}field(e,t,n,r,i,s){let l=xX.has(t)?`${t}.${n}`:xK(e);if(xX.has(t)){if(this.fields.has(l))return l}else for(let t=2;this.fields.has(l);t++)l=`${xK(e)}#${t}`;let a=this.isSecretContext(e,r)||xn(n),o="headers"===e[0]&&"authorization"===e[1].toLowerCase();return this.fields.set(l,{id:l,kind:i??(a?"password":"text"),reason:t,label:n,placeholder:r,...void 0!==s?{defaultValue:s}:{},..."placeholder"===t&&o?{optional:!0}:{},targets:[]}),l}inputField(e,t){let n=`input.${t.id}`;if(this.fields.has(n))return n;let r=this.draft.inputs?.get(t.id);r?"command"===r.type&&this.draft.note("input-command-unsupported",{id:t.id}):this.draft.note("input-undefined",{id:t.id});let i=r?.type==="pickString"&&r.options&&r.options.length>0?r.options:void 0,s=r?.password===!0||this.isSecretContext(e,t.from);return this.fields.set(n,{id:n,kind:i?"select":s?"password":"text",reason:"input",label:t.id,placeholder:t.from,...r?.description?{description:r.description}:{},...r?.default!==void 0?{defaultValue:r.default}:{},...i?{options:i}:{},targets:[]}),n}promptField(e,t){return this.fields.has(t.id)||this.fields.set(t.id,{id:t.id,kind:t.options?"select":t.secret||this.isSecretContext(e,t.from)?"password":"text",reason:t.reason,label:t.label,placeholder:t.from,...t.description?{description:t.description}:{},...void 0!==t.defaultValue?{defaultValue:t.defaultValue}:{},...t.options?{options:t.options}:{},...t.optional?{optional:!0}:{},targets:[]}),t.id}isSecretContext(e,t){switch(e[0]){case"env":case"headers":return xn(e[1]);case"oauth":return"clientSecret"===e[1];case"args":{if(xS([this.argTexts[e[1]]??""]).masked)return!0;let t=this.argTexts[e[1]-1];return void 0!==t&&xS([t,"x"]).args[1]===g3}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,xx(`https://host.invalid/?${n}=x`,xm).masked)}default:return!1}}}function x0(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 x1(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 x2=/^[A-Za-z0-9_-]+$/;function x4(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 x3=new Set(["mcp","server","mcp-server","mcpserver","cli","index","main","app","src","dist","build","bin","lib"]);function x8(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=x5(t);return s&&!x3.has(s.toLowerCase())?s:x5(r)||r||s||t}let x6=[/^mcp[-_]server[-_]/i,/^server[-_]/i,/^mcp[-_]/i,/[-_]mcp[-_]server$/i,/[-_]mcp$/i,/[-_]server$/i];function x5(e){let t=e;for(let e=!0;e;)for(let n of(e=!1,x6)){let r=t.replace(n,"");r!==t&&r&&(t=r,e=!0)}return t}let x9=new Set(["mcp","www","api","app","server","servers","remote","gateway"]);function x7(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=>!x9.has(e.toLowerCase()));return r[r.length-1]??n[n.length-1]??""}let ve=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 vt(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 vn(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(!x3.has(n.toLowerCase())&&"."!==n&&".."!==n)return x5(n.replace(/_/g,"-"))||n}return""}function vr(e,t){vi(e,t)&&vs(e,Math.ceil(t/1e3),t)}function vi(e,t){return!!("number"==typeof t&&Number.isFinite(t))&&t>0||(void 0!==t&&e.note("timeout-dropped",{value:String(t)}),!1)}function vs(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 vl=["codemode","deferred","direct","hidden"],va={"codemode-deferred":"codemode"},vo=["localhost","127.0.0.1","[::1]"];function vc(e){return"string"==typeof e&&vl.includes(e)?e:"string"==typeof e&&Object.hasOwn(va,e)?va[e]:void 0}function vd(e){try{return new URL(e)}catch{return}}function vu(e){let t=vd(e);return void 0!==t&&"http:"===t.protocol&&vo.includes(t.hostname)&&""===t.search&&""===t.hash}function vp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function vh(e){return vp(e)&&Object.values(e).every(e=>"string"==typeof e)}function vm(e,t){if(!x2.test(e))return{problem:"name",name:e};if(!vp(t))return{problem:"not-an-object"};let{type:n,exposure:r,enabled:i,timeout:s,toolExposure:l,description:a}=t;if(void 0!==r&&!vc(r))return{problem:"exposure",value:String(r)};if(void 0!==l){if(!vp(l))return{problem:"tool-exposure"};for(let[e,t]of Object.entries(l))if(!vc(t))return{problem:"tool-exposure",tool:e}}if(void 0!==i&&"boolean"!=typeof i)return{problem:"enabled"};if(void 0!==a&&"string"!=typeof a)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=vd(t.url);if(!e||!/^https?:$/.test(e.protocol))return{problem:"url",url:t.url};if(void 0!==t.headers&&!vh(t.headers))return{problem:"headers"};let n=function(e){var t;let n;if(void 0===e)return;if(!vp(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||!vu(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?vd(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)?vd(t):void 0)&&("https:"===n.protocol||"http:"===n.protocol&&vo.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(!vp(r)||"string"!=typeof r.provider||!r.provider)return{problem:"auth"};if("https:"!==e.protocol&&!vo.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||vh(t.env)?void 0!==t.cwd&&"string"!=typeof t.cwd?{problem:"cwd"}:void 0:{problem:"env"}:{problem:"args"}:{problem:"no-command-or-url"}}let vf=/[A-Za-z_]/,vg=/[A-Za-z0-9_]/,vx=/^[A-Za-z_][A-Za-z0-9_]*$/,vv=new Set([..." \n'\"\\$`|&;<>()#*?[]{}!~="]),vb=new Set([..."|&;<>()"]),vy=/[0-9@*#?$!-]/,vw={n:"\n",t:" ",r:"\r",a:"\x07",b:"\b",e:"\x1b",E:"\x1b",f:"\f",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function vj(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 vk(e,t){return/^(?:[A-Za-z]:\\|\\\\[A-Za-z0-9.$_-])/.test(e.slice(t,t+4))}class vS{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 vC)return{ok:!1,error:e.detail};throw e}return{ok:!0,words:this.words}}fail(e){throw new vC(e)}startWord(){return this.parts||(this.lineBreak&&this.fail({code:"multiple-commands"}),this.parts=[],this.windowsWord=vk(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)&&vj(e,this.index)>0)this.index+=vj(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:"`"}):vb.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||!vv.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=vk(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 vw?(t+=vw[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&&vf.test(n)){let n=this.index+1;for(;n<t.length&&vg.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&&vy.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}),vx.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 vC extends Error{constructor(e){super(e.code),this.detail=e}}function vN(e){return new vS(e).run()}function vE(e){return e.parts.every(e=>"text"===e.type)?e.text:void 0}function vM(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let v$=["httpUrl","trust","includeTools","excludeTools","authProviderType","targetAudience","targetServiceAccount","tcp"];function vI(e){if(v$.some(t=>t in e))return!0;let t=e.oauth;return vM(t)&&["redirectUri","authorizationUrl","tokenUrl","audiences","tokenParamName"].some(e=>e in t)}function vT(e){if(!vM(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]||vM(t)&&"string"==typeof t.path||"string"==typeof n||"string"==typeof r||"string"==typeof i}function vR(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 vA(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 vL(e,t){let n=t?vA(t):void 0;return{code:"sse-transport",params:{...e?{server:e}:{},...t?{url:t}:{},...n?{suggestedUrl:n}:{}}}}function vP(e){return e?{server:e}:{}}function vz(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):void 0}function vO(e,t,n){let r;if(!vM(t))return{note:{code:"no-command-or-url",params:vP(e)}};let i=new Set,s=e=>(i.add(e),t[e]),l=n.rawPi,a=function(e,t){switch(e.flavor){case"zed":return x$;case"opencode":return xR;case"vscode":return xI;default:return vI(t)?xT:xI}}(n,t),o=s("name"),c=e??("string"==typeof o?o:void 0),d=new xJ(n.source,l),u=(e,t)=>{if(l)return e?[{kind:"pi",text:e}]:[];return t&&"mcp-servers"===n.flavor&&/^!|\$\$|\$!/.test(e)&&d.note("looks-like-pi-config"),xz(e,a,t)};d.name=c,d.inputs=n.inputs;let p=s("inputs");Array.isArray(p)&&(d.inputs=new Map([...n.inputs??[],...vD(p)]));let h=s("type"),m=s("command"),f=[s("httpUrl"),s("url"),s("serverUrl")].find(e=>"string"==typeof e);if("tcp"in t)return{note:{code:"websocket-transport",params:vP(c)}};if(void 0!==h&&"unknown"===(r="string"==typeof h?vR(h):"unknown"))return{note:{code:"unsupported-transport",params:{...vP(c),type:String(h)}}};let g="string"==typeof m&&""!==m||Array.isArray(m)||vM(m),x=void 0!==f;if("sse"===r)return{note:vL(c,f)};if("ws"===r)return{note:{code:"websocket-transport",params:{...vP(c),...f?{url:f}:{}}}};if(void 0===r){if(g&&x)return{note:{code:"ambiguous-command-and-url",params:vP(c)}};if(x){if(void 0!==vA(f))return{note:vL(c,f)};r="http","mcp-servers"===n.flavor&&"string"==typeof t.url&&"string"!=typeof t.httpUrl&&d.note("transport-guessed")}else{if(!g)return{note:{code:"no-command-or-url",params:vP(c)}};r="stdio"}}if("stdio"!==r&&"http"!==r)return{note:{code:"unsupported-transport",params:{...vP(c),type:String(h)}}};if("stdio"===r&&!g||"http"===r&&!x)return{note:{code:"no-command-or-url",params:vP(c)}};if(d.transport=r,"stdio"===r){let e=function(e,t,n,r,i,s){let l,a=r("args"),o=r("opencode"===s.flavor?"environment":"env");if("opencode"===s.flavor&&void 0===o&&(o=r("env")),Array.isArray(n)){if(!n.every(e=>"string"==typeof e)||0===n.length)return{code:"invalid-config",params:{...vP(e.name),problem:"args"}};l=n[0],a=[...n.slice(1),...Array.isArray(a)?a:[]]}else if(vM(n))for(let t of(l="string"==typeof n.path?n.path:void 0,void 0===a&&(a=n.args),void 0===o&&(o=n.env),Object.keys(n)))["path","args","env"].includes(t)||e.note("dropped-key",{key:`command.${t}`});else"string"==typeof n&&(l=n);if(!l)return{code:"no-command-or-url",params:vP(e.name)};let c=Array.isArray(a)?[...a]:[];if(void 0!==a&&!Array.isArray(a))return{code:"invalid-config",params:{...vP(e.name),problem:"args"}};if(0===c.length&&/\s/.test(l.trim())&&!/^(?:[A-Za-z]:[\\/]|[\\/]|~[\\/]|\.{1,2}[\\/])/.test(l.trim())){let t=vN(l.trim()),n=t.ok?t.words.map(vE):void 0;n&&n.length>1&&n.every(e=>void 0!==e)&&(e.note("command-split",{command:l}),l=n[0],c.push(...n.slice(1)))}for(let[t,n]of(e.command=i(l,!1),c.entries())){let r=vz(n);if(void 0===r)return{code:"invalid-config",params:{...vP(e.name),problem:"args",index:t}};e.args.push(i(r,!1))}if(void 0!==o){if(!vM(o))return{code:"invalid-config",params:{...vP(e.name),problem:"env"}};for(let[t,n]of Object.entries(o)){if(null===n){e.note("env-null-dropped",{name:t});continue}let r=vz(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&&xn(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 d=r("cwd");for(let n of("string"==typeof d&&""!==d?e.cwd=i(d,!1):void 0!==d&&""!==d&&e.note("dropped-key",{key:"cwd"}),["headers","oauth","auth","url","httpUrl","serverUrl"]))n in t&&(r(n),e.note("dropped-key",{key:n}))}(d,t,m,s,u,n);if(e)return{note:e}}else!function(e,t,n,r,i){let s=r("headers"),l=i(n,!1),a=vM(s)&&Object.keys(s).some(e=>"authorization"===e.toLowerCase());if(1===l.length&&"text"in l[0]?x1(e,n,a):e.url=l,vM(s))for(let[t,n]of Object.entries(s)){let r=vz(n);if(void 0===r){e.note("dropped-key",{key:`headers.${t}`});continue}if(""===r.trim()){"authorization"===t.toLowerCase()?e.note("empty-authorization-dropped"):xn(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 o=r("oauth"),c=r("auth");if(!1===o?e.note("oauth-disable-unsupported"):vM(o)?vW(e,o,i):void 0!==o&&e.note("dropped-key",{key:"oauth"}),vM(c))for(let t of(vW(e,{...void 0!==c.CLIENT_ID?{clientId:c.CLIENT_ID}:{},...void 0!==c.CLIENT_SECRET?{clientSecret:c.CLIENT_SECRET}:{},...void 0!==c.scopes?{scopes:c.scopes}:{}},i,"auth."),Object.keys(c)))["CLIENT_ID","CLIENT_SECRET","scopes"].includes(t)||e.note("oauth-option-dropped",{key:`auth.${t}`});else void 0!==c&&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}))}(d,t,f,s,u);let v=s("timeout");if(void 0!==v)if(l)"number"==typeof v&&v>0?d.timeout=v:d.note("timeout-dropped",{value:String(v)});else if("opencode"===n.flavor)d.note("timeout-dropped",{value:String(v)});else if(vI(t))vr(d,v);else["autoApprove","alwaysAllow","transportType"].some(e=>e in t)||"streamableHttp"===t.type?vi(d,v)&&vs(d,Math.ceil(v),void 0):!function(e,t){if(!vi(e,t))return;let n=t>=1e3;e.note("timeout-unit-guessed",{value:t,unit:n?"milliseconds":"seconds"}),n?vs(e,Math.ceil(t/1e3),t):vs(e,Math.ceil(t),void 0)}(d,v);let b=s("enabled"),y=s("disabled");!1===b||!0===y?(d.enabled=!1,d.note("imported-disabled")):(void 0!==b&&"boolean"!=typeof b||void 0!==y&&"boolean"!=typeof y)&&d.note("dropped-key",{key:void 0!==b?"enabled":"disabled"});let w=s("exposure");if(void 0!==w){let e=vc(w);e?d.exposure=e:d.note("invalid-exposure-dropped",{value:String(w)})}let j=s("toolExposure");if(void 0!==j){let e=vM(j)?Object.entries(j).map(e=>{let[t,n]=e;return[t,vc(n)]}):void 0;e?.every(e=>{let[,t]=e;return void 0!==t})?d.toolExposure=Object.fromEntries(e):d.note("invalid-exposure-dropped",{value:"toolExposure"})}if(l||void 0===w&&void 0===j||d.note("looks-like-pi-config"),l){let e=s("description");"string"==typeof e?d.description=e:void 0!==e&&d.note("dropped-key",{key:"description"})}for(let e of(vF(d,s("includeTools"),s("excludeTools")),Object.keys(t)))i.has(e)||d.note("dropped-key",{key:e});return{draft:d}}function vW(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&&vu(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 vF(e,t,n){let r=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e&&""!==e):[],i=r(t),s=r(n);if(0===i.length&&0===s.length)return;let l={...e.toolExposure??{}};if(i.length>0){let t=e.exposure??"codemode";for(let n of(e.exposure="hidden",i))l[n]=t;e.note("tool-filter-imported",{mode:"include",tools:i.join(", ")})}for(let e of s)l[e]="hidden";s.length>0&&e.note("tool-filter-imported",{mode:"exclude",tools:s.join(", ")}),e.toolExposure=l}function vD(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e)vM(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=>vM(e)?e.value:e).filter(e=>"string"==typeof e)}:{}});return t}function v_(e,t,n,r){let i=[],s=0;for(let l of e.matchAll(/\{([A-Za-z_][A-Za-z0-9_-]*)\}/g)){l.index>s&&i.push({kind:"text",text:e.slice(s,l.index)});let a=vM(t)&&vM(t[l[1]])?t[l[1]]:{};i.push(vB(`${n}${l[1]}`,l[1],l[0],a,r)),s=l.index+l[0].length}return s<e.length&&i.push({kind:"text",text:e.slice(s)}),i}function vB(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 vH(e,t,n){let r=[],i="",s=()=>{i&&("pi"===t?r.push({kind:"pi",text:i}):r.push(...xz(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 vU(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if("variable"===i.type){n+=i.raw;continue}let s=i.value.indexOf(t);if(s<0){n+=i.value;continue}n+=i.value.slice(0,s);let l=i.value.slice(s+t.length);return[n,[...l?[{...i,value:l}]:[],...e.slice(r+1)]]}}let vK=/^https?:\/\//i,vq=/^wss?:\/\//i,vV={"@earendil-works/pi-coding-agent":"pi","@anthropic-ai/claude-code":"claude","@openai/codex":"codex","@google/gemini-cli":"gemini"},vZ=new Set(["pi","claude","codex","gemini"]),vJ=new Set(["install","remove","uninstall","update","list","config"]);function vY(e){return"error"in e?{error:e.error}:{entries:[e],notes:[]}}let vG={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"},vX=new Map([["-l","--local"]]),vQ=["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name","oauth-client-registration"],v0=["env","cwd"];function v1(e,t,n,r){let i={positional:[],afterDashDash:[],values:new Map,lists:new Map,seen:new Map};for(let s=0;s<t.length;s++){let l=t[s],a=l.text;if("--"===a){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(!a.startsWith("-")||"-"===a){i.positional.push(l);continue}let o=a.startsWith("--")?a.indexOf("="):-1,c=o>0?a.slice(0,o):a,d=n[c];if(!d){if(i.positional.length>=r.asArgAfter){i.positional.push(l),i.seen.set(`as-arg:${c}`,c);continue}return{error:{code:"cli-unknown-option",params:{cli:e,option:c}}}}if(i.seen.set(d.name,c),"flag"===d.kind){i.values.set(d.name,!0);continue}let u=o>0?v2(l,o+1):void 0;if("value"===d.kind||"list"===d.kind){let n=u??t[++s];if(void 0===n)return{error:{code:"cli-option-needs-value",params:{cli:e,option:c}}};"value"===d.kind?i.values.set(d.name,n):i.lists.set(d.name,[...i.lists.get(d.name)??[],n]);continue}let p=u?[u]:[];if(!u)for(;s+1<t.length&&r.variadic(d.name,t[s+1]);)p.push(t[++s]);if(0===p.length)return{error:{code:"cli-option-needs-value",params:{cli:e,option:c}}};i.lists.set(d.name,[...i.lists.get(d.name)??[],...p])}return i}function v2(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 v4=/^[A-Za-z_][A-Za-z0-9_]*=/,v3=/^[^\s:]+:/;function v8(e,t,n,r){for(let i of t??[]){let t=vU(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],vH(t[1],n,!0)])}}function v6(e,t,n,r){for(let i of t??[]){let t=vU(i.parts,":"),s=t?.[0].trim();if(!t||!s)return{code:"cli-invalid-pair",params:{cli:r,option:"--header",value:i.text}};let l=function(e){let t=e.map(e=>({...e})),n=t[0];n?.type==="text"&&(n.value=n.value.replace(/^\s+/,""));let r=t[t.length-1];return r?.type==="text"&&(r.value=r.value.replace(/\s+$/,"")),t}(t[1]);if("authorization"===s.toLowerCase()&&l.every(e=>"text"===e.type&&""===e.value)){e.note("empty-authorization-dropped");continue}e.headers.push([s,vH(l,n,!0)])}}function v5(e){if(void 0!==e&&!0!==e){if("user"===e.text)return"global";if("project"===e.text)return"project"}}function v9(e,t,n,r,i){let s,[l,a,...o]=r;if(!l||!a)return{code:"cli-usage",params:{cli:t}};e.name=l.text;let c=void 0===n||!0===n?void 0:n.text.toLowerCase();if(void 0===c){if("http"==(s=vK.test(a.text)?"http":vq.test(a.text)?"ws":"stdio")&&void 0!==vA(a.text))return vL(l.text,a.text);"http"===s&&"gemini"===t&&e.note("transport-assumed-http")}else s="streamable-http"===c?"http":c;return"sse"===s?vL(l.text,a.text):"ws"===s?{code:"websocket-transport",params:{server:l.text,url:a.text}}:"http"===s?(e.transport="http",e.url=vH(a.parts,i,!1),o.length>0&&e.note("cli-extra-arguments",{cli:t,arguments:o.map(e=>e.text).join(" ")}),"http"):"stdio"!==s?{code:"unsupported-transport",params:{server:l.text,type:s}}:(e.transport="stdio",e.command=vH(a.parts,i,!1),e.args=o.map(e=>vH(e.parts,i,!1)),"stdio")}let v7={"-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 be(e,t){return"env"===e?v4.test(t.text):v3.test(t.text)&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(t.text)}function bt(e){e.oauth.clientSecret=[{kind:"prompt",id:"oauth.clientSecret",reason:"client-secret",label:"clientSecret",from:"",secret:!0}],e.note("client-secret-prompt")}let bn={"-s":{name:"scope",kind:"value"},"--scope":{name:"scope",kind:"value"},"--client-secret":{name:"client-secret",kind:"flag"}};function br(e){let t,n=vE(e)??e.text;try{t=xE(n)}catch(e){return{error:{code:"invalid-json",params:{detail:e instanceof Error?e.message:String(e)}}}}return vM(t)?{value:t}:{error:{code:"no-servers-found"}}}let bi={"--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"}},bs={"-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 bl(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(ba(r),ba(i))}return t}function ba(e){try{return decodeURIComponent(e)}catch{return e}}function bo(e){let t=e.trim();for(let e=0;e<4;e++)try{return xE(t)}catch{let e=ba(t);if(e===t)break;t=e.trim()}}function bc(e){return{error:{code:"install-link-invalid",params:{detail:e}}}}function bd(e){let t=e.get("config");if(!t)return bc("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:bo(n);return vM(r)?{entries:[vO(e.get("name")||void 0,r,{source:"cursor-install-link",flavor:"mcp-servers",rawPi:!1})],notes:[]}:bc("config")}function bu(e,t,n,r){return vM(e)?{entries:[vO(n,e,{source:t,flavor:"vscode",rawPi:!1,inputs:vD(r)})],notes:[]}:bc("config")}function bp(e){return{error:{code:"by-name-link",params:{name:e}}}}function bh(e){let t=e.indexOf("?");return t<0?"":e.slice(t+1)}function bm(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:[bg(void 0,r)],notes:[]};return{error:{code:"unrecognized-input"}}}if(n>3)return bc("nesting");let i=t.protocol.replace(/:$/,"").toLowerCase();switch(i){case"cursor":if(/\/mcp\/install\/?$/.test(t.pathname))return bd(bl(t.search));return bc("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 bp(ba(t[1]));if(/^mcp\/api\.mcp\.github\.com\//.test(e))return bp(e.replace(/^mcp\//,""));if(/^mcp\/install\?/.test(e))return bu(bo(bh(r)),"vscode-install-link");return bc(i)}case"vsweb+mcp":return bu(bo(bh(r)),"visual-studio-install-link");case"ghapp":if(/^\/\/mcp\/install/.test(r.slice(r.indexOf(":")+1)))return bu(bo(bh(r)),"copilot-app-install-link");return bc(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 bd(bl(e.search));if("vscode.dev"===r||"insiders.vscode.dev"===r){let t=bl(e.search);if(/^\/redirect\/?$/.test(i)&&t.get("url"))return bm(t.get("url"),n+1);if(/^\/redirect\/mcp\/install\/?$/.test(i)){let e=t.get("config");return e?bu(bo(e),"vscode-install-link",t.get("name")||void 0,bo(t.get("inputs")??"[]")):bc("config")}}if("aka.ms"===r&&/^\/vs\/mcp-install\/?$/i.test(i))return bu(bo(e.search.slice(1)),"visual-studio-install-link");if("github.com"===r&&/^\/copilot\/app\/launch\/?$/.test(i)){let t=bl(e.search).get("open");return t?bm(t,n+1):bc("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:[bg(e,t)],notes:[]}}(t,r,n);default:return{error:{code:"unsupported-url-scheme",params:{scheme:i}}}}}let bf=new Set(["localhost","127.0.0.1","[::1]"]);function bg(e,t){let n=x7(t)||void 0;if(void 0!==vA(t))return{note:vL(n,t)};let r=new xJ("url",!1);return r.transport="http",x1(r,t,!1),e?.protocol!=="http:"||bf.has(e.hostname)||r.note("insecure-http",{host:e.hostname}),{draft:r}}let bx=/[\u200B-\u200D\u2060\uFEFF]/g,bv=/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]\S*)?$/i,bb={"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 by(e){return new Set(e.fields.flatMap(e=>e.targets.map(e=>xU(e.path))))}function bw(e){var t;let n,r,i,s,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=(n=e.replace(bx,"").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(!a)return{ok:!1,notes:[{code:"empty-input"}]};if(a.startsWith("{")||a.startsWith("[")||/^"[^"\n]+"\s*:/.test(a))s=function(e,t){let n;try{n=xE(e)}catch(t){try{n=xE(`{${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 vO(n,r,t)});if(Array.isArray(e)){let r=e.filter(vT);return 0===r.length?{error:{code:"no-servers-found"}}:{entries:r.map(e=>vO(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})),notes:n}}if(!vM(e))return{error:{code:"no-servers-found"}};let i=vM(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?x8(t.split("/").pop()??t):void 0,r=Array.isArray(e.remotes)?e.remotes.filter(vM):[],i=r.filter(e=>"string"==typeof e.type&&"http"===vR(e.type)&&"string"==typeof e.url);if(0===i.length){let e=r.find(e=>"sse"===e.type);return e?[{note:vL(n,"string"==typeof e.url?e.url:void 0)}]:[{note:{code:"registry-packages-unsupported",params:vP(n)}}]}return i.map(e=>{let r=new xJ("registry-server-json",!1);for(let i of(r.name=n,t&&n!==t&&(r.originalName=t),r.transport="http",r.url=v_(e.url,e.variables,"url.","registry-variable"),Array.isArray(e.headers)?e.headers.filter(vM):[])){if("string"!=typeof i.name||""===i.name)continue;let e=i.name;"string"==typeof i.value&&""!==i.value?r.headers.push([e,v_(i.value,i.variables,`headers.${e}.`,"registry-header")]):r.headers.push([e,[vB(`headers.${e}`,e,"",i,"registry-header")]])}return{draft:r}})}(i),notes:n};if(vM(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(vM(e.servers)){let t=vD(e.inputs);return{entries:r(e.servers,{source:"vscode-json",flavor:"vscode",rawPi:!1,inputs:t}),notes:n}}if(vM(e.mcp)){let t=e.mcp;if(vM(t.servers)){let e=vD(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(vM(e.context_servers))return{entries:Object.entries(e.context_servers).map(e=>{let t,[n,r]=e;return vM(r)&&("extension"===r.source||!vT(r))?{note:{code:"zed-extension-server",params:{server:n}}}:vO(n,vM(r)?(t={...r},delete t.source,t):r,{source:"zed-json",flavor:"zed",rawPi:!1})}),notes:n};if(vT(e))return{entries:[vO(void 0,e,{source:"server-object",flavor:"mcp-servers",rawPi:t})],notes:n};let s=Object.values(e);return s.length>0&&s.every(vM)&&s.some(vT)?{entries:r(e,{source:"server-map",flavor:"mcp-servers",rawPi:t}),notes:n}:{error:{code:"no-servers-found"}}}(n,t)}(a,!0===l.rawPi);else if(bv.test(a)){if(!("error"in(s=bm(`http://${a}`))))for(let e of s.entries)"draft"in e&&e.draft.note("scheme-assumed",{url:`http://${a}`})}else{let e;s=!/\s/.test(a)&&/^[A-Za-z][A-Za-z0-9+.-]+:/.test(a)?bm(a):(e=vN(a.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&&vV[i]&&e[t+1]?.text==="mcp"&&(n=t,r=vV[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 vY(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=vX.get(e[t].text)??e[t].text;if("--"===s||n.length>=2){n.push(...e.slice("--"===s?t+1:t));break}if(!s.startsWith("--")){n.push(e[t]);continue}let l=s.slice(2),a=vG[l];if(!a)return{error:{code:"cli-unknown-option",params:{cli:"pi",option:s}}};if("flag"===a){r.set(l,!0);continue}let o=e[++t];if(void 0===o)return{error:{code:"cli-option-needs-value",params:{cli:"pi",option:s}}};"list"===a?i.set(l,[...i.get(l)??[],o]):r.set(l,o)}let[s,...l]=n,a=r.get("url");if(!s||""===s.text||void 0===a==(0===l.length))return{error:{code:"cli-usage",params:{cli:"pi"}}};let o=e=>{let t=r.get(e);return!0===t?void 0:t},c=(void 0===a?vQ:v0).find(e=>r.has(e)||i.has(e));if(c)return{error:{code:"cli-option-wrong-transport",params:{cli:"pi",option:`--${c}`,transport:void 0===a?"stdio":"http"}}};let d=new xJ("pi-mcp-add",!0);d.name=s.text,d.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=vU(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!==a&&!0!==a){d.transport="http",d.url=vH(a.parts,"pi",!1);let e=u("header");if("error"in e)return e;for(let[t,n]of e)d.headers.push([t,vH(n,"pi",!0)]);let t=o("bearer-token-env-var");if(void 0!==t){let e=["Authorization",[{kind:"pi",text:`Bearer $\{${t.text}}`}]],n=d.headers.findIndex(e=>{let[t]=e;return"Authorization"===t});n>=0?d.headers[n]=e:d.headers.push(e)}let n=o("oauth-client-id"),r=o("oauth-client-secret"),i=o("oauth-callback-port"),s=o("oauth-client-name"),l=o("oauth-client-registration");n&&(d.oauth.clientId=vH(n.parts,"pi",!1)),r&&(d.oauth.clientSecret=vH(r.parts,"pi",!0)),i&&(d.oauth.callbackPort=Number(i.text)),s&&(d.oauth.clientName=vH(s.parts,"pi",!1)),l&&(d.oauth.clientRegistration=l.text),p.url=a.parts.some(e=>"variable"===e.type)?"https://placeholder.invalid/":a.text,(i||s||l)&&(p.oauth={...n?{clientId:n.text}:{},...i?{callbackPort:Number(i.text)}:{},...s?{clientName:s.text}:{},...l?{clientRegistration:l.text}:{}})}else{d.transport="stdio";let e=u("env");if("error"in e)return e;for(let[t,n]of e)d.env.push([t,vH(n,"pi",!0)]);let[t,...n]=l;d.command=vH(t.parts,"pi",!1),d.args=n.map(e=>vH(e.parts,"pi",!1));let r=o("cwd");r&&(d.cwd=vH(r.parts,"pi",!1)),p.command=t.text}let h=o("exposure");void 0!==h&&(p.exposure=h.text,d.exposure=vc(h.text)??h.text);let m=o("description");void 0!==m&&(p.description=m.text,d.description=m.text);let f=vm("server",p);return f?{note:{code:"invalid-config",params:{server:s.text,...f}}}:{draft:d}}(t,i.slice(1)));if("claude"===r&&"add"===e)return vY(function(e){let t=v1("claude",e,v7,{asArgAfter:2,variadic:be});if("error"in t)return{error:t.error};let n=new xJ("claude-mcp-add",!1),r=v9(n,"claude",t.values.get("transport"),[...t.positional,...t.afterDashDash],xI);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=v5(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=v6(n,t.lists.get("header"),xI,"claude");if(r)return{error:r};let l=t.values.get("client-id");l&&!0!==l&&(n.oauth.clientId=vH(l.parts,xI,!1)),t.values.has("client-secret")&&bt(n);let a=t.values.get("callback-port");a&&!0!==a&&(i=n,Number.isInteger(e=Number(s=a.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=v8(n,t.lists.get("env"),xI,"claude");if(e)return{error:e}}return{draft:n}}(t));if("claude"===r&&"add-json"===e)return vY(function(e){let t=v1("claude",e,bn,{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=br(r);if("error"in s)return s;let l=vO(n.text,s.value,{source:"claude-mcp-add-json",flavor:"mcp-servers",rawPi:!1});return"note"in l||(l.draft.scopeHint=v5(t.values.get("scope")),t.values.has("client-secret")&&"http"===l.draft.transport&&!l.draft.oauth.clientSecret&&bt(l.draft)),l}(t));if("claude"===r&&"add-from-claude-desktop"===e)return{error:{code:"claude-desktop-import"}};if("codex"===r&&"add"===e)return vY(function(e){let t=v1("codex",e,bi,{asArgAfter:1/0,stopAfter:2});if("error"in t)return{error:t.error};let n=t.afterDashDash,r=t.lists.get("env")??[],[i,...s]=t.positional,l=n.length>0?n:s,a=t.values.get("url");if(!i||void 0===a==(0===l.length)||n.length>0&&s.length>0)return{error:{code:"cli-usage",params:{cli:"codex"}}};let o=new xJ("codex-mcp-add",!1);for(let e of(o.name=i.text,["config","enable","disable"]))t.values.has(e)&&o.note("cli-option-ignored",{cli:"codex",option:t.seen.get(e)});if(t.values.has("oauth-resource")&&o.note("oauth-option-dropped",{key:"--oauth-resource"}),void 0!==a&&!0!==a){if(r.length>0)return{error:{code:"cli-option-wrong-transport",params:{cli:"codex",option:"--env",transport:"http"}}};if(void 0!==vA(a.text))return{note:vL(i.text,a.text)};o.transport="http",o.url=vH(a.parts,x$,!1);let e=t.values.get("bearer-token-env-var");e&&!0!==e&&o.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&&(o.oauth.clientId=vH(n.parts,x$,!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"}}};o.transport="stdio";let e=v8(o,r,x$,"codex");if(e)return{error:e};o.command=vH(l[0].parts,x$,!1),o.args=l.slice(1).map(e=>vH(e.parts,x$,!1))}return{draft:o}}(t));if("gemini"===r&&"add"===e)return vY(function(e){let t=v1("gemini",e,bs,{asArgAfter:2});if("error"in t)return{error:t.error};let n=new xJ("gemini-mcp-add",!1),r=v9(n,"gemini",t.values.get("transport"),[...t.positional,...t.afterDashDash],xT);if("string"!=typeof r)return"cli-usage"===r.code?{error:r}:{note:r};if(n.scopeHint=v5(t.values.get("scope")),"http"===r){t.lists.has("env")&&n.note("cli-option-wrong-transport",{cli:"gemini",option:"--env",transport:"http"});let e=v6(n,t.lists.get("header"),xT,"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=v8(n,t.lists.get("env"),xT,"gemini");if(e)return{error:e}}let i=t.values.get("timeout");for(let e of(i&&!0!==i&&vr(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 vF(n,s("include-tools"),s("exclude-tools")),{draft:n}}(t));if("add"===e||"install"===e)return{error:{code:"cli-unsupported",params:{cli:r}}};if(vZ.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]&&vJ.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=v2(e[n],10)}if(!r)return{error:{code:"cli-option-needs-value",params:{cli:"code",option:"--add-mcp"}}};let s=br(r);if("error"in s)return s;t.push(vO(void 0,s.value,{source:"vscode-add-mcp",flavor:"vscode",rawPi:!1}))}return{entries:t,notes:[]}}(e.slice(1)):vY(function(e){let t=new xJ("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,vH(r.value,x$,!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=vH(i.parts,x$,!1),t.args=e.slice(n+1).map(e=>vH(e.parts,x$,!1));let s=e.slice(n+1).map(e=>e.text),l=s.some(e=>/^mcp-remote(?:@|$)/.test(e))?s.find(e=>vK.test(e)):void 0;return l&&t.note("mcp-remote-bridge",{url:l}),{draft:t}}(e))}(e.words):{error:function(e){let{code:t,...n}=e;return Object.keys(n).length>0?{code:bb[t],params:n}:{code:bb[t]}}(e.error)}}if("error"in s)return{ok:!1,notes:[s.error]};let o=[...s.notes],c=[],d=[...l.takenNames??[]],u=new Set;for(let e of s.entries){if("note"in e){o.push(e.note);continue}let n=function(e){let t,n=new xQ(e);if("stdio"===e.transport&&e.command&&""!==xY(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||""===xY(e.url))return{note:{code:"no-command-or-url",...e.name?{params:{server:e.name}}:{}}};let r=n.encode(["url"],e.url),i={};for(let[t,r]of e.headers)i[t]=n.encode(["headers",t],r);let s={},{clientId:l,clientSecret:a,callbackPort:o,clientName:c,clientRegistration:d,callbackUrl:u,scope:p,authServerMetadataUrl:h}=e.oauth;l&&(s.clientId=n.encode(["oauth","clientId"],l)),a&&(s.clientSecret=n.encode(["oauth","clientSecret"],a)),void 0!==o&&(s.callbackPort=o),c&&(s.clientName=n.encode(["oauth","clientName"],c)),d&&(s.clientRegistration=d),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){o.push(n.note);continue}let r=n.server,i=r.name,s=!i;s&&(i=function(e){if("url"in e)return x7(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&&x7(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=vt(t,new Set(["-p","--package","-c","--call"]));return e?x8(e):""}case"pnpm":case"yarn":case"bun":case"npm":{let e=t.findIndex(e=>"dlx"===e||"exec"===e||"x"===e),n=e>=0?vt(t.slice(e+1),new Set(["-p","--package"])):void 0;return n?x8(n):""}case"uvx":case"pipx":{let e=vt("pipx"===n&&"run"===t[0]?t.slice(1):t,new Set(["--from","--with","--python","-p","--index-url","--spec"]));return e?x8(e):""}case"uv":{let e=t.indexOf("run"),n=e>=0?vt(t.slice(e+1),new Set(["--with","--directory","--python","-p","--from","--project"])):void 0;return n?vn(n):""}case"docker":case"podman":{let e=t.indexOf("run"),n=e>=0?vt(t.slice(e+1),ve):void 0;if(!n)return"";let r=n.split("/").pop().replace(/[:@].*$/,"");return x5(r)||r}case"python":case"python3":case"py":{let e=t.indexOf("-m");if(e>=0&&t[e+1])return x8(t[e+1].replace(/_/g,"-"));let n=vt(t,new Set(["-X","-W"]));return n?vn(n):""}case"node":case"deno":case"tsx":case"ts-node":{let e=vt("deno"===n&&"run"===t[0]?t.slice(1):t,new Set(["-r","--require","--import","--loader"]));return e?vn(e):""}default:return x5(n.replace(/_/g,"-"))||n}}(e.command,t)}(r.config))&&r.notes.push({code:"name-derived",params:{name:i}});let l=(t=i,x2.test(t))?i:i.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,48).replace(/[-_]+$/g,"")||"server";l!==i&&i&&(r.originalName=r.originalName??i,r.notes.push({code:"name-sanitized",params:{original:i,name:l}}));let a=x4(l,s?[...d,...u]:u);a!==l&&(r.notes.push({code:"name-deduplicated",params:{original:l,name:a}}),l=a),!s&&d.includes(l)&&r.notes.push({code:"name-taken",params:{name:l,suggestedName:x4(l,[...d,...u])}}),r.name=l;let p=vm(l,function(e){let t=by(e),n=JSON.parse(JSON.stringify(e.config));t.has(xU(["url"]))&&(n.url="https://placeholder.invalid/");let r=n.oauth;return r&&t.has(xU(["oauth","callbackUrl"]))&&delete r.callbackUrl,n}(r));if(p){o.push({code:"invalid-config",params:{server:l,...p}});continue}!function(e){let t=by(e);for(let n of b$(e.config))t.has(xU(n))||e.notes.push({code:"literal-secret",params:{field:xK(n)}});let n=e.config;if("url"in n){for(let[t,r]of Object.entries(n.headers??{})){let n=xF(r);n.length>0&&e.notes.push({code:"header-env-reference",params:{header:t,names:n.join(", ")}})}let t=xF(n.oauth?.clientSecret??"");t.length>0&&e.notes.push({code:"client-secret-env-reference",params:{names:t.join(", ")}})}}(r),u.add(l),c.push(r)}return 0===c.length?{ok:!1,notes:o.length>0?o:[{code:"no-servers-found"}]}:{ok:!0,servers:c,notes:o}}let bj=/^[A-Za-z_][A-Za-z0-9_]*$/;function bk(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 bS(e){let t=by(e);return b$(e.config).filter(e=>xq(e)&&!t.has(xU(e)))}function bC(e){return"string"==typeof e&&""===e.trim()?"missing":"name"}let bN=/^(?:bearer|basic|token)\s+/i;function bE(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=JSON.parse(JSON.stringify(e.config)),i=new Map,s=[],l=new Map(bS(e).map(e=>[xK(e),e])),a=[];for(let[e,t]of Object.entries(n)){let n="string"==typeof t?t.trim():"",r=l.get(e);r?bj.test(n)?a.push([r,n]):s.push({code:"field-reference-invalid",params:{field:e,problem:bC(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():"";bj.test(r)?"select"!==n.kind&&n.targets.every(e=>xq(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:bC(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 o=new Set,c=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&&o.add(xK(e.path));let s=xU(e.path);if(c.has(s))continue;if(c.add(s),e.parts.some(e=>"string"!=typeof e&&void 0===i.get(e.field))){bk(r,e.path,void 0);continue}let l="";for(let t of e.parts){var d,u,p,h;l+="string"==typeof t?t:(d=i.get(t.field),u=e.path,p=""===l,h=e.encoding,"reference"in d?`$\{${d.reference}}`:"uri-component"===h?encodeURIComponent(d.text):xq(u)?xO(d.text,{atStart:p}):d.text)}bk(r,e.path,l)}for(let[e,t]of a){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(bN)?.[0]??"":"";bk(r,e,`${i}$\{${t}}`)}for(let e of b$(r))o.add(xK(e));return{ok:!0,config:r,secretPaths:[...o]}}let bM=["command","args","env","cwd","url","headers","oauth"];function b$(e){let t=[];for(let n of function(e){if(!xC(e))return[];let t=[];for(let n of["env","headers"]){let r=e[n];if(xC(r))for(let[e,i]of Object.entries(r))"string"==typeof i&&xN(i)&&""!==i&&(xn(e)||/^(?:bearer|basic|token)\s+\S/i.test(i)||xy(i,xu).masked)&&t.push({kind:"env"===n?"env":"header",name:e})}let n=xC(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&""!==n&&xN(n)&&t.push({kind:"oauth-client-secret"}),"string"==typeof e.url&&xx(e.url,xm).masked&&t.push({kind:"url"}),"string"==typeof e.command&&xy(e.command,xm).masked&&t.push({kind:"command"}),Array.isArray(e.args)&&xS(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:""):[];xS(n).args.forEach((e,r)=>{e!==n[r]&&t.push(["args",r])})}}return t.sort((e,t)=>bM.indexOf(e[0])-bM.indexOf(t[0]))}let bI="PI_WEB_PASSWORD";function bT(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function bR(e){return bT(e)?Object.entries(e).filter(e=>"string"==typeof e[1]):[]}function bA(e){if(!bT(e))return[];if(!("url"in e))return bR(e.env).map(e=>{let[t,n]=e;return{kind:"env",name:t,value:n}});let t=bR(e.headers).map(e=>{let[t,n]=e;return{kind:"header",name:t,value:n}}),n=bT(e.oauth)?e.oauth.clientSecret:void 0;return"string"==typeof n&&t.push({kind:"oauth-client-secret",value:n}),t}let bL={text:"",rawPi:!1,server:0,values:{},references:{},secretReferences:{}};function bP(e,t,n){let r=bw(e,{rawPi:t});if(!r.ok)return;let i=r.servers[Math.min(n,r.servers.length-1)],{config:s}=i,l="url"in s?["url",s.url]:["command",s.command,s.args??[]];return JSON.stringify([i.source,i.originalName??i.name,l])}function bz(e,t){let n={...e,...t},r=bP(e.text,e.rawPi,e.server);if(void 0!==r&&r===bP(n.text,n.rawPi,e.server))return n;let i={...n,server:0,values:{},references:{},secretReferences:{}};return delete i.name,i}function bO(e){return xM[e.code]??"warning"}function bW(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?fY(t):t;if("string"==typeof i.field&&e.code.startsWith("field-")){let e=r.find(e=>e.id===i.field);e&&(s.field=fY(e.label))}"invalid-config"===e.code&&(s.problem=t("tool-exposure"===(n=String(i.problem??"no-command-or-url"))&&void 0!==i.tool?"mcp.importProblem.tool-exposure.tool":"args"===n&&void 0!==i.index?"mcp.importProblem.args.index":`mcp.importProblem.${n}`,s)),"cli-option-wrong-transport"===e.code&&("stdio"===i.transport||"http"===i.transport)&&(s.transport=t(`mcp.transport.${i.transport}`));let l=t(function(e){let t=e.params??{};switch(e.code){case"field-reference-invalid":return`mcp.importNote.field-reference-invalid.${"target"===t.problem||"missing"===t.problem?t.problem:"name"}`;case"sse-transport":return void 0===t.suggestedUrl?"mcp.importNote.sse-transport":"mcp.importNote.sse-transport.suggested";case"timeout-unit-guessed":return`mcp.importNote.timeout-unit-guessed.${"milliseconds"===t.unit?"milliseconds":"seconds"}`;case"tool-filter-imported":return`mcp.importNote.tool-filter-imported.${"exclude"===t.mode?"exclude":"include"}`;default:return`mcp.importNote.${e.code}`}}(e),s);return"string"==typeof s.server?t("mcp.importNote.forServer",{server:s.server,note:l}):l}let bF={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"},bD={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"},b_=JSON.stringify({command:"uvx",args:["mcp-server-fetch"]}),bB=JSON.stringify({name:"fetch",command:"uvx",args:["mcp-server-fetch"]}),bH=[{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 '${bB}'`},{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(b_)}`},{source:"vscode-install-link",text:`vscode:mcp/install?${encodeURIComponent(bB)}`},{source:"visual-studio-install-link",text:`vsweb+mcp:/install?${encodeURIComponent(bB)}`},{source:"copilot-app-install-link",text:`ghapp://mcp/install?${encodeURIComponent(bB)}`}];function bU(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?fY(r):r.field===e.id?n:`‹${fY(t.find(e=>{let{id:t}=e;return t===r.field})?.label??r.field)}›`).join("")}))].join(", ")}function bK(e){return"select"!==e.kind&&e.targets.every(e=>xq(e.path)&&void 0===e.encoding)}let bq=/^[A-Za-z_][A-Za-z0-9_]*$/;function bV(){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 bq.test(r)?r:void 0}let bZ=/^(?:proxy-)?authorization$/i;function bJ(e,t){let n=function(e,t){if(e.startsWith("env.")){let t=e.slice(4);return bq.test(t)?t:bV(t)}let n=function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];return bV(t,...n)??bV(...n)};if(e.startsWith("headers.")){let t=e.slice(8);return n(bZ.test(t)?"TOKEN":t.replace(/^x-/i,""))}if("oauth.clientSecret"===e)return n("CLIENT_SECRET")}(e,t);return n===bI?void 0:n}function bY(e){return e.startsWith("env.")||e.startsWith("headers.")||"oauth.clientSecret"===e}function bG(e,t){let n=e;for(let e of t)n=n.split(e).join(g3);return{text:n,masked:n!==e}}function bX(e){let{kind:t,name:n}=e;return void 0===n?{kind:t}:{kind:t,name:n}}function bQ(e,t){let n=t.files.find(t=>t.scope===e),r=n?.problems.find(gx);return n&&r?{kind:"file-problem",path:n.path,reason:r.reason}:void 0}function b0(e,t){return e.servers.filter(e=>e.scope===t).map(e=>e.name)}function b1(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 b2(e,t,n){switch(e.kind){case"trust-too-broad":return t(b3[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(b4[e.kind])}}let b4={"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"},b3={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 b8(e){return fY(tS(e))}function b6(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}let b5=[{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"}],b9=new Set(["name-derived","name-sanitized","name-deduplicated","name-taken"]);function b7(e){let{notes:t,fields:n=[]}=e,{t:r}=(0,ns.s)();if(0===t.length)return null;let i={error:0,warning:1,info:2},s=[...t].sort((e,t)=>i[bO(e)]-i[bO(t)]);return(0,d.jsx)("ul",{className:"mcp-add-notes",children:s.map((e,t)=>(0,d.jsx)("li",{className:`mcp-add-note is-${bO(e)}`,children:bW(e,r,n)},`${t}\0${e.code}`))})}let ye={"server-invalid":"mcp.add.refused.server-invalid","web-password":"mcp.add.blocked.web-password"};function yt(e){let{data:t,cwd:n,draft:r,busy:i,controlsBusy:s,failure:l,onDraftChange:a,onSubmit:o,onTrustProject:c}=e,{t:p}=(0,ns.s)(),h=(0,u.useId)(),m=(0,u.useId)(),f=(0,u.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:gw(r)});let s=r.trustFolder;return s?s.allowed?{kind:"trust-and-write",folder:r.cwd}:n("trust-too-broad"===s.reason?{kind:"trust-too-broad",breadth:s.breadth}:{kind:"folder-not-fresh"}):n({kind:"project-untrusted",trustable:!1})}(n,r),l=e=>bw(t.text,{rawPi:t.rawPi,takenNames:b0(n,e)}),a=l(t.scope??"global"),o=a.ok?a.servers[Math.min(t.server,a.servers.length-1)]:void 0,c=t.scope??(o?.scopeHint==="project"&&"write"===s.kind?"project":"global");c!==(t.scope??"global")&&(o=(a=l(c)).ok?a.servers[Math.min(t.server,a.servers.length-1)]:void 0);let d={parsed:a,name:t.name??"",scope:c,projectMode:s,..."blocked"===s.kind?{projectBlock:s.block}:{},values:{},pasteSecrets:[],secretReferences:{},fieldProblems:{},secretPaths:[],trustFolder:!1},u=gB(n.mcp);if(!o)return{...d,submitBlock:{kind:u?"mcp-off":"nothing"}};let p=t.name??o.name,h=function(e,t){let n={};for(let r of e.fields){let e=t.references[r.id];void 0!==e&&bK(r)?n[r.id]={reference:e}:void 0!==t.values[r.id]&&(n[r.id]=t.values[r.id])}return n}(o,t),m=bS(o).map(xK),f=Object.fromEntries(m.flatMap(e=>{let n=t.secretReferences[e];return void 0===n?[]:[[e,n]]})),g=bE(o,h,f),x={};if(!g.ok)for(let e of g.notes){let t=e.params?.field;"field-required"===e.code||"string"!=typeof t||t in x||(x[t]=e)}let v=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={};for(let n of e.fields){let e=t[n.id];"object"==typeof e?r[n.id]=bq.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=bE(e,r,Object.fromEntries(Object.entries(n).map(e=>{let[t,n]=e;return[t,bq.test(n.trim())?n:"VALUE"]})));return i.ok?i.secretPaths:[]}(o,h,f),b=function(e,t,n){let r=n?.ok?n.config:e.config,i=n?.ok?function(e,t){let n=new Set;for(let r of e.fields){let e=t[r.id];if("password"!==r.kind||"string"!=typeof e||""===e.trim())continue;let i=e.trim();n.add(i),n.add(i.replace(/\$/g,"$$$$")),n.add(encodeURIComponent(i))}return[...n].filter(e=>""!==e).sort((e,t)=>t.length-e.length)}(e,t):[],s=!1!==r.enabled,l={source:e.source,commandFields:bA(r).filter(e=>{let{value:t}=e;return xW(t)}).map(bX),variableReferences:bA(r).map(e=>({...bX(e),variables:xF(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=bG(r.url,i);return{...l,transport:"http",target:fY(e.text),envNames:[],headerNames:Object.keys(r.headers??{}),masked:e.masked}}let a=bG(fQ(r.command,r.args??[]),i);return{...l,transport:"stdio",target:a.text,...void 0!==r.cwd?{cwd:fY(r.cwd)}:{},envNames:Object.keys(r.env??{}),headerNames:[],masked:a.masked}}(o,h,g),y=g.ok?vm(p,g.config):void 0,w="blocked"===s.kind?s.block:v.length>0?{kind:"secret",fields:v,fixed:!v.every(bY)}:bQ("project",n),j=b0(n,c),k=n.files.find(e=>e.scope===c);if(u)i={kind:"mcp-off"};else if(x2.test(p))if(j.includes(p))i={kind:"name-taken",name:p,suggestedName:x4(p,j),...k?{path:k.path}:{}};else if(g.ok)if(y)i={kind:"config-invalid",note:{code:"invalid-config",params:"url"===y.problem?{...y,url:b.target}:y}};else if(void 0!==function(e,t){for(let{value:n,...r}of bA(e))if(t.isCommandConfigValue(n)?n.toUpperCase().includes(bI):t.getConfigValueEnvVarNames(n).some(e=>e.toUpperCase()===bI))return r}(g.config,{isCommandConfigValue:xW,getConfigValueEnvVarNames:xF}))i={kind:"web-password"};else if("project"===c&&w)i={kind:"scope",block:w};else{let e=bQ(c,n);e&&(i={kind:"scope",block:e})}else{let e=e=>{let t=String(e.params?.field??"");return o.fields.find(e=>e.id===t)?.label??t},t=g.notes.filter(e=>"field-required"===e.code||"field-reference-invalid"===e.code&&e.params?.problem==="missing");i=t.length>0?{kind:"fields",fields:[...new Set(t.map(e))]}:{kind:"field-invalid",fields:[...new Set(g.notes.map(e))]}}else i={kind:"name-invalid"};return void 0===t.scope&&"project"===c&&w?e({...t,scope:"global"},n,r):{parsed:a,server:o,name:p,scope:c,projectMode:s,...w?{projectBlock:w}:{},values:h,pasteSecrets:m,secretReferences:f,fill:g,fieldProblems:x,secretPaths:v,preview:b,...i?{submitBlock:i}:{},trustFolder:"project"===c&&"trust-and-write"===s.kind}})(r,t,n),[r,t,n]),g=(0,u.useMemo)(()=>(function(e){let t=bw(e,{rawPi:!0});if(!t.ok)return!1;let n=bw(e,{rawPi:!1});return t.servers.some((e,t)=>e.rawPi&&!(n.ok&&n.servers[t]?.rawPi))})(r.text),[r.text]),{parsed:x,server:v,preview:b,projectBlock:y,submitBlock:w}=f,j=v?[...v.notes,...x.notes].filter(e=>"literal-secret"!==e.code||!f.pasteSecrets.includes(String(e.params?.field))):[],k=void 0!==r.name&&r.name!==v?.name?[]:j.filter(e=>b9.has(e.code)),S=j.filter(e=>!b9.has(e.code)),C=!i&&!s&&void 0===w,N=()=>{C&&o(b1(r,f))},E=e=>a({...r,...e}),M=t.files.find(e=>e.scope===f.scope)?.path??("project"===f.scope&&n?`${n.replace(/[\\/]+$/,"")}/.pi/mcp.json`:"mcp.json"),$=w&&(""!==r.text.trim()||"mcp-off"===w.kind)?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];switch(e.kind){case"mcp-off":return t("mcp.reason.mcp-off");case"nothing":return t("mcp.add.blocked.nothing");case"name-invalid":return t("mcp.add.nameInvalid");case"name-taken":return t("mcp.add.nameTaken",{name:fY(e.name),path:e.path?b8(e.path):"mcp.json"});case"fields":return t("mcp.add.blocked.fields",{fields:e.fields.map(fY).join(", ")});case"field-invalid":return t("mcp.add.blocked.fieldsInvalid",{fields:e.fields.map(fY).join(", ")});case"config-invalid":return bW(e.note,t,n);case"web-password":return t("mcp.add.blocked.web-password");case"scope":return b2(e.block,t,b8)}}(w,p,v?.fields):void 0,I=y?.kind==="project-untrusted"&&y.trustable&&c,T=b?"http"===b.transport?b.headerNames:b.envNames:[];return(0,d.jsxs)(mm,{title:p("mcp.add.title"),catalogs:b5,target:(0,d.jsxs)(mp,{value:f.scope,label:p("config.saveTo"),options:[{value:"global",label:b6("global",p)},{value:"project",label:b6("project",p),disabled:void 0!==y&&"project"!==f.scope}],path:b8(M),disabledReason:y?b2(y,p,b8):null,onChange:e=>E({scope:e}),children:[I&&(0,d.jsx)("span",{className:"mcp-config-line",children:(0,d.jsx)(mw,{size:"small",onClick:c,children:p("mcp.trust.trustButton")})}),f.trustFolder&&"trust-and-write"===f.projectMode.kind&&(0,d.jsx)("p",{className:"mcp-config-line is-warning",children:p("mcp.add.trustExplain",{path:b8(f.projectMode.folder)})})]}),inputLabel:p("mcp.add.inputLabel"),inputId:"mcp-add-source",placeholder:p("mcp.add.placeholder"),value:r.text,canSubmit:C,onValueChange:e=>a(bz(r,{text:e})),onSubmit:N,examplesLabel:p("mcp.add.examples"),examples:""===r.text.trim()?bH.map(e=>{let{source:t,text:n}=e;return{label:p(bD[t]),value:n}}):[],multiline:!0,children:[(0,d.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.modelHint")}),g&&(0,d.jsxs)("label",{className:"mcp-add-toggle",children:[(0,d.jsx)("input",{type:"checkbox",checked:r.rawPi,onChange:e=>a(bz(r,{rawPi:e.target.checked}))}),(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-line",children:p("mcp.add.rawPi")}),r.rawPi&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.rawPiOn")})]})]}),!x.ok&&""!==r.text.trim()&&(0,d.jsx)(b7,{notes:x.notes}),x.ok&&x.servers.length>1&&(0,d.jsxs)(ma,{label:p("mcp.add.serverLabel"),children:[(0,d.jsx)("select",{className:"mcp-add-input","aria-label":p("mcp.add.serverLabel"),value:String(x.servers.indexOf(v??x.servers[0])),onChange:e=>E({server:Number(e.target.value),name:void 0,values:{},references:{},secretReferences:{}}),children:x.servers.map((e,t)=>(0,d.jsx)("option",{value:t,children:fY(e.name)},`${t}\0${e.name}`))}),(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.serverCount",{count:x.servers.length})})]}),v&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ma,{label:p("config.name"),children:(0,d.jsx)("input",{id:m,className:"mcp-add-input","aria-label":p("config.name"),value:f.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:e=>E({name:e.target.value})})}),(0,d.jsx)(b7,{notes:k,fields:v.fields}),w?.kind==="name-taken"&&(0,d.jsx)("span",{className:"mcp-config-line",children:(0,d.jsx)(mw,{size:"small",onClick:()=>E({name:w.suggestedName}),children:p("mcp.add.useName",{name:fY(w.suggestedName)})})})]}),v&&b&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ml,{children:p("mcp.add.preview")}),(0,d.jsxs)(mo,{children:[(0,d.jsx)(mc,{label:p("mcp.add.readAs"),children:p(bD[b.source])}),(0,d.jsx)(mc,{label:p("mcp.detail.transport"),children:p(`mcp.transport.${b.transport}`)}),(0,d.jsx)(mc,{label:"http"===b.transport?p("mcp.detail.url"):p("mcp.detail.command"),tone:"plain",mono:!0,children:b.target}),"stdio"===b.transport&&void 0!==b.cwd&&(0,d.jsx)(mc,{label:p("mcp.detail.cwd"),mono:!0,children:b.cwd}),T.length>0&&(0,d.jsx)(mc,{label:"http"===b.transport?p("mcp.detail.headers"):p("mcp.detail.env"),children:(0,d.jsx)(yn,{names:T})}),b.commandFields.length>0&&(0,d.jsx)(mc,{label:p("mcp.detail.shellCommands"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.server.commandFields")}),(0,d.jsx)("span",{className:"mcp-config-chips",children:b.commandFields.map(e=>{let t=f2(e);return(0,d.jsx)("code",{className:"mcp-config-chip",children:p(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})]})}),b.variableReferences.length>0&&(0,d.jsx)(mc,{label:p("mcp.detail.variables"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:p("http"===b.transport?"mcp.server.sendsVariables":"mcp.server.passesVariables")}),(0,d.jsx)("span",{className:"mcp-config-chips",children:f8(b.variableReferences).map(e=>{let{variable:t,field:n}=e,r=f2(n);return(0,d.jsx)("code",{className:"mcp-config-chip",children:p("mcp.server.variableIn",{variable:fY(t),field:p(r.key,r.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})})]}),(0,d.jsxs)("div",{className:"mcp-config-lines",children:[b.unfilled&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.add.previewUnfilled")}),b.masked&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:p("mcp.server.masked")})]}),(0,d.jsx)(b7,{notes:S,fields:v.fields}),v.fields.length>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ml,{children:p("mcp.add.fields")}),v.fields.map(e=>{var t;let n;return(0,d.jsx)(yr,{field:e,fields:v.fields,draft:r,suggestedName:(t=f.name,(n=e.targets[0])?bJ(xK(n.path),t):void 0),problem:f.fieldProblems[e.id],onDraftChange:a},e.id)})]}),f.pasteSecrets.length>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ml,{children:p("mcp.add.secrets")}),f.pasteSecrets.map(e=>{var t,n;let i;return(0,d.jsx)(yi,{label:e,draft:r,suggestedName:bJ(e,f.name),stored:f.fill?.ok?(t=f.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)&&xu(i)?i:void 0):void 0,problem:f.fieldProblems[e],onDraftChange:a},e)})]})]}),(0,d.jsx)(mw,{variant:"primary",className:"is-pushed-right",disabled:!C,"aria-busy":i||void 0,"aria-describedby":$?h:void 0,onClick:N,children:i?p("mcp.add.adding"):f.trustFolder?p("mcp.add.buttonTrust"):p("mcp.add.button")}),$&&(0,d.jsx)("p",{id:h,className:`mcp-config-line ${w?.kind==="scope"?"is-warning":"is-dim"}`,children:$}),v&&!w&&(0,d.jsx)("p",{className:"mcp-config-line is-dim",children:p("mcp.add.afterAdd")}),l&&(0,d.jsxs)("div",{role:"alert",className:"mcp-add-failure",children:[(0,d.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(b3[e.breadth.kind],{path:b8(e.breadth.path)});if("secret-global-only"===e.reason&&e.fields)return t(e.fields.every(bY)?"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:fY(e.name),path:e.path?b8(e.path):"mcp.json"});let n=e.reason?ye[e.reason]:void 0;return n?t(n,{error:fY(e.error)}):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):fY(e.error)}(l,p)]}),l.trustKept&&(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.trustKept",{folder:b8(l.trust?.decisionPath??n??"")})}),l.notes&&l.notes.length>0&&(0,d.jsx)(b7,{notes:l.notes,fields:v?.fields}),"name-taken"===l.reason&&l.suggestedName&&w?.kind!=="name-taken"&&(0,d.jsx)("span",{className:"mcp-config-line",children:(0,d.jsx)(mw,{size:"small",onClick:()=>E({name:l.suggestedName}),children:p("mcp.add.useName",{name:fY(l.suggestedName)})})}),"host-env-confirm"===l.reason&&l.names&&l.names.length>0&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:p("mcp.add.hostEnv.body",{names:l.names.map(fY).join(", ")})}),(0,d.jsx)("span",{className:"mcp-config-line",children:(0,d.jsx)(mw,{variant:"danger",size:"small",disabled:i||s||void 0!==w,onClick:()=>o(b1(r,f,l.names)),children:p("mcp.add.hostEnv.confirm")})})]})]})]})}function yn(e){let{names:t}=e,{t:n}=(0,ns.s)();return(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(e)},e))}),(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:n("mcp.detail.valuesHidden")})]})}function yr(e){let t,{field:n,fields:r,draft:i,suggestedName:s,problem:l,onDraftChange:a}=e,{t:o}=(0,ns.s)(),c=(0,u.useId)(),p=l?{"aria-invalid":!0,"aria-describedby":c}:{},h=bK(n),m=h?i.references[n.id]:void 0,f=void 0!==m,g=fY(n.label),x=i.values[n.id]??n.defaultValue??"",v=bF[n.reason],b=n.optional&&1===(t=new Set(n.targets.map(e=>{let{path:t}=e;return"headers"===t[0]?t[1]:void 0}))).size?[...t][0]:void 0,y=f?m&&!l?bU(n,r,"${"+m+"}",!0):void 0:bU(n,r,`‹${o("mcp.add.field.slot")}›`),w=e=>a({...i,values:{...i.values,[n.id]:e}}),j=e=>{let t={...i.references};void 0===e?delete t[n.id]:t[n.id]=e,a({...i,references:t})};return(0,d.jsxs)("div",{className:"mcp-add-field",children:[(0,d.jsx)(ma,{label:g,children:f?(0,d.jsx)("input",{className:"mcp-add-input","aria-label":o("mcp.add.field.variableName",{field:g}),value:m,placeholder:s??"GITHUB_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>j(e.target.value)}):"select"===n.kind?(0,d.jsxs)("select",{className:"mcp-add-input","aria-label":g,value:x,...p,onChange:e=>w(e.target.value),children:[!n.options?.includes(x)&&(0,d.jsx)("option",{value:"",children:o("mcp.add.field.choose")}),(n.options??[]).map(e=>(0,d.jsx)("option",{value:e,children:fY(e)},e))]}):(0,d.jsx)("input",{className:"mcp-add-input",type:"password"===n.kind?"password":"text","aria-label":g,value:x,autoComplete:"off",placeholder:n.placeholder?fY(n.placeholder):void 0,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...p,onChange:e=>w(e.target.value)})}),l&&(0,d.jsx)("span",{id:c,className:"mcp-config-line is-error",children:bW(l,o,[n])}),(0,d.jsxs)("span",{className:"mcp-config-lines",children:[n.description&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:fY(n.description)}),v&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:o(v)}),f?(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:y?o("mcp.add.field.storedAsVariable",{value:y}):o("mcp.add.field.variableHint")}):(0,d.jsxs)(d.Fragment,{children:[y&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:o("mcp.add.field.storedAs",{value:y})}),n.optional&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:b?o("mcp.add.field.optionalHeader",{name:fY(b)}):o("mcp.add.field.optional")})]})]}),h&&(0,d.jsxs)("label",{className:"mcp-add-toggle",children:[(0,d.jsx)("input",{type:"checkbox",checked:f,onChange:e=>j(e.target.checked?s??"":void 0)}),(0,d.jsx)("span",{className:"mcp-config-line",children:o("mcp.add.field.useVariable")})]})]})}function yi(e){let{label:t,draft:n,suggestedName:r,stored:i,problem:s,onDraftChange:l}=e,{t:a}=(0,ns.s)(),o=(0,u.useId)(),c=n.secretReferences[t],p=void 0!==c,h=fY(t),m=e=>{let r={...n.secretReferences};void 0===e?delete r[t]:r[t]=e,l({...n,secretReferences:r})};return(0,d.jsxs)("div",{className:"mcp-add-field",children:[(0,d.jsx)("span",{className:"mcp-config-lines",children:(0,d.jsxs)("span",{className:"mcp-config-line",children:[(0,d.jsx)("code",{className:"mcp-config-chip",children:h})," ",a("mcp.add.secret.holds")]})}),(0,d.jsxs)("label",{className:"mcp-add-toggle",children:[(0,d.jsx)("input",{type:"checkbox",checked:p,onChange:e=>m(e.target.checked?r??"":void 0)}),(0,d.jsx)("span",{className:"mcp-config-line",children:a("mcp.add.field.useVariable")})]}),p&&(0,d.jsx)(ma,{label:a("mcp.add.field.variableName",{field:h}),children:(0,d.jsx)("input",{className:"mcp-add-input","aria-label":a("mcp.add.field.variableName",{field:h}),value:c,placeholder:r??"API_TOKEN",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",...s?{"aria-invalid":!0,"aria-describedby":o}:{},onChange:e=>m(e.target.value)})}),s&&(0,d.jsx)("span",{id:o,className:"mcp-config-line is-error",children:bW(s,a)}),(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:p?void 0!==i?a("mcp.add.secret.storedAs",{value:fY(i)}):a("mcp.add.field.variableHint"):a("mcp.add.secret.asPasted")})]})}let ys=new Set(["done","failed","cancelled","expired"]);function yl(e){var t;return e?.flow!==void 0&&!e.gone&&(t=e.flow.phase,!ys.has(t))}let ya={"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"},yo={"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"},yc={connecting:"mcp.signIn.phase.connecting",starting:"mcp.signIn.phase.starting",finishing:"mcp.signIn.phase.finishing"},yd={"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 yu(e,t,n){var r;let i={...e,flow:t,deadlineAt:n+t.expiresInMs,gone:!1};return r=t.phase,ys.has(r)&&(delete i.pasteError,delete i.cancelError,i.pasting&&(i.pasting=!1),i.cancelling&&(i.cancelling=!1)),i}function yp(e){return"sign-in-unknown"===e.reason}async function yh(e,t,n,r){return g$(e,{...t,signal:r},n,e=>null!==e&&"object"==typeof e&&"string"==typeof e.flowId&&"string"==typeof e.phase&&"string"==typeof e.name&&("global"===e.scope||"project"===e.scope)&&"number"==typeof e.expiresInMs?e:void 0)}function ym(e,t,n,r,i){let s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},l=t.method??"GET";return gT(r=>yh(e,t,n,r),()=>({ok:!1,error:{error:`${l} ${e} did not answer within ${i} ms`,timedOut:!0}}),i,r,s)}function yf(e){return`/api/mcp/sign-in/${encodeURIComponent(e)}`}function yg(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?yo[e.reason]:void 0;return r?t(r):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function yx(e){let{server:t,run:n,block:r,signOutBlock:i,blockSaidBy:s,signOutBlockSaidBy:l,controlsBusy:a,signingOut:o,onSignIn:c,onSignOut:p,onPaste:h,onCancel:m}=e,{t:f}=(0,ns.s)(),g=(0,u.useId)(),x=(0,u.useId)(),v=(0,u.useId)(),b=(0,u.useRef)(null),y=(0,u.useRef)(null),w=yl(n),j=(0,u.useRef)(w);if((0,u.useEffect)(()=>{let e=j.current;j.current=w,!e&&w?t_(document,y.current):e&&!w&&t_(document,b.current)},[w]),!t.usesOAuth)return void 0===t.authProvider&&t.headerNames.some(e=>"authorization"===e.toLowerCase())?null:(0,d.jsx)(mc,{label:f("mcp.detail.signIn"),children:void 0!==t.authProvider?f("mcp.signIn.provider",{provider:fY(t.authProvider)}):f("mcp.signIn.header")});let k=n?.flow,S=n?.starting===!0,C=void 0!==k&&(k.scope!==t.scope||k.name!==t.name),N=(t.oauthStateStored??t.signedIn)!==!1,E=S||o||void 0!==r,M=a||S||void 0!==i,$=k?.phase==="finishing";return(0,d.jsx)(mc,{label:f("mcp.detail.signIn"),tone:"plain",children:(0,d.jsxs)("div",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-line",children:f(!0===t.signedIn?"mcp.signIn.signedIn":!1===t.signedIn?t.oauthStateStored?"mcp.signIn.registrationOnly":"mcp.signIn.notSignedIn":"mcp.signIn.unknown")}),k&&w&&C&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:f("mcp.signIn.shared",{name:fY(k.name)})}),k&&w&&("authorize"===k.phase?(0,d.jsx)(yv,{flow:k,pasting:n?.pasting===!0,pasteError:n?.pasteError,onPaste:e=>h(t,k.flowId,e)},k.flowId):(0,d.jsx)("span",{role:"status",className:"mcp-config-line",children:f(yc[k.phase]??"mcp.signIn.phase.connecting")})),k&&w&&$&&(0,d.jsx)("span",{id:v,className:"mcp-config-line is-dim",children:f("mcp.signIn.phase.noCancel")}),k&&!w&&!n?.gone&&(0,d.jsx)(yb,{flow:k,shared:C}),n?.gone&&(0,d.jsx)("span",{role:"alert",className:"mcp-config-line is-warning",children:f("mcp.signIn.gone")}),n?.error&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[f("mcp.signIn.requestFailed")," ",yg(n.error,f)]}),w&&n?.cancelError&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[f("mcp.signIn.cancelFailed")," ",yg(n.cancelError,f,"mcp.signIn.cancelTimedOut")]}),n?.signOutError&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[f("mcp.signIn.signOutFailed")," ",yg(n.signOutError,f,"mcp.actionTimedOut")]}),n?.signedOut&&(0,d.jsx)("span",{role:"status",className:"mcp-config-line",children:f(n.signedOut.removed?"mcp.signIn.signedOutDone":"mcp.signIn.signedOutNothing")}),r&&!s&&(0,d.jsx)("span",{id:g,className:"mcp-config-line is-dim",children:f(ya[r])}),!r&&i&&!l&&N&&!w&&(0,d.jsx)("span",{id:x,className:"mcp-config-line is-dim",children:f(ya[i])}),(0,d.jsxs)("div",{className:"mcp-sign-in-actions",children:[w&&k?(0,d.jsx)(mw,{ref:y,size:"small",disabled:n?.cancelling===!0||$,"aria-busy":n?.cancelling===!0||void 0,"aria-describedby":$?v:void 0,onClick:()=>m(t,k.flowId),children:f(n?.cancelling?"mcp.signIn.cancelling":"mcp.signIn.cancel")}):(0,d.jsx)(mw,{ref:b,size:"small",variant:"primary",disabled:E,"aria-busy":S||void 0,"aria-describedby":r?s??g:void 0,onClick:()=>c(t),children:f(S?"mcp.signIn.starting":"mcp.signIn.button")}),N&&!w&&(0,d.jsx)(mw,{size:"small",disabled:M,"aria-busy":o||void 0,"aria-describedby":i?r?s??g:l??x:void 0,onClick:()=>p(t),children:f(o?"mcp.signIn.signingOut":"mcp.signIn.signOut")})]}),!r&&!w&&N&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:f("mcp.signIn.replaces")}),N&&!i&&!w&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:f("mcp.signIn.signOutExplain")})]})})}function yv(e){let{flow:t,pasting:n,pasteError:r,onPaste:i}=e,{t:s}=(0,ns.s)(),[l,a]=(0,u.useState)(""),o=(0,u.useRef)(null),c=(0,u.useRef)(n);(0,u.useEffect)(()=>{let e=c.current;c.current=n,e&&!n&&t_(document,o.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,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(mz,{message:s("mcp.signIn.authorize.message"),hint:p?(0,d.jsxs)(d.Fragment,{children:[s("mcp.signIn.authorize.link")," ",(0,d.jsx)("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:fY(p)})]}):(0,d.jsxs)(d.Fragment,{children:[s("mcp.signIn.authorize.notALink")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.authorizationUrl??"")})]}),value:l,placeholder:s("mcp.signIn.paste.placeholder"),inputLabel:s("mcp.signIn.paste.label"),submitLabel:s(n?"mcp.signIn.paste.checking":"mcp.signIn.paste.submit"),disabled:n,plainEnterSubmits:!1,inputRef:o,onValueChange:a,onSubmit:()=>i(l)}),r&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[s("mcp.signIn.paste.refused")," ",yg(r,s,"mcp.signIn.paste.timedOut"),"redirect-denied"===r.reason&&r.error&&(0,d.jsxs)(d.Fragment,{children:[" ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(r.error)})]})]}),t.redirectUrl&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.signIn.authorize.redirect",{url:fY(t.redirectUrl)})}),(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:s("mcp.signIn.authorize.wait")})]})}function yb(e){let{flow:t,shared:n}=e,{t:r}=(0,ns.s)(),i=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 yd[e.failure??"internal"];case"cancelled":return"mcp.signIn.cancelled";case"expired":return"mcp.signIn.expired";default:return}}(t,n);if(!i)return null;let s=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,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{role:"status",className:"error"===s?"mcp-config-line is-error":"warning"===s?"mcp-config-line is-warning":"mcp-config-line",children:r(i,{name:fY(t.name)})}),t.error&&(0,d.jsxs)("span",{className:"mcp-config-line is-error",children:[r("mcp.test.error")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.error)})]})]})}function yy(e,t){return t("project"===e?"skills.scope.project":"skills.scope.global")}function yw(e){return fY(tS(e))}function yj(e,t){let{key:n,params:r}=e;return r?t(n,void 0===r.path?r:{...r,path:yw(r.path)}):t(n)}function yk(e,t){return e.timedOut?t("mcp.loadTimedOut"):e.reason&&"internal"!==e.reason?t(`mcp.reason.${e.reason}`):e.error}function yS(e,t){return e.timedOut?t("mcp.actionTimedOut"):yk(e,t)}function yC(){if("u"<typeof document)return null;let e=document.activeElement;return e instanceof HTMLButtonElement||e instanceof HTMLSelectElement?e:null}function yN(e){let{cwd:t,onClose:n,embedded:r=!1,trust:i,onTrustProject:s,onProjectTrustChanged:l}=e,[a,o]=(0,u.useState)({state:"loading"}),[c,p]=(0,u.useState)(!1),[h,m]=(0,u.useState)(()=>hC("mcp",t)),[f,g]=(0,u.useState)({saving:!1,error:null}),[x,v]=(0,u.useState)(null),[b,y]=(0,u.useState)(null),[w,j]=(0,u.useState)(null),[k,S]=(0,u.useState)(null),[C,N]=(0,u.useState)(null),[E,M]=(0,u.useState)({}),$=(0,u.useRef)(0),I=(0,u.useRef)(null),T=(0,u.useRef)(null),R=(0,u.useRef)(null),A=(0,u.useRef)(new Map),[L,P]=(0,u.useState)({}),z=(0,u.useRef)(L);z.current=L;let[O,W]=(0,u.useState)(0),[F,D]=(0,u.useState)(!1),[_,B]=(0,u.useState)(bL),H=(0,u.useRef)(_);H.current=_;let[U,K]=(0,u.useState)(null),[q,V]=(0,u.useState)(null),Z=(0,u.useRef)(!0),J=(0,u.useRef)(a);J.current=a;let Y=(0,u.useCallback)(async()=>{let e=++$.current;I.current?.abort();let n=new AbortController;I.current=n,p(!0);let r=await gz(t,void 0,n.signal);if(e===$.current){if(p(!1),!r.ok)return void o({state:"failed",error:r.error});o({state:"loaded",data:r.data,...r.projectError?{projectError:r.projectError}:{}}),m(e=>gy(gv(r.data,!!t),e))}},[t]),G=fd(i);(0,u.useEffect)(()=>(Y(),()=>{$.current+=1,I.current?.abort()}),[Y,G]);let X=(0,u.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"preference"});let n=await gF(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"preference"}),n.ok&&o(e=>{var t,r;let i;return"loaded"===e.state?{...e,data:(t=e.data,r=n.preference,i={...t.codemode,preference:r},delete i.preferenceError,{...t,codemode:i})}:e}),Y())},[Y]),Q=(0,u.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"mode"});let n=await gD(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"mode"}),n.ok&&o(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.mode;if(!n)return e;let r={settingsPath:n.settingsPath,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,mode:r}}}(e.data,n.mode)}:e),Y())},[Y]),ee=(0,u.useCallback)(async e=>{let t=new AbortController;T.current=t,g({saving:!0,error:null,target:"inlineBudget"});let n=await g_(e,void 0,t.signal);T.current===t&&(T.current=null,g({saving:!1,error:n.ok?null:n.error,target:"inlineBudget"}),n.ok&&o(e=>"loaded"===e.state?{...e,data:function(e,t){let n=e.codemode.inlineBudget;if(!n)return e;let r={settingsPath:n.settingsPath,default:n.default,max:n.max,...n.projectOverride?{projectOverride:n.projectOverride}:{},...t};return{...e,codemode:{...e.codemode,inlineBudget:r}}}(e.data,n.inlineBudget)}:e),Y())},[Y]);(0,u.useEffect)(()=>{let e=A.current;return Z.current=!0,()=>{Z.current=!1,T.current?.abort(),T.current=null,R.current?.abort(),R.current=null,e.clear()}},[]);let et=(0,u.useCallback)(async e=>{let n=f7(e);if(A.current.has(n))return;let r={};A.current.set(n,r),M(e=>({...e,[n]:{...e[n],running:!0,startedAt:Date.now(),error:void 0,queueTimedOut:void 0,configKey:void 0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await g4({scope:e.scope,name:e.name},s);if(A.current.get(n)!==r)return;A.current.delete(n),M(t=>({...t,[n]:function(e,t,n){let r=e?.signedOutAt,i={...e?.startedAt!==void 0?{startedAt:e.startedAt}:{},...void 0!==r?{signedOutAt:r}:{}};if(void 0!==r&&(e?.startedAt??0)<=r)return{running:!1,...i};let s=e?.response?{response:e.response}:{};return t.ok?t.data.result.queueTimedOut?{running:!1,...i,...s,queueTimedOut:!0,configKey:t.data.configKey}:{running:!1,...i,response:t.data}:{running:!1,...i,...s,error:t.error,...void 0!==n?{configKey:n}:{}}}(t[n],l,e.configKey)}));let a=J.current,o="loaded"===a.state?a.data.servers.find(e=>f7(e)===n):void 0;(l.ok?o?.configKey===l.data.configKey:void 0===l.error.reason||l.error.timedOut)||Y()},[t,Y]),en=(0,u.useCallback)((e,n)=>{$.current+=1,I.current?.abort(),p(!1),o(t=>({state:"loaded",data:e,..."loaded"===t.state&&t.projectError?{projectError:t.projectError}:{}})),m(r=>gy(gv(e,!!t),n??r))},[t]),er=(0,u.useCallback)(async e=>{let n=f7(e),r=z.current[n];if(r?.starting||yl(r))return;P(e=>({...e,[n]:{starting:!0}}));let i=J.current,s="loaded"===i.state&&i.data.project?t:null,l=await function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:(e,t)=>fetch(e,t),r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:15e3;return ym("/api/mcp/sign-in",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:e.scope,name:e.name,...t?{cwd:t}:{}})},n,r,i,{abortAtDeadline:!1})}({scope:e.scope,name:e.name},s);Z.current&&(P(e=>({...e,[n]:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();return e.ok?yu({},e.data,t):{error:e.error}}(l)})),l.ok||void 0===l.error.reason||l.error.timedOut||Y())},[t,Y]),ei=(0,u.useCallback)(async(e,t,n)=>{let r=f7(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 ym(yf(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:t})},n,r,i)}(t,n);Z.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?{...yu(i,n.data,r),pasteError:void 0}:yp(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,u.useCallback)(async(e,t)=>{let n=f7(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 ym(yf(e),{method:"DELETE"},t,n,r)}(t);Z.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?yu(i,n.data,r):yp(n.error)?{...i,gone:!0}:{...i,cancelError:n.error}}(e[n],t,r);return void 0===i||i===e[n]?e:{...e,[n]:i}})},[]),el=Object.entries(L).flatMap(e=>{let[t,n]=e;return yl(n)&&n.flow?[`${t}\x01${n.flow.flowId}`]:[]}).join("\x02");(0,u.useEffect)(()=>{if(!el)return;let e=new AbortController,t=setTimeout(async()=>{for(let t of el.split("\x02")){let[n,r]=t.split("\x01"),i=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 ym(yf(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?yu(e,n.data,r):yp(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()}},[el,O]);let ea=(0,u.useRef)(L);(0,u.useEffect)(()=>{let e=ea.current;ea.current=L,Object.keys(L).some(t=>{var n,r;return n=e[t],r=L[t],yl(n)&&!yl(r)})&&Y()},[L,Y]);let eo=(0,u.useCallback)(async(e,n,r)=>{R.current?.abort();let i=new AbortController;R.current=i,v(n);let s=J.current,l="loaded"===s.state&&s.data.project?t:null,a=await gZ(e,l,void 0,i.signal);if(R.current===i)return R.current=null,v(null),a.ok?en(a.data,r?.(a.data)):Y(),a},[en,t,Y]),ec=(0,u.useCallback)(async(e,t)=>{let n=f7(e),r=yC();y(null),j(null);let i=await eo({action:t?"enable":"disable",scope:e.scope,name:e.name},`switch:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[eo]),ed=(0,u.useCallback)(async(e,t)=>{let n=f7(e),r=yC();y(null),j(null);let i=await eo({action:"set-in-project",name:e.name,enabled:t},`in-project:${n}`);i&&(i.ok||y({key:n,failure:i.error}),N({control:r}))},[eo]),eu=(0,u.useCallback)(async(e,t)=>{let n=f7(e),r=yC();y(null),j(null);let i=await eo({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}))},[eo]),ep=(0,u.useCallback)(async e=>{let t=f7(e),n=yC();y(null),j(null);let r=await eo({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})},[eo]),eh=(0,u.useCallback)(async()=>{if(!k)return;let e=yC();y(null),j(null),S({...k,undoing:!0,error:void 0});let t=await eo({action:"undo",token:k.token},"undo",e=>e.restored?f7(e.restored):void 0);t&&(S(e=>e?.token!==k.token?e:t.ok?null:{...e,undoing:!1,error:t.error}),t.ok||N({control:e}))},[eo,k]),em=(0,u.useCallback)(async e=>{let t=f7(e),n=yC();y(null),j(null),P(e=>({...e,[t]:{...e[t],signOutError:void 0,signedOut:void 0}}));let r=await eo({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();M(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})}},[eo]),ef=(0,u.useCallback)(async e=>{let n=yC(),r=H.current;y(null),j(null),K(null);let i=await eo(e,"add",e=>e.added?f7(e.added):void 0);if(!i)return;let s=H.current!==r;if(!i.ok){s||K(i.error),i.error.trust&&t&&l?.(t,i.error.trust),N({control:n});return}let{added:a,trust:o,trustedFolder:c}=i.data;if(D(!1),s||B(bL),N({control:null,toSelectedRow:!0}),!a)return;V({...a,key:f7(a),...c&&t?{trustedFolder:t}:{}}),o&&t&&l?.(t,o);let d=i.data.servers.find(e=>f7(e)===f7(a));d&&!gY(d,i.data)&&et(d)},[t,l,eo,et]),eg=k?.token,ex=k?.expiresInMs;(0,u.useEffect)(()=>{if(void 0===eg||void 0===ex)return;let e=setTimeout(()=>S(e=>e?.token===eg?null:e),ex);return()=>clearTimeout(e)},[eg,ex]);let ev=(0,u.useCallback)(async(e,t,n)=>{let{targets:r,keptOff:i}={targets:fc(t,n,e=>e.enabled).filter(n?gq:gK),keptOff:n?t.filter(e=>!e.enabled&&gK(e)&&!gq(e)).length:0},s=yC();if(y(null),j(i>0?{scope:e,keptOff:i,failures:[],total:0}:null),0===r.length)return;let l=await eo({action:"set-enabled",enabled:n,servers:r.map(e=>{let{scope:t,name:n}=e;return{scope:t,name:n}})},`group:${e}`);if(!l)return;if(N({control:s}),!l.ok)return void j({scope:e,keptOff:i,failures:[],total:r.length,error:l.error});let a=l.data.results??[],o=a.filter(e=>void 0!==e.reason).map(e=>({name:e.name,failure:{error:e.error??"",reason:e.reason}}));j(o.length>0||i>0?{scope:e,keptOff:i,failures:o,total:a.length}:null)},[eo]);return(0,u.useEffect)(()=>{h&&hN("mcp",h,t)},[t,h]),(0,d.jsx)(yE,{cwd:t,load:a,selected:h,refreshing:c,embedded:r,codemodeSave:f,busy:x,actionError:b,groupStatus:w,undo:k,focusBack:C,tests:E,signIns:L,adding:F,addDraft:_,addFailure:U,added:q,onAddOpen:()=>{D(!0),V(null),y(null)},onAddDraftChange:e=>{H.current=e,B(e),K(null)},onAddSubmit:e=>void ef(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),V(t=>t?.key===e?t:null)},onRefresh:()=>void Y(),onCodemodeChange:e=>void X(e),onCodemodeModeChange:e=>void Q(e),onCodemodeInlineBudgetSave:e=>void ee(e),onServerSwitch:(e,t)=>void ec(e,t),onServerSwitchInProject:(e,t)=>void ed(e,t),onExposureChange:(e,t)=>void eu(e,t),onGroupSwitch:(e,t,n)=>void ev(e,t,n),onRemove:e=>void ep(e),onUndo:()=>void eh(),onTrustProject:s,onClose:n})}function yE(e){var t,n,r,i;let s,l,a,{cwd:o,load:c,selected:p,refreshing:h,embedded:m,codemodeSave:f={saving:!1,error:null},busy:g=null,actionError:x=null,groupStatus:v=null,undo:b=null,focusBack:y=null,tests:w={},signIns:j={},adding:k=!1,addDraft:S=bL,addFailure:C=null,added:N=null,onAddOpen:E=()=>{},onAddDraftChange:M=()=>{},onAddSubmit:$=()=>{},onSelect:I,onRefresh:T,onCodemodeChange:R,onCodemodeModeChange:A=()=>{},onCodemodeInlineBudgetSave:L=()=>{},onServerSwitch:P=()=>{},onServerSwitchInProject:z=()=>{},onExposureChange:O=()=>{},onGroupSwitch:W=()=>{},onRemove:F=()=>{},onUndo:D=()=>{},onTest:_=()=>{},onSignIn:B=()=>{},onSignOut:H=()=>{},onSignInPaste:U=()=>{},onSignInCancel:K=()=>{},onTrustProject:q,onClose:V}=e,{t:Z}=(0,ns.s)(),J=(0,u.useId)(),Y=(0,u.useId)(),G="loaded"===c.state?(t=c.data,s=!1,l=t.servers.map(e=>{var t;let n=w[f7(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;s=!0;let r={...n.result,origin:"test"};return{...e,status:r}}),s?{...t,servers:l}:t):void 0,X=G?gv(G,!!o):[],Q=G?{mcpAvailable:G.mcp.available,projectServersLoad:ge(G.project)}:void 0,ee=X.flatMap(e=>e.servers),et=ee.find(e=>f7(e)===p),en=N?ee.find(e=>f7(e)===N.key):void 0,er=G?function(e){if(!e.available)return"builtin-disabled"===e.reason?e.settingsPath?{key:"mcp.unavailable.builtin-disabled",params:{path:e.settingsPath}}:{key:"mcp.unavailable.builtin-disabled-unknown"}:{key:"operator-disabled"===e.reason?"mcp.unavailable.operator-disabled":"mcp.unavailable.internals-unavailable"}}(G.mcp):void 0,ei=er?void 0:G?.hostInactive,es=G?.files.find(e=>"project"===e.scope),el=G?function(e,t){if(!e||!t||!t.exists&&0===t.problems.length)return;let{trust:n}=e;return n?n.requiresTrust||!1===n.decision?!0===n.decision?n.inherited&&n.decisionPath?{kind:"inherited",key:"mcp.trust.trustedThrough",params:{path:n.decisionPath}}:void 0:!1===n.decision&&n.inherited&&n.decisionPath?{kind:"untrusted",key:"mcp.trust.untrustedThrough",params:{path:n.decisionPath}}:{kind:"untrusted",key:"mcp.trust.untrusted"}:void 0:{kind:"untrusted",key:"mcp.trust.unreadable"}}(G.project,es):void 0,ea=q&&gw(G?.project)?q:void 0,eo=el?.kind==="untrusted"&&void 0!==ea,ec=(0,u.useRef)(null),ed=(0,u.useRef)(null),eu=(0,u.useRef)(eo);(0,u.useEffect)(()=>{let e=eu.current;eu.current=eo,e&&!eo&&t_(document,ec.current??ed.current)},[eo]);let ep=(0,u.useRef)(null),eh=b?.token,em=(0,u.useRef)(eh);(0,u.useEffect)(()=>{let e=em.current;em.current=eh,void 0!==eh&&eh!==e?t_(document,ep.current):void 0!==e&&void 0===eh&&t_(document,ec.current??ed.current)},[eh]);let ef=G?[...G.files].sort((e,t)=>e.scope===t.scope?0:"global"===e.scope?-1:1).flatMap(e=>e.problems.map(t=>({file:e,problem:t}))):[],eg=gb(ee),ex=G?.files.find(e=>"global"===e.scope),ev=G?function(e){let t=e.files.find(e=>"project"===e.scope);if(t?.autoEnableCodemode!==void 0&&ge(e.project))return t.autoEnableCodemode?{value:!0,path:t.path}:{value:!1,path:t.path};let n=e.files.find(e=>"global"===e.scope);return n?.autoEnableCodemode!==void 0?n.autoEnableCodemode?{value:!0,path:n.path}:{value:!1,path:n.path}:{value:!0}}(G):void 0,eb=G?(n=ee.length,r=G.files,n>0?"mcp.selectItem":r.some(e=>e.problems.some(gx))?"mcp.emptyFileProblem":"mcp.empty"):void 0,ey=null!==g||h||f.saving,ew=(0,u.useRef)(null);(0,u.useEffect)(()=>{if(y&&!ey&&ew.current!==y)if(ew.current=y,y.toSelectedRow)t_(document,ec.current??ed.current);else{var e,t,n;e=document,t=y.control,n=ec.current??ed.current,t&&t_(e,t.isConnected&&!t.disabled?t:n)}},[y,ey]);let ej=e=>G?gH(e,G):void 0,ek=!!G&&gB(G.mcp),eS=X.find(e=>"project"===e.scope)?.servers??[],eC=ej("project"),eN=e=>"mcp-off"===e?er?J:void 0:e&&el?.kind==="untrusted"?Y:void 0,eE=el?.kind==="untrusted"?[yj(el,Z),eC&&"mcp-off"!==eC&&eS.length>0?Z(gU[eC]):null].filter(Boolean).join(" "):"";return(0,d.jsxs)(hX,{embedded:m,title:Z("settings.mcp"),subtitle:o?tS(o):void 0,closeLabel:Z("i18n.close"),onClose:V,children:[(0,d.jsxs)("div",{className:"mcp-config-notices",children:[er&&(0,d.jsxs)(mf,{id:J,children:[yj(er,Z),ek&&(0,d.jsxs)(d.Fragment,{children:[" ",Z(gU["mcp-off"])]}),G&&!G.mcp.available&&G.mcp.detail&&(0,d.jsxs)(d.Fragment,{children:[" ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(G.mcp.detail)})]})]}),ei&&(0,d.jsx)(mf,{children:Z("mcp.hostInactive",{path:yw(ei.cwd),owner:yw(ei.owner)})}),"loaded"===c.state&&c.projectError&&(0,d.jsx)(mf,{children:Z("mcp.projectNotListed",{reason:yk(c.projectError,Z)})}),el?.kind==="untrusted"&&(0,d.jsx)(mg,{id:Y,message:eE,trustLabel:Z("mcp.trust.trustButton"),onTrust:ea}),el?.kind==="inherited"&&(0,d.jsx)(mf,{children:yj(el,Z)}),b&&(0,d.jsxs)(mf,{action:b.error?.reason==="undo-unavailable"?void 0:(0,d.jsx)(mw,{ref:ep,size:"small",onClick:D,disabled:b.undoing||ey,children:b.undoing?Z("mcp.undoing"):Z("mcp.undo")}),children:[Z("mcp.removed",{name:fY(b.name),path:yw(b.path)}),b.error&&(0,d.jsxs)(d.Fragment,{children:[" ",Z("mcp.undoFailed")," ",yS(b.error,Z)]})]}),N&&G&&en&&(0,d.jsx)(yM,{added:N,cwd:o,server:en,testing:w[N.key]?.running===!0,signIn:j[N.key],signingOut:g===`sign-out:${N.key}`,signInBlock:en?gY(en,G):void 0,onSignIn:B})]}),(0,d.jsxs)(h4,{children:[(0,d.jsxs)(h3,{children:[(0,d.jsx)(h8,{children:"loading"===c.state?(0,d.jsx)("div",{className:"config-sidebar-message",children:Z("i18n.loading")}):"failed"===c.state?(0,d.jsxs)("div",{role:"alert",className:"config-sidebar-message is-error",children:[Z("mcp.loadFailed")," ",yk(c.error,Z)]}):G&&Q?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"config-sidebar-group",children:(0,d.jsx)(y$,{codemode:G.codemode,active:!k&&p===f9,rowRef:ec,onSelect:I})}),X.map(e=>{let t=ej(e.scope);return(0,d.jsx)(yI,{group:e,context:Q,selected:k?null:p,selectedRowRef:ec,block:t,blockNoticeId:eN(t),busy:g,controlsBusy:ey,status:v?.scope===e.scope?v:null,onSelect:I,onGroupSwitch:W},e.scope)})]}):null}),G&&(0,d.jsx)(mk,{ref:ed,active:k,onClick:E,children:Z("mcp.add.action")})]}),(0,d.jsx)(mv,{motionKey:k?"add":p??"",children:(0,d.jsx)(mt,{className:"is-fill",children:G&&Q&&ev&&eb?k?(0,d.jsx)(yt,{data:G,cwd:o,draft:S,busy:"add"===g,controlsBusy:ey,failure:C,onDraftChange:M,onSubmit:$,onTrustProject:ea}):p===f9?(0,d.jsx)(yB,{codemode:G.codemode,autoEnable:ev,save:f,serverBusy:null!==g,onChange:R,onModeChange:A,onInlineBudgetSave:L}):et?(0,d.jsx)(yA,{server:et,editCwd:G.project?.cwd??null,onEdited:T,context:Q,codemode:G.codemode,toolSearchDisabled:G.toolSearchDisabled,autoEnable:ev,block:ej(et.scope),blockNoticeId:eN(ej(et.scope)),uncheckedSaid:er?.key==="mcp.unavailable.internals-unavailable",inProject:function(e,t){if("global"!==e.scope||void 0!==e.invalidError||e.notAnObject||!ge(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:f7(r),keys:r.override.keys,applies:!0===e.overriddenByProject}:void 0:{kind:"switch"}}(et,G),inProjectBlock:ej("project"),savedWhileOff:!G.mcp.available&&!ek,busy:g,controlsBusy:ey,actionError:x?.key===f7(et)?x.failure:null,test:(i=w[f7(et)],i&&void 0!==i.configKey&&i.configKey!==et.configKey?{running:i.running,...i.response?{response:i.response}:{}}:i),testBlock:gY(et,G),signIn:j[f7(et)],signInBlock:gY(et,G),signOutBlock:(a=gH(et.scope,G))||(void 0===et.invalidError&&et.validated?void 0:"invalid"),onSwitch:P,onSwitchInProject:z,onShowServer:e=>{I(e),requestAnimationFrame(()=>t_(document,ec.current??ed.current))},onExposureChange:O,onRemove:F,onTest:_,onSignIn:B,onSignOut:H,onSignInPaste:U,onSignInCancel:K},f7(et)):(0,d.jsx)(mx,{children:"mcp.empty"===eb?Z(eb,{globalPath:yw(ex?.path??"~/.pi/agent/mcp.json")}):Z(eb)}):null})})]}),(0,d.jsxs)(mb,{status:ef.length>0?(0,d.jsx)(my,{tone:ef.some(e=>{let{problem:t}=e;return gx(t)})?"error":"warning",summary:1===ef.length?Z("mcp.footer.fileProblem"):Z("mcp.footer.fileProblems",{count:ef.length}),details:ef.map(e=>{let{file:t,problem:n}=e,r=f6(n,t.realPath);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("code",{className:"mcp-config-chip",children:yw(t.path)})," ",Z(`mcp.fileProblem.${n.reason}`),r&&(0,d.jsxs)(d.Fragment,{children:[" ",(0,d.jsx)("code",{className:"mcp-config-chip",children:r})]})]})})}):(0,d.jsx)(my,{summary:[eg.total>0?Z("mcp.serverCount",{enabled:eg.enabled,total:eg.total}):"",Z("config.switchAutoSave")].filter(Boolean).join(" \xb7 ")}),children:[!m&&(0,d.jsx)(mw,{onClick:V,children:Z("i18n.close")}),(0,d.jsx)(mw,{variant:"secondary",onClick:T,disabled:ey,children:Z("i18n.refresh")})]})]})}function yM(e){let{added:t,cwd:n,server:r,testing:i,signIn:s,signingOut:l,signInBlock:a,onSignIn:o}=e,{t:c}=(0,ns.s)(),u=fY(t.name),p="project"===t.scope&&n?fY(tC(t.path,n)):yw(t.path),h=r.status,m=!i&&h?.origin==="test"&&"needs-auth"===h.state&&r.usesOAuth,f=s?.starting===!0||yl(s);return(0,d.jsxs)(mf,{action:!m||f||l||a?void 0:(0,d.jsx)(mw,{size:"small",variant:"primary",onClick:()=>o(r),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:yw(t.trustedFolder)}),i&&(0,d.jsxs)(d.Fragment,{children:[" ",c("mcp.add.testing")]}),m&&(0,d.jsxs)(d.Fragment,{children:[" ",c("mcp.add.needsSignIn")]})]})}function y$(e){let{codemode:t,active:n,rowRef:r,onSelect:i}=e,{t:s}=(0,ns.s)(),l=t.builtinDisabled||"unavailable"===t.sandbox.state?"unavailable":t.preference??"unknown",a=s(gN[l]);return(0,d.jsxs)(h7,{ref:n?r:void 0,active:n,"aria-label":s("mcp.codemode.rowLabel",{state:a}),onClick:()=>i(f9),children:[(0,d.jsx)(mS,{...gc(gE(l))}),(0,d.jsx)(me,{className:"is-grow",children:s("mcp.codemode.title")}),(0,d.jsx)("span",{className:`mcp-sidebar-badge is-${gE(l)}`,children:a})]})}function yI(e){var t;let n,r,{group:i,context:s,selected:l,selectedRowRef:a,block:o,blockNoticeId:c,busy:u,controlsBusy:p,status:h,onSelect:m,onGroupSwitch:f}=e,{t:g}=(0,ns.s)(),{enabled:x,total:v}=gb(i.servers),b=(t=i.servers).some(e=>e.enabled&&gK(e))&&t.every(e=>e.enabled||!gq(e)),y=function(e){if(!(e.servers.length>0))return e.file?e.file.problems.some(gx)?"mcp.group.fileProblem":"mcp.group.empty":"mcp.group.notListed"}(i),w=h?(n=h.keptOff>0?g("mcp.groupKeptOff",{count:h.keptOff}):void 0,r=h.error?`${g("mcp.actionFailed")} ${yS(h.error,g)}`:h.failures.length>0?[g("mcp.bulkFailed",{count:h.failures.length,total:h.total}),...h.failures.map(e=>{let{name:t,failure:n}=e;return`${fY(t)}: ${yS(n,g)}`})].join("\n"):void 0,{...n?{note:n}:{},...r?{error:r}:{}}):void 0;return(0,d.jsxs)("div",{className:"config-sidebar-group",children:[(0,d.jsx)(h6,{aside:v>0?(0,d.jsx)(h5,{enabled:x,total:v,checked:b,disabled:p||void 0!==o,loading:u===`group:${i.scope}`,describedBy:o?c:void 0,label:g(b?"mcp.groupSwitchOn":"mcp.groupSwitchOff",{group:yy(i.scope,g)}),onChange:e=>f(i.scope,i.servers,e)}):void 0,children:yy(i.scope,g)}),w&&(0,d.jsx)(h9,{note:w.note,error:w.error}),y&&(0,d.jsx)("div",{className:"mcp-sidebar-group-empty",children:g(y)}),i.servers.map(e=>{let t=f7(e),n=gn(e,s),r=go(n),i=ga[n],o=fY(e.name);return(0,d.jsxs)(h7,{ref:l===t?a:void 0,active:l===t,"aria-label":g("mcp.rowLabel",{name:o,state:g(gs(n,e.status))}),onClick:()=>m(t),children:[(0,d.jsx)(mS,{...gc(r)}),(0,d.jsx)(me,{className:`is-grow${"on"===r?"":" is-muted"}`,children:o}),i&&(0,d.jsx)("span",{className:`mcp-sidebar-badge is-${r}`,children:g(i)})]},t)})]})}function yT(e){let{fields:t}=e,{t:n}=(0,ns.s)();return(0,d.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>{let t=f2(e);return(0,d.jsx)("code",{className:"mcp-config-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function yR(e){let{names:t}=e;return(0,d.jsx)("span",{className:"mcp-config-chips",children:t.map(e=>(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(e)},e))})}function yA(e){let{server:t,editCwd:n,onEdited:r,context:i,codemode:s,toolSearchDisabled:l,autoEnable:a,block:o,blockNoticeId:c,uncheckedSaid:p,inProject:h,inProjectBlock:m,savedWhileOff:f,busy:g,controlsBusy:x,actionError:v,test:b,testBlock:y,signIn:w,signInBlock:j,signOutBlock:k,onSwitch:S,onSwitchInProject:C,onShowServer:N,onExposureChange:E,onRemove:M,onTest:$,onSignIn:I,onSignOut:T,onSignInPaste:R,onSignInCancel:A}=e,{t:L}=(0,ns.s)(),[P,z]=(0,u.useState)(!1),[O,W]=(0,u.useState)(!1),F=(0,u.useId)(),D=(0,u.useId)(),_=gn(t,i),B=f0(t),H=t.status,U=H?.origin==="test"&&"connected"===H.state&&H.toolCount>0?H:void 0,K=void 0===t.invalidError,q="http"===t.transport||void 0===t.transport&&void 0!==t.url,V=!q&&("stdio"===t.transport||void 0!==t.command),Z=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"===gj(r)?void 0:{key:"mcp.exposure.autoEnableOff",params:{path:n.path}}}if("deferred"!==e||!t.toolSearchDisabled)return;let i=t.toolSearchDisabled.settingsPath;return i?{key:"mcp.exposure.toolSearchDisabled",params:{path:i}}:{key:"mcp.exposure.toolSearchDisabledUnknown"}}(t.exposure,{codemode:s,toolSearchDisabled:l},a):void 0,J=(0,u.useId)(),Y=(0,u.useId)(),G=f7(t),X=fY(t.name),Q=!t.enabled&&void 0!==t.webPasswordField,ee=!0===t.notAnObject,et=o?c?void 0:L(`mcp.reason.${o}`):ee?L("mcp.reason.entry-not-object"):Q?L("mcp.reason.web-password"):f?L("mcp.write.savedWhileOff"):void 0,en=et?F:o?c:void 0,er=e=>void 0!==e&&e===o&&void 0!==c;return P?(0,d.jsx)(f5,{server:t,cwd:n,onCancel:()=>z(!1),onSaved:()=>{z(!1),W(!0),r()}}):(0,d.jsxs)(mt,{children:[(0,d.jsxs)("div",{className:"config-detail-heading",children:[(0,d.jsxs)(mn,{children:[(0,d.jsxs)(mr,{children:[(0,d.jsx)(md,{scope:t.scope,children:yy(t.scope,L)}),(0,d.jsx)(ms,{children:X})]}),(0,d.jsxs)(mi,{children:[!t.override&&!t.notAnObject&&(0,d.jsx)(mw,{size:"small",disabled:x||void 0!==o,"aria-describedby":o?F:void 0,onClick:()=>z(!0),children:L("mcp.edit.action")}),(0,d.jsx)(yD,{server:t,test:b,testBlock:y,describedBy:er(y)?c:D,onTest:$}),(0,d.jsx)(mw,{variant:"danger",size:"small",disabled:x||void 0!==o,"aria-describedby":o?en:void 0,onClick:()=>M(t),children:g===`remove:${G}`?L("i18n.removing"):L("i18n.remove")}),(0,d.jsx)(mj,{checked:t.enabled,disabled:x||void 0!==o||ee||Q,loading:g===`switch:${G}`,describedBy:en,label:L(t.enabled?"mcp.server.switchOff":"mcp.server.switchOn",{name:X}),onChange:e=>S(t,e)})]})]}),et&&(0,d.jsx)("div",{id:F,className:"config-detail-heading-note",children:et})]}),O&&(0,d.jsx)("p",{role:"status",className:"mcp-config-line",children:L("mcp.edit.saved")}),v&&(0,d.jsxs)("p",{role:"alert",className:"mcp-config-line is-error",children:[L("mcp.actionFailed")," ",yS(v,L)]}),(0,d.jsxs)(mo,{children:[(0,d.jsx)(y_,{server:t,state:_,test:b,testBlock:y,testBlockSaid:er(y),testBlockId:D}),void 0!==t.description&&(0,d.jsx)(mc,{label:L("mcp.detail.description"),tone:"plain",children:fY(t.description)}),void 0!==B?(0,d.jsx)(mc,{label:q?L("mcp.detail.url"):L("mcp.detail.command"),tone:"plain",mono:!0,className:"mcp-config-code",children:B}):t.transport&&(0,d.jsx)(mc,{label:L("mcp.detail.transport"),children:L(`mcp.transport.${t.transport}`)}),V&&void 0!==t.cwd&&(0,d.jsx)(mc,{label:L("mcp.detail.cwd"),mono:!0,className:"mcp-config-code",children:fY(t.cwd)}),V&&t.envNames.length>0&&(0,d.jsx)(mc,{label:L("mcp.detail.env"),children:(0,d.jsx)(yR,{names:t.envNames})}),q&&t.headerNames.length>0&&(0,d.jsx)(mc,{label:L("mcp.detail.headers"),children:(0,d.jsx)(yR,{names:t.headerNames})}),K&&t.commandFields.length>0&&(0,d.jsx)(mc,{label:L("mcp.detail.shellCommands"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:L("mcp.server.commandFields")}),(0,d.jsx)(yT,{fields:t.commandFields})]})}),K&&t.variableReferences.length>0&&(0,d.jsx)(mc,{label:L("mcp.detail.variables"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:L(f4(t))}),(0,d.jsx)("span",{className:"mcp-config-chips",children:f8(t.variableReferences).map(e=>{let{variable:t,field:n}=e,r=f2(n);return(0,d.jsx)("code",{className:"mcp-config-chip",children:L("mcp.server.variableIn",{variable:t,field:L(r.key,r.params)})},`${t}\0${n.kind}\0${n.name??""}`)})})]})}),q&&K&&(0,d.jsx)(yx,{server:t,run:w,block:j,signOutBlock:k,blockSaidBy:er(j)?c:void 0,signOutBlockSaidBy:er(k)?c:void 0,controlsBusy:x,signingOut:g===`sign-out:${G}`,onSignIn:I,onSignOut:T,onPaste:R,onCancel:A}),(t.exposure||U)&&(0,d.jsx)(mc,{label:L("mcp.detail.exposure"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-lines",children:[t.exposure&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{className:"mcp-exposure-choice",children:[(0,d.jsx)("select",{className:"mcp-add-input mcp-exposure-select","aria-label":L("mcp.exposure.label",{name:X}),"aria-describedby":[J,o?en:null].filter(Boolean).join(" "),value:t.exposure,disabled:x||void 0!==o,onChange:e=>{let n=e.target.value;n!==t.exposure&&E(t,n)},children:gf.map(e=>(0,d.jsx)("option",{value:e,children:"codemode"===e?L("mcp.exposure.optionDefault",{label:L(gg[e])}):L(gg[e])},e))}),g===`exposure:${G}`&&(0,d.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:L("i18n.saving")})]}),(0,d.jsx)("span",{id:J,className:"mcp-config-line",children:L(gm[t.exposure])}),void 0!==t.toolExposureCount&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:L("mcp.exposure.toolOverrides",{count:t.toolExposureCount})}),Z&&(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:yj(Z,L)})]}),U&&(0,d.jsx)(yF,{status:U,serverExposure:t.exposure})]})}),h&&(0,d.jsx)(mc,{label:L("mcp.detail.inProject"),tone:"plain",children:(0,d.jsx)("span",{className:"mcp-config-lines",children:"override"===h.kind?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"mcp-config-line",children:h.applies?L("mcp.inProject.overridden",{keys:h.keys.join(", ")}):L("mcp.inProject.refused")}),(0,d.jsx)("span",{children:(0,d.jsx)(mw,{size:"small",onClick:()=>N(h.key),children:L("mcp.inProject.show")})})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{children:(0,d.jsx)(mw,{size:"small",disabled:x||void 0!==m||Q,"aria-describedby":[Y,m||Q?en:null].filter(Boolean).join(" "),onClick:()=>C(t,!t.enabled),children:g===`in-project:${G}`?L("i18n.saving"):L(t.enabled?"mcp.inProject.turnOff":"mcp.inProject.turnOn")})}),(0,d.jsx)("span",{id:Y,className:"mcp-config-line is-dim",children:L("mcp.inProject.saved")})]})})}),(0,d.jsx)(mc,{label:L("mcp.detail.file"),tone:"dim",mono:!0,className:"mcp-config-code",children:yw(t.sourcePath)})]}),(0,d.jsxs)("div",{className:"mcp-config-lines",children:[f1(t)&&(0,d.jsx)("p",{className:"mcp-config-line is-warning",children:L("mcp.server.hiddenCharacters")}),!t.validated&&!p&&(0,d.jsx)("p",{className:"mcp-config-line is-warning",children:L("mcp.server.unchecked")}),t.replacesGlobal&&(0,d.jsx)("p",{className:"mcp-config-line is-warning",children:L("mcp.server.replacesGlobal")}),t.override&&(0,d.jsx)("p",{className:"mcp-config-line",children:yj(f3(t.override.keys),L)}),t.shadowedByProject&&"replaced"!==_&&(0,d.jsx)("p",{className:"mcp-config-line",children:L("mcp.server.shadowedByProject")}),t.overriddenByProject&&"overridden"!==_&&(0,d.jsx)("p",{className:"mcp-config-line",children:L("mcp.server.overriddenByProject")}),t.masked&&(0,d.jsx)("p",{className:"mcp-config-line is-dim",children:L("mcp.server.masked")})]})]})}function yL(e){let{error:t,stderr:n}=e,{t:r}=(0,ns.s)();return(0,d.jsxs)(d.Fragment,{children:[t&&(0,d.jsxs)("span",{className:"mcp-config-line is-error",children:[r("mcp.test.error")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t)})]}),n&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:r("mcp.test.stderr")}),(0,d.jsx)("pre",{className:"mcp-test-output",children:n.split(/\r?\n/).map(fY).join("\n")})]})]})}function yP(e){let{status:t,showState:n,entryCwd:r}=e;return"session"===t.origin?(0,d.jsx)(yW,{status:t,showState:n}):(0,d.jsx)(yO,{status:t,showState:n,entryCwd:r})}function yz(e){let{view:t}=e,{t:n}=(0,ns.s)();return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:`mcp-config-state is-${t.tone}`,children:n(t.key)})," "]})}function yO(e){let{status:t,showState:n,entryCwd:r}=e,{t:i,locale:s}=(0,ns.s)(),l=gd(t.testedAt,s),a=t.serverInfo;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,d.jsx)(yz,{view:t.timedOut?{key:gX.timedOut,tone:"error"}:{key:gX[t.state],tone:go(t.state)}}),i((t.afterSignIn?g0:gQ)[t.timedOut?"timedOut":t.state],{count:t.toolCount,seconds:g1(t.durationMs),time:l})]}),(0,d.jsx)(yL,{error:t.error,stderr:t.stderr}),a&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.serverInfo",{name:fY(a.title??a.name),version:fY(a.version)})}),t.resources&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.resources")}),void 0!==t.cwd&&t.cwd!==r&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.ranIn",{path:yw(t.cwd)})}),void 0!==t.queuedMs&&t.queuedMs>=500&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:i("mcp.test.queued",{seconds:g1(t.queuedMs)})})]})}function yW(e){let{status:t,showState:n}=e,{t:r,locale:i}=(0,ns.s)(),s=gd(t.updatedAt,i),l=void 0===t.closedAt?void 0:gd(t.closedAt,i);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{className:"mcp-config-line",children:[n&&(0,d.jsx)(yz,{view:void 0!==t.closedAt?{key:"mcp.session.state.closed",tone:"off"}:{key:gu[t.state],tone:gh[t.state]}}),r(void 0!==t.closedAt?"mcp.session.summary.closed":gp[t.state],{path:yw(t.cwd),time:s,...void 0===l?{}:{closedTime:l}})]}),void 0!==t.conflict&&(0,d.jsxs)("span",{className:"mcp-config-line is-error",children:[r("mcp.session.conflictOwner")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:yw(t.conflict)})]}),(0,d.jsx)(yL,{error:t.error,stderr:t.stderr})]})}function yF(e){let{status:t,serverExposure:n}=e,{t:r}=(0,ns.s)(),i=t.toolCount-t.tools.length;return(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("ul",{className:"mcp-test-tools",children:t.tools.map((e,t)=>(0,d.jsxs)("li",{className:"mcp-test-tool",children:[(0,d.jsxs)("span",{className:"mcp-config-chips",children:[(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(e.name)}),e.readOnly&&(0,d.jsx)("span",{className:"mcp-test-tool-tag",children:r("mcp.test.readOnly")}),e.exposure!==(n??"codemode")&&(0,d.jsx)("span",{className:"mcp-test-tool-tag",children:r(gg[e.exposure])})]}),e.description&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:fY(e.description)})]},`${t}\0${e.name}`))}),i>0&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:r("mcp.test.moreTools",{count:i})})]})}function yD(e){let{server:t,test:n,testBlock:r,describedBy:i,onTest:s}=e,{t:l}=(0,ns.s)(),a=(0,u.useRef)(null),o=n?.running===!0,c=(0,u.useRef)(o);return(0,u.useEffect)(()=>{let e=c.current;c.current=o,e&&!o&&t_(document,a.current)},[o]),(0,d.jsx)(mw,{ref:a,size:"small",disabled:o||void 0!==r,"aria-busy":o||void 0,"aria-describedby":r?i:void 0,onClick:()=>s(t),children:l(o?"mcp.test.testing":"mcp.test.button")})}function y_(e){let{server:t,state:n,test:r,testBlock:i,testBlockSaid:s,testBlockId:l}=e,{t:a}=(0,ns.s)(),o=t.status,c=gl[n],u="invalid"===i&&"invalid"===n?"state":"web-password"===i&&void 0!==t.webPasswordField?"password":void 0;return(0,d.jsx)(mc,{label:a("i18n.status"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-lines",children:[(0,d.jsx)("span",{className:`mcp-config-state is-${go(n)}`,children:a(gs(n,o))}),"invalid"===n&&(0,d.jsxs)("span",{id:"state"===u?l:void 0,className:"mcp-config-line is-warning",children:[a("mcp.server.invalid")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.invalidError??"")})]}),t.webPasswordField&&(0,d.jsxs)("span",{id:"password"===u?l:void 0,className:"mcp-config-line is-warning",children:[a("mcp.server.webPassword")," ",(0,d.jsx)(yT,{fields:[t.webPasswordField]})]}),o?(0,d.jsx)(yP,{status:o,showState:gt(o)!==n,entryCwd:t.cwd}):!i&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.test.never")}),c&&(0,d.jsx)("span",{className:"mcp-config-line",children:a(c)}),r?.queueTimedOut&&(0,d.jsx)("span",{role:"alert",className:"mcp-config-line is-error",children:a("mcp.test.queueTimedOut")}),r?.error&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[a("mcp.test.requestFailed")," ",function(e,t){if(e.timedOut)return t("mcp.test.requestTimedOut");let n=e.reason?gG[e.reason]:void 0;return n?t(n):yk(e,t)}(r.error,a)]}),i&&!u&&!s&&(0,d.jsx)("span",{id:l,className:"mcp-config-line is-dim",children:a(gJ[i])}),!i&&t.commandFields.length>0&&(0,d.jsx)("span",{className:"mcp-config-line is-dim",children:a("mcp.test.serial")})]})})}function yB(e){let{codemode:t,autoEnable:n,save:r,serverBusy:i,onChange:s,onModeChange:l,onInlineBudgetSave:a}=e,{t:o}=(0,ns.s)(),c=t.sandbox,u=t.preference,p=r.saving||i,h=void 0===r.target||"preference"===r.target?r:{saving:!1,error:null},m=function(e,t){if("automatic"===gj(e)&&!t.value)return{key:"mcp.codemode.autoEnableOff",params:{path:t.path}}}(t,n),f="unavailable"===t.sandbox.state?{key:"mcp.codemode.alwaysUnavailable.sandbox"}:t.globalBuiltinSettingsPath?{key:"mcp.codemode.alwaysUnavailable.builtin",params:{path:t.globalBuiltinSettingsPath}}:void 0,g=function(e){if(!e.builtinDisabled)return;let t=e.builtinSettingsPath;return t?e.globalBuiltinSettingsPath?{key:"mcp.codemode.builtinDisabled",params:{path:t}}:{key:"mcp.codemode.builtinDisabledProject",params:{path:t}}:{key:"mcp.codemode.builtinDisabledUnknown"}}(t),x=function(e){let t=e.projectOverride;if(t)return{key:gk[t.preference],params:{path:t.settingsPath}}}(t);return(0,d.jsxs)(mt,{children:[(0,d.jsx)(mn,{children:(0,d.jsx)(mr,{children:(0,d.jsx)(ms,{children:o("mcp.codemode.title")})})}),(0,d.jsx)("p",{className:"mcp-config-line",children:o("mcp.codemode.intro")}),(0,d.jsxs)(mo,{children:[(0,d.jsx)(mc,{label:o("mcp.codemode.mode"),tone:"plain",children:(0,d.jsxs)("div",{className:"mcp-config-lines",children:[u?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(mu,{value:u,label:o("mcp.codemode.title"),options:[{value:"automatic",label:o(gN.automatic),disabled:p},{value:"always",label:o(gN.always),disabled:p||void 0!==f}],disabledReason:f?yj(f,o):null,onChange:e=>{e!==u&&s(e)},children:h.saving&&(0,d.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:o("i18n.saving")})}),(0,d.jsx)("span",{className:"mcp-config-line",children:o("always"===u?"mcp.codemode.alwaysDescription":"mcp.codemode.automaticDescription")})]}):(0,d.jsxs)("span",{className:"mcp-config-line is-warning",children:[o("mcp.codemode.preferenceError")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.preferenceError??"")})]}),h.error&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[o("mcp.codemode.saveFailed")," ",(0,d.jsx)(yH,{error:h.error})]}),x&&(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:yj(x,o)}),m&&(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:yj(m,o)})]})}),t.mode?(0,d.jsx)(yU,{mode:t.mode,codemode:t,save:r,waiting:p,onChange:l}):void 0!==t.modeError&&(0,d.jsx)(mc,{label:o("mcp.codemode.toolMode"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-line is-warning",children:[o("mcp.codemode.preferenceError")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.modeError)})]})}),t.inlineBudget?(0,d.jsx)(yK,{budget:t.inlineBudget,save:r,waiting:p,onSave:a}):void 0!==t.inlineBudgetError&&(0,d.jsx)(mc,{label:o("mcp.codemode.inlineBudget"),tone:"plain",children:(0,d.jsxs)("span",{className:"mcp-config-line is-warning",children:[o("mcp.codemode.preferenceError")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.inlineBudgetError)})]})}),(0,d.jsx)(mc,{label:o("mcp.codemode.sandbox"),tone:"plain",children:"unavailable"===c.state?(0,d.jsxs)("span",{className:"mcp-config-line is-warning",children:[o("mcp.codemode.sandbox.unavailable")," ",(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(c.error)})]}):(0,d.jsx)("span",{className:"mcp-config-line",children:o("available"===c.state?"mcp.codemode.sandbox.available":"mcp.codemode.sandbox.not-checked")})}),g&&(0,d.jsx)(mc,{label:o("mcp.codemode.builtin"),tone:"error",children:yj(g,o)})]})]})}function yH(e){let{error:t}=e,{t:n}=(0,ns.s)();return t.timedOut?(0,d.jsx)(d.Fragment,{children:n("mcp.codemode.saveTimedOut")}):t.reason&&"internal"!==t.reason?(0,d.jsx)(d.Fragment,{children:n(`mcp.reason.${t.reason}`)}):(0,d.jsx)("code",{className:"mcp-config-chip",children:fY(t.error)})}function yU(e){let{mode:t,codemode:n,save:r,waiting:i,onChange:s}=e,{t:l}=(0,ns.s)(),a="mode"===r.target,o=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:gC[r.value],params:{path:r.settingsPath}}),"only"===(r??t).value&&"automatic"===gj(e)&&n.push({key:"mcp.codemode.toolMode.automaticNote"}),n}(n);return(0,d.jsx)(mc,{label:l("mcp.codemode.toolMode"),tone:"plain",children:(0,d.jsxs)("div",{className:"mcp-config-lines",children:[(0,d.jsx)(mu,{value:t.value,label:l("mcp.codemode.toolMode"),options:[{value:"on",label:l("mcp.codemode.toolMode.on"),disabled:i},{value:"only",label:l("mcp.codemode.toolMode.only"),disabled:i}],onChange:e=>{(e!==t.value||void 0!==t.invalid)&&s(e)},children:a&&r.saving&&(0,d.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:l("i18n.saving")})}),(0,d.jsx)("span",{className:"mcp-config-line",children:l(gS[t.value])}),o.map(e=>(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:yj(e,l)},e.key)),a&&r.error&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[l("mcp.codemode.toolMode.saveFailed")," ",(0,d.jsx)(yH,{error:r.error})]})]})})}function yK(e){let t,n,{budget:r,save:i,waiting:s,onSave:l}=e,{t:a}=(0,ns.s)(),o=(0,u.useRef)(null),c=(0,u.useId)(),p=void 0===r.value?"":String(r.value),[h,m]=(0,u.useState)(p);(0,u.useEffect)(()=>{m(p)},[p]);let f=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,r.max),g=!!f.ok&&(null===f.value?void 0!==r.value||void 0!==r.invalid:f.value!==r.value),x="inlineBudget"===i.target,v=x&&i.saving,b=(0,u.useRef)(v);(0,u.useEffect)(()=>{let e=b.current;b.current=v,e&&!v&&t_(document,o.current)},[v]);let y=(t=[],void 0!==r.invalid&&t.push({key:"mcp.codemode.inlineBudget.invalid",params:{path:r.settingsPath,value:r.invalid,default:String(r.default)}}),(n=r.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(r.default)}}),t);return(0,d.jsx)(mc,{label:a("mcp.codemode.inlineBudget"),tone:"plain",children:(0,d.jsxs)("div",{className:"mcp-config-lines",children:[(0,d.jsxs)("form",{className:"mcp-codemode-budget",onSubmit:e=>{e.preventDefault(),f.ok&&g&&!s&&l(f.value)},children:[(0,d.jsx)("input",{ref:o,className:"mcp-add-input mcp-codemode-budget-input",inputMode:"numeric","aria-label":a("mcp.codemode.inlineBudget"),"aria-describedby":c,"aria-invalid":!f.ok||void 0,value:h,placeholder:String(r.default),readOnly:s,autoComplete:"off",spellCheck:!1,onChange:e=>m(e.target.value)}),(0,d.jsx)("span",{className:"mcp-config-line",children:a("mcp.codemode.inlineBudget.unit")}),(0,d.jsx)(mw,{type:"submit",size:"small",disabled:!g||s,children:a("mcp.codemode.inlineBudget.save")}),v&&(0,d.jsx)("span",{role:"status",className:"mcp-config-line is-dim",children:a("i18n.saving")})]}),!f.ok&&(0,d.jsx)("span",{className:"mcp-config-line is-error",children:a("mcp.codemode.inlineBudget.invalidDraft",{max:String(r.max)})}),(0,d.jsx)("span",{id:c,className:"mcp-config-line",children:a("mcp.codemode.inlineBudget.description",{default:String(r.default)})}),y.map(e=>(0,d.jsx)("span",{className:"mcp-config-line is-warning",children:yj(e,a)},e.key)),x&&i.error&&(0,d.jsxs)("span",{role:"alert",className:"mcp-config-line is-error",children:[a("mcp.codemode.inlineBudget.saveFailed")," ",(0,d.jsx)(yH,{error:i.error})]})]})})}let yq=[{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 yV(){let{t:e}=(0,ns.s)(),t=cM();return(0,d.jsx)("div",{className:"settings-font-rows",children:yq.map(n=>{let{kind:r,label:i,placeholder:s,reset:l,weightLabel:a}=n,o=t[`${r}Weight`],c=co.findIndex(e=>e.value===o);return(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-range-option settings-font-row",children:[(0,d.jsxs)("div",{className:"settings-chat-range-header settings-font-header",children:[(0,d.jsx)("label",{htmlFor:`settings-font-${r}`,children:e(i)}),(0,d.jsx)("input",{id:`settings-font-${r}`,className:`settings-font-input${"mono"===r?" is-mono":""}`,type:"text",value:t[r],placeholder:e(s),maxLength:500,"aria-describedby":"settings-typography-description",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:e=>t.setFontPreference(r,e.target.value)}),(0,d.jsx)("output",{htmlFor:`settings-font-${r}-weight`,title:`${e(a)}: ${o}`,children:e(co[c].label)}),(0,d.jsx)(mw,{variant:"ghost",size:"small",className:"settings-chat-reset",title:e(l),"aria-label":e(l),disabled:!t[r]&&400===o,onClick:()=>t.resetFontPreference(r),children:(0,d.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,d.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,d.jsx)("input",{id:`settings-font-${r}-weight`,type:"range",min:co[0].value,max:co[co.length-1].value,step:100,value:o,"aria-label":e(a),"aria-valuetext":`${o} ${e(co[c].label)}`,onChange:e=>t.setFontWeight(r,Number(e.target.value))})]},r)})})}function yZ(e){let{section:t,size:n=16,strokeWidth:r=1.8}=e,i={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===t?(0,d.jsxs)("svg",{...i,children:[(0,d.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,d.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,d.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===t?(0,d.jsxs)("svg",{...i,children:[(0,d.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,d.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,d.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"skills"===t?(0,d.jsxs)("svg",{...i,children:[(0,d.jsx)("path",{d:"m12 2-10 5 10 5 10-5-10-5Z"}),(0,d.jsx)("path",{d:"m2 12 10 5 10-5M2 17l10 5 10-5"})]}):"agents"===t?(0,d.jsx)(nW,{size:n,strokeWidth:r,className:"settings-section-icon is-agent"}):"mcp"===t?(0,d.jsxs)("svg",{...i,children:[(0,d.jsx)("rect",{x:"3",y:"3",width:"18",height:"7",rx:"2"}),(0,d.jsx)("rect",{x:"3",y:"14",width:"18",height:"7",rx:"2"}),(0,d.jsx)("path",{d:"M7 6.5h.01M7 17.5h.01M11 6.5h6M11 17.5h6"})]}):(0,d.jsx)("svg",{...i,children:(0,d.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 yJ(){let{t:e}=(0,ns.s)(),[t,n]=(0,u.useState)(()=>{let e="u"<typeof document?void 0:document.documentElement.dataset.sunbeamAvatar;return r5.some(t=>t.id===e)?e:r5[0].id});return(0,d.jsxs)("fieldset",{className:"settings-avatar-picker",children:[(0,d.jsx)("legend",{children:e("settings.chatAvatar")}),(0,d.jsx)("div",{className:"settings-avatar-options",children:r5.map(r=>{let{id:i,label:s}=r;return(0,d.jsxs)("label",{className:"settings-avatar-option",title:e(s),children:[(0,d.jsx)("input",{type:"radio",name:"sunbeam-avatar",value:i,checked:t===i,"aria-label":e(s),onChange:()=>(e=>{document.documentElement.dataset.sunbeamAvatar=e,n(e);try{localStorage.setItem("pi-sunbeam-avatar",e)}catch{}})(i),className:"sr-only"}),(0,d.jsx)("span",{className:"settings-avatar-preview","data-sunbeam-avatar":i,"aria-hidden":"true"})]},i)})})]})}function yY(e){let{sessionId:t,onSessionReloaded:n,quoteSelectionEnabled:r,onQuoteSelectionChange:i}=e,{locale:s,setLocale:l,supportedLocales:a,t:o}=(0,ns.s)(),{preference:c,setThemePreference:p}=lH(),{width:h,setWidth:m,fontSize:f,setFontSize:g}=ca(),x=o2.use(),[v,b]=(0,u.useState)(null),[y,w]=(0,u.useState)(!1),[j,k]=(0,u.useState)(null),[S,C]=(0,u.useState)(!1),[N,E]=(0,u.useState)(null),[$,I]=(0,u.useState)(!1),[T,A]=(0,u.useState)(null),[P,z]=(0,u.useState)(!1),[O,W]=(0,u.useState)(null),[F,D]=(0,u.useState)(!1),[_,B]=(0,u.useState)(null),[H,U]=(0,u.useState)(!1),[K,q]=(0,u.useState)(!1),[V,Z]=(0,u.useState)("");(0,u.useEffect)(()=>{I(aL()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>U(e?.enabled===!0)).catch(()=>{})},[]);let J=async()=>{q(!0),Z("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);M.clear();let t=R();if(t)try{L(t).forEach(e=>t.removeItem(e))}catch{}window.location.replace("/login")}catch{Z(o("auth.logoutFailed"))}finally{q(!1)}};(0,u.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await nE(t);e||b(n)}).catch(t=>{e||k(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]),(0,u.useEffect)(()=>{let e=!1;return fetch("/api/cache-miss-notices").then(async t=>{let n=await nE(t);e||A(!0===n.enabled)}).catch(t=>{e||W(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let Y=async e=>{z(!0),W(null);try{let r=await fetch("/api/cache-miss-notices",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await nE(r);A(!0===i.enabled),t&&n()}catch(e){W(e instanceof Error?e.message:String(e))}finally{z(!1)}},G=async e=>{w(!0),k(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),i=await nE(r);b(i),t&&(await dA(t,{type:"reload"}),n())}catch(e){k(e instanceof Error?e.message:String(e))}finally{w(!1)}},X=async(e,t)=>{if(v){C(!0),E(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 nE(r);b(i)}catch(e){E(e instanceof Error?e.message:String(e))}finally{C(!1)}}},Q=async()=>{if(!F){D(!0),B(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 fo(s))throw Error("unsupported or not permitted");B({kind:"ok",message:o("settings.pushRegistered")})}catch(e){B({kind:"error",message:`${o("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{D(!1)}}};return(0,d.jsxs)("div",{className:"settings-general",children:[(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("settings.appearance")}),(0,d.jsx)("div",{role:"radiogroup","aria-label":o("settings.appearance"),className:"settings-theme-options",children:r6.map(e=>{let t=c===e.id;return(0,d.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,d.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>p(e.id),className:"sr-only"}),"auto"===e.id?(0,d.jsxs)("span",{className:"settings-theme-swatch settings-theme-system","aria-hidden":"true",children:[(0,d.jsx)("span",{"data-theme":"light",className:"settings-theme-chip"}),(0,d.jsx)("span",{"data-theme":"dark",className:"settings-theme-chip"}),(0,d.jsx)("span",{className:"settings-theme-system-name",children:o(e.label)})]}):(0,d.jsx)("span",{className:"settings-theme-swatch","aria-hidden":"true",children:(0,d.jsx)("span",{"data-theme":e.id,className:"settings-theme-fill",children:(0,d.jsx)("span",{className:"settings-theme-name",children:o(e.label)})})}),(0,d.jsx)("span",{className:"sr-only",children:o(e.label)})]},e.id)})}),"sunbeam"===c&&(0,d.jsx)(yJ,{})]}),(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("settings.chat")}),(0,d.jsxs)("div",{className:"settings-chat-options",children:[(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,d.jsx)("span",{children:o("settings.thinkingExpandedDefault")}),(0,d.jsx)(mj,{checked:$,label:o("settings.thinkingExpandedDefault"),onChange:e=>{!function(e){try{window.localStorage.setItem(aR,String(e))}catch{return}window.dispatchEvent(new Event(aA))}(e),I(e)}})]}),(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,d.jsx)("span",{children:o("settings.quoteSelection")}),(0,d.jsx)(mj,{checked:r,label:o("settings.quoteSelection"),onChange:i})]}),(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",role:"radiogroup","aria-label":o("settings.enterSendMode"),children:[(0,d.jsx)("span",{children:o("settings.enterSendMode")}),(0,d.jsxs)("div",{className:"settings-send-mode-options",children:[(0,d.jsxs)("label",{className:"settings-send-mode-option",children:[(0,d.jsx)("input",{type:"radio",name:"enter-send-mode",value:"enter",checked:"enter"===x,onChange:()=>{o2.set("enter")},className:"sr-only"}),(0,d.jsx)("span",{className:"settings-send-mode-label",children:o("settings.enterSendModeEnter")})]}),(0,d.jsxs)("label",{className:"settings-send-mode-option",children:[(0,d.jsx)("input",{type:"radio",name:"enter-send-mode",value:"ctrlEnter",checked:"ctrlEnter"===x,onChange:()=>{o2.set("ctrlEnter")},className:"sr-only"}),(0,d.jsx)("span",{className:"settings-send-mode-label",children:o("settings.enterSendModeCtrlEnter")})]})]})]}),(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,d.jsx)("span",{children:o("settings.cacheMissNotices")}),(0,d.jsx)(mj,{checked:!0===T,loading:null===T&&!O||P,label:o("settings.cacheMissNotices"),describedBy:"settings-cache-miss-notices-description",onChange:e=>void Y(e)})]})]}),(0,d.jsx)("p",{id:"settings-cache-miss-notices-description",className:"settings-general-description",children:o("settings.cacheMissNoticesDescription")}),O&&(0,d.jsx)("p",{role:"alert",className:"settings-general-error",children:O})]}),(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("settings.typography")}),(0,d.jsx)("p",{id:"settings-typography-description",className:"settings-general-description",children:o("settings.fontDescription")}),(0,d.jsxs)("div",{className:"settings-chat-options",children:[(0,d.jsx)(yV,{}),(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,d.jsxs)("div",{className:"settings-chat-range-header",children:[(0,d.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:o("settings.chatContentFontSize")}),(0,d.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[f,"px"]}),(0,d.jsx)(mw,{variant:"ghost",size:"small",className:"settings-chat-reset",title:o("settings.resetChatContentFontSize"),"aria-label":o("settings.resetChatContentFontSize"),disabled:14===f,onClick:()=>g(14),children:(0,d.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,d.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,d.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:f,onChange:e=>g(Number(e.target.value))})]}),(0,d.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,d.jsxs)("div",{className:"settings-chat-range-header",children:[(0,d.jsx)("label",{htmlFor:"settings-chat-content-width",children:o("settings.chatContentWidth")}),(0,d.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,d.jsx)(mw,{variant:"ghost",size:"small",className:"settings-chat-reset",title:o("settings.resetChatContentWidth"),"aria-label":o("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>m(820),children:(0,d.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,d.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,d.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>m(Number(e.target.value))})]})]})]}),v&&(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("settings.builtinTools")}),(0,d.jsx)("p",{id:"settings-builtin-tools-description",className:"settings-general-description",children:o("settings.builtinToolsDescription")}),(0,d.jsx)("div",{className:"settings-send-mode-options settings-builtin-tools",role:"group","aria-label":o("settings.builtinTools"),"aria-describedby":"settings-builtin-tools-description",children:dH.kt.map(e=>(0,d.jsxs)("label",{className:"settings-send-mode-option",children:[(0,d.jsx)("input",{type:"checkbox",checked:v.builtinTools.includes(e),disabled:S,onChange:t=>void X(e,t.target.checked),className:"sr-only"}),(0,d.jsx)("span",{className:"settings-send-mode-label",children:"bash"===e&&v.powerShellEnabled?"powershell":e})]},e))}),N&&(0,d.jsx)("p",{role:"alert",className:"settings-general-error",children:N}),v.isWindows&&(0,d.jsxs)("div",{className:"settings-general-subsection",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("settings.shellTool")}),(0,d.jsx)("p",{className:"settings-general-description",children:o("settings.shellToolDescription")}),(0,d.jsxs)("div",{className:"settings-shell-option",children:[(0,d.jsx)("span",{children:o("settings.usePowerShell")}),(0,d.jsx)(mj,{checked:v.powerShellEnabled,loading:y,label:o("settings.usePowerShell"),onChange:e=>void G(e)})]}),j&&(0,d.jsx)("p",{role:"alert",className:"settings-general-error",children:j})]})]}),(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("common.language")}),(0,d.jsx)("div",{role:"radiogroup","aria-label":o("common.language"),className:"settings-language-options",children:a.map(e=>{let t=s===e.id;return(0,d.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>l(e.id),className:"settings-language-option",children:[(0,d.jsx)("span",{className:"settings-language-radio",children:t&&(0,d.jsx)("span",{className:"settings-language-radio-dot"})}),(0,d.jsx)("span",{className:"settings-language-label",children:e.label}),(0,d.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsx)("h3",{className:"settings-general-heading",children:o("settings.pushPermission")}),(0,d.jsx)("p",{className:"settings-general-description",children:o("settings.pushPermissionDescription")}),(0,d.jsx)("div",{className:"settings-push-action",children:(0,d.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:F,onClick:()=>void Q(),children:F?o("settings.pushRegisterLoading"):o("settings.pushRegister")})}),_&&(0,d.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===_.kind?{color:"var(--accent)"}:void 0,children:_.message})]}),H&&(0,d.jsxs)("section",{className:"settings-general-section",children:[(0,d.jsxs)(mw,{variant:"secondary",disabled:K,onClick:()=>void J(),children:[(0,d.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,d.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),K?o("auth.loggingOut"):o("auth.logOut")]}),V&&(0,d.jsx)("p",{role:"alert",className:"settings-general-error",children:V})]})]})}let yG={home:"home",section:"home",detail:"section"},yX={home:0,section:1,detail:2},yQ="cubic-bezier(0.2, 0.8, 0.2, 1)";function y0(e){let t,{embedded:n=!1,cwd:r,sessionId:i,initialSection:s,openAtHome:l=!1,onClose:a,onSessionReloaded:o,quoteSelectionEnabled:c,onQuoteSelectionChange:p,projectTrust:h,onOpenTrustDialog:f,onProjectTrustChanged:g}=e,{t:x}=(0,ns.s)(),[v,b]=(0,u.useState)(s),[y,w]=(0,u.useState)(()=>new Set([v])),j=[{id:"general",label:x("settings.general")},{id:"models",label:x("common.models")},{id:"skills",label:x("common.skills")},{id:"agents",label:x("common.agents")},{id:"plugins",label:x("common.plugins")},{id:"mcp",label:x("settings.mcp")}].map(e=>{var t;return{...e,requiresProject:(t=e.id,hb.has(t))}}),k=hb.has(v),S=nf(),C=function(e,t){let[n,r]=(0,u.useState)(t?"home":"section");e||"section"===n||r("section");let i=(0,u.useRef)(n);i.current=n;let s=(0,u.useRef)(0);(0,u.useEffect)(()=>{if(!e)return;let t=()=>{0!==s.current&&(s.current-=1,r(e=>yG[e]))};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[e]);let l=(0,u.useCallback)(t=>{e&&(window.history.pushState(window.history.state,""),s.current+=1,r(t))},[e]);return{level:n,levelRef:i,enter:l,goUp:(0,u.useCallback)(()=>{s.current>0?window.history.back():r(e=>yG[e])},[]),dropHistory:(0,u.useCallback)(()=>{let e=s.current;s.current=0,e>0&&window.history.go(-e)},[])}}(S,l),{dropHistory:N,enter:E,goUp:M,levelRef:$}=C,I=(0,u.useRef)(null),T=(0,u.useRef)(null),R=(0,u.useRef)(null);(0,u.useLayoutEffect)(()=>{let e=T.current,t=R.current;if(!e||!t)return;let n=()=>{let n=e.querySelector('[aria-current="page"]');n&&(t.style.transform=`translateX(${n.offsetLeft+(n.offsetWidth-24)/2}px)`)};n();let r=new ResizeObserver(n);return r.observe(e),e.querySelectorAll("button").forEach(e=>r.observe(e)),()=>r.disconnect()},[v,x]);let A=(0,u.useRef)(!1),L=(0,u.useRef)(null);m(L,v,{desktopOnly:!0});let P=(0,u.useRef)(C.level);(0,u.useLayoutEffect)(()=>{let e=P.current;P.current=C.level,S&&e!==C.level&&function(e,t,n,r){if(!e||"function"!=typeof e.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let i=yX[r]>yX[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:yQ}),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:yQ})})}(L.current,I.current,e,C.level)},[S,C.level]);let z=(0,u.useCallback)(()=>{N(),a()},[a,N]),O=j.find(e=>e.id===v)?.label??x("settings.title"),[W,F]=(0,u.useState)(null),D=(0,u.useMemo)(()=>({detailOpen:"detail"===C.level,openDetail:()=>{"section"===$.current&&(F(null),E("detail"))},closeDetail:()=>{"detail"===$.current&&M()},reportDetailTitle:F}),[E,M,C.level,$]);(0,u.useEffect)(()=>hS(s),[s]),(0,u.useEffect)(()=>tF(document,z),[z]);let _=(0,u.useRef)(null);(0,u.useLayoutEffect)(()=>tD(document,_.current,{restoreTextEntry:!window.matchMedia?.("(pointer: coarse)").matches}),[]),(0,u.useEffect)(()=>{!r&&k&&(b("general"),w(e=>new Set(e).add("general")),hS("general"))},[r,k]);let B=e=>{w(t=>new Set(t).add(e)),b(e),hS(e)},H=(e,t)=>y.has(e)?(0,d.jsx)("div",{hidden:v!==e||"home"===C.level,"data-phone-level":S?C.level:void 0,className:"settings-section-host",children:t},e):null;return(0,d.jsx)("div",{ref:_,role:n?"region":"dialog","aria-modal":!n||void 0,"aria-label":x("settings.title"),tabIndex:-1,onPointerDown:e=>{A.current=e.target===e.currentTarget},onPointerCancel:()=>{A.current=!1},onClick:e=>{let t=A.current;A.current=!1,!n&&t&&e.target===e.currentTarget&&z()},className:`settings-dialog-backdrop${n?" is-embedded":""}`,children:(0,d.jsxs)("div",{className:"settings-dialog-surface",children:[(0,d.jsxs)("div",{ref:I,className:"settings-dialog-header",children:[S&&"home"!==C.level&&(t="detail"===C.level?O:x("settings.title"),(0,d.jsxs)("button",{type:"button",className:"settings-phone-back",onClick:M,"aria-label":x("settings.backTo",{name:t}),children:[(0,d.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,d.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,d.jsx)("span",{children:t})]})),(!n||S)&&(0,d.jsx)("strong",{className:"settings-dialog-title",children:S&&"home"!==C.level?"section"===C.level?O:W:x("settings.title")}),(0,d.jsxs)("nav",{ref:T,"aria-label":x("settings.title"),className:"settings-section-tabs",children:[j.map(e=>{let t=v===e.id,n=e.requiresProject&&!r;return(0,d.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:n,title:n?x("settings.projectRequired"):e.label,"aria-current":t?"page":void 0,onClick:()=>B(e.id),children:[(0,d.jsx)(yZ,{section:e.id}),(0,d.jsx)("span",{children:e.label})]},e.id)}),(0,d.jsx)("span",{ref:R,className:"settings-section-indicator","aria-hidden":"true"})]}),(0,d.jsx)("button",{type:"button",onClick:z,title:x("i18n.close"),"aria-label":x("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,d.jsxs)("main",{ref:L,className:"settings-dialog-main",children:[S&&"home"===C.level&&(0,d.jsx)("nav",{"aria-label":x("settings.title"),className:"settings-phone-home",children:j.map(e=>{let t=e.requiresProject&&!r;return(0,d.jsxs)("button",{type:"button",className:"settings-phone-home-item",disabled:t,"aria-describedby":t?`settings-phone-home-${e.id}-note`:void 0,onClick:()=>{B(e.id),E("section")},children:[(0,d.jsx)(yZ,{section:e.id,size:20}),(0,d.jsxs)("span",{className:"settings-phone-home-label",children:[(0,d.jsx)("span",{children:e.label}),t&&(0,d.jsx)("span",{id:`settings-phone-home-${e.id}-note`,className:"settings-phone-home-note",children:x("settings.projectRequired")})]}),(0,d.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,d.jsx)("path",{d:"m9 18 6-6-6-6"})})]},e.id)})}),(0,d.jsxs)(hQ.Provider,{value:D,children:[H("general",(0,d.jsx)(yY,{sessionId:i,onSessionReloaded:o,quoteSelectionEnabled:c,onQuoteSelectionChange:p})),H("models",(0,d.jsx)(fl,{embedded:!0,cwd:r,onClose:z})),r&&H("skills",(0,d.jsx)(fv,{embedded:!0,cwd:r,trust:h,onTrustProject:f,onClose:z},r)),r&&H("agents",(0,d.jsx)(fA,{embedded:!0,cwd:r,sessionId:i,trust:h,onClose:z,onReloaded:o},r)),r&&H("plugins",(0,d.jsx)(fq,{embedded:!0,cwd:r,sessionId:i,trust:h,onClose:z,onReloaded:o},r)),H("mcp",(0,d.jsx)(yN,{embedded:!0,cwd:r,trust:h,onTrustProject:f,onProjectTrustChanged:g,onClose:z},r??""))]})]})]})})}let y1="project-trust-mcp-status";function y2(e){let{cwd:t,busy:n,error:r,onCancel:i,onConfirm:s,onStatus:l}=e,[a,o]=(0,u.useState)({state:"loading"}),c=(0,u.useRef)(l);return(0,u.useEffect)(()=>{c.current=l},[l]),(0,u.useEffect)(()=>{let e=!0,n=!1;o({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);o(r),"loaded"===r.state&&r.status&&c.current?.(r.status)}).catch(t=>{e&&o(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,d.jsx)(y4,{cwd:t,busy:n,error:r,listing:a,onCancel:i,onConfirm:s})}function y4(e){let{cwd:t,busy:n,error:r,listing:i,onCancel:s,onConfirm:l}=e,{t:a}=(0,ns.s)(),o="loading"===i.state,c="loaded"===i.state?function(e){if(e){if(!e.requiresTrust)return"mcp.reason.trust-not-required";if(e.trusted)return"trust.alreadyTrusted"}}(i.status):void 0,p=(0,u.useRef)(null),h=(0,u.useRef)(n),m=(0,u.useRef)(s);return(0,u.useEffect)(()=>{h.current=n,m.current=s},[n,s]),(0,u.useEffect)(()=>{var e,t,n;let r,i;return e=document,t=p.current,n=()=>{h.current||m.current()},r=e.activeElement,t?.focus({preventScroll:!0}),i=tW(e,n),()=>{i(),r&&r.isConnected&&"function"==typeof r.focus&&r.focus({preventScroll:!0})}},[]),(0,d.jsx)("div",{role:"presentation",className:"project-trust-backdrop",onClick:e=>{n||e.target!==e.currentTarget||s()},children:(0,d.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,d.jsxs)("div",{className:"project-trust-body",children:[(0,d.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,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,d.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,d.jsxs)("div",{className:"project-trust-content",children:[(0,d.jsx)("div",{id:"project-trust-title",className:"project-trust-title",children:a("trust.dialogTitle")}),(0,d.jsx)("div",{id:"project-trust-description",className:"project-trust-text",children:a("trust.dialogBody")}),(0,d.jsx)("code",{className:"project-trust-path",children:fY(t)}),c&&(0,d.jsx)("p",{id:"project-trust-notice",role:"status",className:"project-trust-notice",children:a(c)}),"loaded"===i.state&&void 0!==i.statusError&&(0,d.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,d.jsx)("p",{className:"project-trust-mcp-line is-warning",children:a("mcp.reason.trust-unreadable")}),(0,d.jsx)("code",{className:"project-trust-mcp-detail",children:fY(i.statusError)})]}),(0,d.jsx)(y8,{listing:i})]})]}),r&&(0,d.jsx)(y3,{error:r}),(0,d.jsxs)("div",{className:"project-trust-footer",children:[(0,d.jsx)("button",{type:"button",className:"project-trust-button",onClick:s,disabled:n,children:a(c?"trust.close":"trust.cancel")}),!c&&(0,d.jsx)("button",{type:"button",className:"project-trust-button is-primary",onClick:l,disabled:n||o,"aria-busy":n||void 0,"aria-describedby":o?y1:void 0,children:a(n?"trust.trusting":"trust.trustProject")})]})]})})}function y3(e){let{error:t}=e,{t:n}=(0,ns.s)(),r=void 0!==t.reason&&"internal"!==t.reason;return(0,d.jsxs)("div",{role:"alert",className:"project-trust-error",children:[n(r?`mcp.reason.${t.reason}`:"trust.trustFailed"),!r&&(0,d.jsx)("code",{className:"project-trust-error-detail",children:fY(t.error)})]})}function y8(e){let{listing:t}=e,{t:n}=(0,ns.s)();if("loading"===t.state)return(0,d.jsx)("p",{id:y1,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 r="failed"===t.state&&t.timedOut;return(0,d.jsxs)("div",{className:"project-trust-mcp-failed",children:[(0,d.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(r?"trust.mcp.timedOut":"trust.mcp.loadFailed")}),e&&(0,d.jsx)("code",{className:"project-trust-mcp-detail",children:fY(e)})]})}let{mcpFile:r,mcpServers:i}=t.listing;return r.exists||0!==r.problems.length?(0,d.jsxs)("section",{className:"project-trust-mcp","aria-labelledby":"project-trust-mcp-title",children:[(0,d.jsx)("div",{id:"project-trust-mcp-title",className:"project-trust-mcp-title",children:n("trust.mcp.title")}),i.length>0&&(0,d.jsx)("p",{className:"project-trust-mcp-intro",children:n("trust.mcp.intro")}),(0,d.jsx)(y6,{file:r}),0===i.length&&0===r.problems.length&&(0,d.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.none")}),i.some(e=>!e.validated)&&(0,d.jsx)("p",{className:"project-trust-mcp-line",children:n("trust.mcp.unchecked")}),i.length>0&&(0,d.jsx)("ul",{className:"project-trust-mcp-list",children:i.map(e=>(0,d.jsx)(y7,{server:e},e.name))})]}):null}function y6(e){let{file:t}=e,{t:n}=(0,ns.s)();return(0,d.jsx)(d.Fragment,{children:t.problems.map(e=>{let r=f6(e,t.realPath);return(0,d.jsxs)("div",{className:"project-trust-mcp-problem",children:[(0,d.jsx)("p",{className:"project-trust-mcp-line is-warning",children:n(`mcp.fileProblem.${e.reason}`)}),r&&(0,d.jsx)("code",{className:"project-trust-mcp-detail",children:r})]},e.reason)})})}function y5(e){let{fields:t}=e,{t:n}=(0,ns.s)();return(0,d.jsx)(d.Fragment,{children:t.map(e=>{let t=f2(e);return(0,d.jsx)("code",{className:"project-trust-mcp-chip",children:n(t.key,t.params)},`${e.kind}\0${e.name??""}`)})})}function y9(e){let{server:t}=e,{t:n}=(0,ns.s)();return(0,d.jsx)(d.Fragment,{children:f8(t.variableReferences).map(e=>{let{variable:t,field:r}=e,i=f2(r);return(0,d.jsx)("code",{className:"project-trust-mcp-chip",children:n("mcp.server.variableIn",{variable:t,field:n(i.key,i.params)})},`${t}\0${r.kind}\0${r.name??""}`)})})}function y7(e){let t,{server:n}=e,{t:r}=(0,ns.s)(),i=f0(n),s=void 0===n.invalidError;return(0,d.jsxs)("li",{className:"project-trust-mcp-server",children:[(0,d.jsxs)("div",{className:"project-trust-mcp-server-head",children:[(0,d.jsx)("span",{className:"project-trust-mcp-server-name",children:fY(n.name)}),n.transport&&(0,d.jsx)("span",{className:"project-trust-mcp-tag",children:r(`mcp.transport.${n.transport}`)})]}),void 0!==i&&(0,d.jsx)("code",{className:"project-trust-mcp-target",children:i}),void 0!==n.cwd&&(0,d.jsx)("p",{className:"project-trust-mcp-line",children:r("trust.mcp.cwd",{path:fY(n.cwd)})}),f1(n)&&(0,d.jsx)("p",{className:"project-trust-mcp-line is-warning",children:r("mcp.server.hiddenCharacters")}),void 0!==n.invalidError&&(0,d.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[r("mcp.server.invalid")," ",(0,d.jsx)("code",{className:"project-trust-mcp-chip",children:fY(n.invalidError)})]}),n.webPasswordField&&(0,d.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[r("mcp.server.webPassword")," ",(0,d.jsx)(y5,{fields:[n.webPasswordField]})]}),!n.enabled&&(0,d.jsx)("p",{className:"project-trust-mcp-line",children:r("mcp.server.disabled")}),s&&n.commandFields.length>0&&(0,d.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[r("mcp.server.commandFields")," ",(0,d.jsx)(y5,{fields:n.commandFields})]}),s&&n.variableReferences.length>0&&(0,d.jsxs)("p",{className:"project-trust-mcp-line is-warning",children:[r(f4(n))," ",(0,d.jsx)(y9,{server:n})]}),n.replacesGlobal&&(0,d.jsx)("p",{className:"project-trust-mcp-line is-warning",children:r("mcp.server.replacesGlobal")}),n.override&&(0,d.jsx)("p",{className:"project-trust-mcp-line is-warning",children:r((t=f3(n.override.keys)).key,t.params)}),n.masked&&(0,d.jsx)("p",{className:"project-trust-mcp-line is-dim",children:r("mcp.server.masked")})]})}function we(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function wt(e){let t=e,n=t.branchPreview,r=we(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&we(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function wn(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 wr(e){let{node:t,activePathIds:n,depth:r,isLast:i,parentLines:s,onSelect:l}=e,{node:a,skipped:o,branchPreview:c,labelEntry:u}=wt(t),p=n.has(a.entry.id),h=n.has(t.entry.id)||n.has(a.entry.id),m=c?.text??function(e){if("message"===e.type&&we(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),f=c?c.role??null:we(u)?u.message.role:null;return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{role:"button",tabIndex:l?0:-1,"aria-disabled":!l,style:{display:"flex",alignItems:"center",height:24,cursor:l?"pointer":"default"},onClick:l?()=>l(a.entry.id):void 0,onKeyDown:l?e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),l(a.entry.id))}:void 0,children:[s.map((e,t)=>(0,d.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,d.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,d.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,d.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,d.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,d.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"}}),f&&(0,d.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===f?"var(--accent)":"var(--text-dim)",background:"user"===f?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===f?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===f?"U":"A"}),o>0&&(0,d.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",o]}),(0,d.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})]}),a.children.map((e,t)=>(0,d.jsx)(wr,{node:e,activePathIds:n,depth:r+1,isLast:t===a.children.length-1,parentLines:[...s,!i],onSelect:l},e.entry.id))]})}function wi(e){let{tree:t,activeLeafId:n,onLeafChange:r,inline:i,embedded:s=!1,containerRef:l,open:a,onToggle:o,hasSession:c,compact:p,hideInlineButton:h,locked:m=!1}=e,{t:f}=(0,ns.s)(),[g,x]=(0,u.useState)(!1),v=void 0!==a?a:g,b=(0,u.useRef)(null),[y,w]=(0,u.useState)(null);(0,u.useEffect)(()=>{if(!v||!i)return;let e=l?.current??b.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();w({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[v,i,l]);let j=(0,u.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]),k=(0,u.useCallback)(e=>{r(e)},[r]),S=m?void 0:k,C=m&&(0,d.jsx)("div",{style:{padding:"2px 0 4px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:f("i18n.branchesLockedWhileRunning")}),N=c?wn(t)?null:f("i18n.noBranches"):f("i18n.noActiveSession"),E=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=wt(e[0]).node;return t.children.length>1?t.children:[]}(t),M=!N&&E.length>0,$=(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:M?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,d.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:v?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,d.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return s?(0,d.jsxs)("div",{className:"workspace-branch-list",children:[(0,d.jsx)("p",{className:"workspace-branch-description",children:f("branches.description")}),C,M?E.map((e,t)=>(0,d.jsx)(wr,{node:e,activePathIds:j,depth:0,isLast:t===E.length-1,parentLines:[],onSelect:S},e.entry.id)):(0,d.jsxs)("div",{className:"workspace-branch-empty",children:[(0,d.jsx)("strong",{children:N}),c&&(0,d.jsx)("p",{children:f("branches.createHint",{action:f("i18n.editFromHere")})})]})]}):i?(0,d.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,d.jsxs)("button",{ref:b,onClick:()=>o?o():x(e=>!e),style:{display:h?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:v?"var(--bg-selected)":"none",border:"none",borderTop:v?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:v?"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=v?"var(--text)":"var(--text-muted)"},title:f("i18n.branches"),"aria-label":f("i18n.branches"),"aria-pressed":v,children:[$,!p&&(0,d.jsx)("span",{children:f("i18n.branches")})]}),v&&y&&(0,d.jsx)("div",{style:{position:"fixed",top:y.top,left:y.left,width:y.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:M?(0,d.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[C,E.map((e,t)=>(0,d.jsx)(wr,{node:e,activePathIds:j,depth:0,isLast:t===E.length-1,parentLines:[],onSelect:S},e.entry.id))]}):(0,d.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:N})})]}):(0,d.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,d.jsxs)("button",{onClick:()=>x(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,d.jsx)("span",{style:{color:"var(--text-muted)"},children:f("i18n.branches")}),I]}),v&&(0,d.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:M?(0,d.jsxs)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:[C,E.map((e,t)=>(0,d.jsx)(wr,{node:e,activePathIds:j,depth:0,isLast:t===E.length-1,parentLines:[],onSelect:S},e.entry.id))]}):(0,d.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:N??f("i18n.noBranches")})})]})}function ws(e){let{loading:t,prompt:n,translate:r}=e;return(0,d.jsxs)("section",{className:"system-prompt-panel","aria-label":r("system.prompt"),children:[(0,d.jsx)("div",{className:"system-prompt-scroll",children:n?(0,d.jsx)("div",{className:"system-prompt-text",children:n}):(0,d.jsx)("div",{className:"system-prompt-empty",children:r(""===n?"system.empty":t?"system.loading":"system.load")})}),(0,d.jsx)("style",{children:`
|
|
86
|
+
.system-prompt-panel {
|
|
87
|
+
display: flex;
|
|
88
|
+
height: min(600px, 75dvh);
|
|
89
|
+
min-height: 220px;
|
|
90
|
+
flex-direction: column;
|
|
91
|
+
background: var(--bg-panel);
|
|
92
|
+
border-bottom: 1px solid var(--border);
|
|
93
|
+
}
|
|
94
|
+
.system-prompt-scroll {
|
|
95
|
+
min-height: 0;
|
|
96
|
+
flex: 1;
|
|
97
|
+
overflow: auto;
|
|
98
|
+
padding: 12px 16px;
|
|
99
|
+
}
|
|
100
|
+
.system-prompt-text {
|
|
101
|
+
color: var(--text-muted);
|
|
102
|
+
font-family: var(--font-mono);
|
|
103
|
+
font-size: 12px;
|
|
104
|
+
line-height: 1.6;
|
|
105
|
+
overflow-wrap: anywhere;
|
|
106
|
+
white-space: pre-wrap;
|
|
107
|
+
}
|
|
108
|
+
.system-prompt-empty {
|
|
109
|
+
padding: 10px 0;
|
|
110
|
+
color: var(--text-muted);
|
|
111
|
+
font-size: 12px;
|
|
112
|
+
font-style: italic;
|
|
113
|
+
}
|
|
114
|
+
`})]})}function wl(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function wa(e){let{children:t}=e;return(0,d.jsx)("div",{className:"tool-definitions-empty",children:t})}function wo(e){let{loading:t,tools:n,translate:r}=e,i=(0,u.useMemo)(()=>n?.filter(e=>e.active&&!e.declarationHidden)??null,[n]),[s,l]=(0,u.useState)(null);(0,u.useEffect)(()=>{l(e=>i?.some(t=>t.name===e)?e:i?.[0]?.name??null)},[i]);let a=i?.find(e=>e.name===s)??i?.[0]??null,o=a?function(e){if(!e||!e.properties||"object"!=typeof e.properties)return[];let t=e.properties,n=new Set(Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[]);return Object.entries(t).map(e=>{let[t,r]=e,i=r&&"object"==typeof r?r:{};return{name:t,type:function e(t){let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(n)return n.map(t=>t&&"object"==typeof t?e(t):"unknown").filter((e,t,n)=>n.indexOf(e)===t).join(" | ");if(void 0!==t.const)return wl(t.const);if(Array.isArray(t.enum)&&t.enum.length>0&&void 0===t.type)return[...new Set(t.enum.map(e=>null===e?"null":typeof e))].join(" | ");let r=t.type,i=Array.isArray(r)?r.filter(e=>"string"==typeof e).join(" | "):"string"==typeof r?r:"string"==typeof t.$ref?t.$ref.split("/").pop()??"object":"unknown";if("array"===i){let n=t.items,r=n&&"object"==typeof n?e(n):"unknown";return`${r}[]`}return i}(i),description:"string"==typeof i.description?i.description:void 0,required:n.has(t),allowedValues:Array.isArray(i.enum)?i.enum.map(wl).join(", "):void 0,defaultValue:void 0===i.default?void 0:wl(i.default)}})}(a.parameters):[];return(0,d.jsxs)("div",{className:"tool-definitions-panel",children:[(0,d.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":r("tools.title"),children:(0,d.jsx)("div",{className:"tool-definitions-list",children:i&&i.length>0?i.map(e=>{let t=e.name===a?.name;return(0,d.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>l(e.name),children:(0,d.jsx)("code",{children:e.name})},e.name)}):i?(0,d.jsx)(wa,{children:r("tools.noTools")}):(0,d.jsx)(wa,{children:t?r("tools.loading"):r("tools.load")})})}),(0,d.jsx)("section",{className:"tool-definition-detail","aria-label":r("tools.details"),children:a?(0,d.jsxs)("div",{className:"tool-definition-scroll",children:[a.description&&(0,d.jsxs)("section",{className:"tool-definition-section",children:[(0,d.jsx)("div",{className:"tool-definition-section-label",children:r("tools.description")}),(0,d.jsx)("div",{className:"tool-definition-description",children:a.description})]}),(0,d.jsxs)("section",{className:"tool-definition-section",children:[(0,d.jsxs)("div",{className:"tool-definition-section-label",children:[(0,d.jsx)("span",{children:r("tools.parameters")}),(0,d.jsx)("span",{children:r("tools.parameterCount",{count:o.length})})]}),o.length>0?(0,d.jsx)("div",{className:"tool-definition-fields",children:o.map(e=>(0,d.jsxs)("div",{className:"tool-definition-field",children:[(0,d.jsxs)("div",{className:"tool-definition-field-name",children:[(0,d.jsx)("code",{children:e.name}),(0,d.jsx)("span",{className:e.required?"required":void 0,children:r(e.required?"tools.required":"tools.optional")})]}),(0,d.jsxs)("div",{className:"tool-definition-field-value",children:[(0,d.jsx)("code",{className:"tool-definition-type",children:e.type}),e.description&&(0,d.jsx)("div",{children:e.description}),e.allowedValues&&(0,d.jsxs)("div",{className:"tool-definition-meta",children:[r("tools.allowedValues"),": ",(0,d.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,d.jsxs)("div",{className:"tool-definition-meta",children:[r("tools.defaultValue"),": ",(0,d.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,d.jsx)("div",{className:"tool-definition-no-parameters",children:r("tools.noParameters")})]}),a.promptGuidelines&&a.promptGuidelines.length>0&&(0,d.jsxs)("section",{className:"tool-definition-section",children:[(0,d.jsx)("div",{className:"tool-definition-section-label",children:r("tools.guidelines")}),(0,d.jsx)("ul",{className:"tool-definition-guidelines",children:a.promptGuidelines.map((e,t)=>(0,d.jsx)("li",{children:e},`${a.name}:${t}`))})]})]}):(0,d.jsx)(wa,{children:i?r("tools.noTools"):t?r("tools.loading"):r("tools.load")})}),(0,d.jsx)("style",{children:`
|
|
115
|
+
.tool-definitions-panel {
|
|
116
|
+
display: grid;
|
|
117
|
+
grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
|
|
118
|
+
height: min(600px, 75dvh);
|
|
119
|
+
min-height: 240px;
|
|
120
|
+
overflow: hidden;
|
|
121
|
+
background: var(--bg-panel);
|
|
122
|
+
border-bottom: 1px solid var(--border);
|
|
123
|
+
}
|
|
124
|
+
.tool-definitions-sidebar,
|
|
125
|
+
.tool-definition-detail {
|
|
126
|
+
display: flex;
|
|
127
|
+
min-width: 0;
|
|
128
|
+
min-height: 0;
|
|
129
|
+
flex-direction: column;
|
|
130
|
+
}
|
|
131
|
+
.tool-definitions-sidebar {
|
|
132
|
+
border-right: 1px solid var(--border);
|
|
133
|
+
background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
|
|
134
|
+
}
|
|
135
|
+
.tool-definitions-list,
|
|
136
|
+
.tool-definition-scroll {
|
|
137
|
+
min-height: 0;
|
|
138
|
+
flex: 1;
|
|
139
|
+
overflow: auto;
|
|
140
|
+
}
|
|
141
|
+
.tool-definitions-item {
|
|
142
|
+
display: flex;
|
|
143
|
+
width: 100%;
|
|
144
|
+
min-height: 38px;
|
|
145
|
+
align-items: center;
|
|
146
|
+
padding: 8px 12px;
|
|
147
|
+
border: none;
|
|
148
|
+
border-bottom: 1px solid var(--border);
|
|
149
|
+
background: transparent;
|
|
150
|
+
color: var(--text-muted);
|
|
151
|
+
cursor: pointer;
|
|
152
|
+
text-align: left;
|
|
153
|
+
}
|
|
154
|
+
.tool-definitions-item:hover {
|
|
155
|
+
background: var(--bg-hover);
|
|
156
|
+
color: var(--text);
|
|
157
|
+
}
|
|
158
|
+
.tool-definitions-item.selected {
|
|
159
|
+
background: var(--bg-selected);
|
|
160
|
+
box-shadow: inset 2px 0 0 var(--accent);
|
|
161
|
+
color: var(--text);
|
|
162
|
+
}
|
|
163
|
+
.tool-definitions-item code {
|
|
164
|
+
max-width: 100%;
|
|
165
|
+
color: inherit;
|
|
166
|
+
font-size: 11px;
|
|
167
|
+
font-weight: 600;
|
|
168
|
+
overflow-wrap: anywhere;
|
|
169
|
+
}
|
|
170
|
+
.tool-definition-scroll {
|
|
171
|
+
padding: 14px 16px 20px;
|
|
172
|
+
}
|
|
173
|
+
.tool-definition-section + .tool-definition-section {
|
|
174
|
+
margin-top: 18px;
|
|
175
|
+
}
|
|
176
|
+
.tool-definition-section-label {
|
|
177
|
+
display: flex;
|
|
178
|
+
align-items: center;
|
|
179
|
+
justify-content: space-between;
|
|
180
|
+
gap: 8px;
|
|
181
|
+
margin-bottom: 7px;
|
|
182
|
+
color: var(--text-dim);
|
|
183
|
+
font-size: 11px;
|
|
184
|
+
font-weight: 600;
|
|
185
|
+
}
|
|
186
|
+
.tool-definition-section-label > span:last-child {
|
|
187
|
+
font-weight: 400;
|
|
188
|
+
white-space: nowrap;
|
|
189
|
+
}
|
|
190
|
+
.tool-definition-description {
|
|
191
|
+
color: var(--text-muted);
|
|
192
|
+
font-size: 12px;
|
|
193
|
+
line-height: 1.55;
|
|
194
|
+
overflow-wrap: anywhere;
|
|
195
|
+
white-space: pre-wrap;
|
|
196
|
+
}
|
|
197
|
+
.tool-definition-fields {
|
|
198
|
+
border-top: 1px solid var(--border);
|
|
199
|
+
}
|
|
200
|
+
.tool-definition-field {
|
|
201
|
+
display: grid;
|
|
202
|
+
grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
|
|
203
|
+
gap: 12px;
|
|
204
|
+
padding: 9px 0;
|
|
205
|
+
border-bottom: 1px solid var(--border);
|
|
206
|
+
font-size: 11px;
|
|
207
|
+
line-height: 1.45;
|
|
208
|
+
}
|
|
209
|
+
.tool-definition-field-name {
|
|
210
|
+
display: flex;
|
|
211
|
+
min-width: 0;
|
|
212
|
+
flex-direction: column;
|
|
213
|
+
gap: 3px;
|
|
214
|
+
color: var(--text);
|
|
215
|
+
}
|
|
216
|
+
.tool-definition-field-name code {
|
|
217
|
+
overflow-wrap: anywhere;
|
|
218
|
+
}
|
|
219
|
+
.tool-definition-field-name span {
|
|
220
|
+
color: var(--text-dim);
|
|
221
|
+
font-size: 10px;
|
|
222
|
+
}
|
|
223
|
+
.tool-definition-field-name span.required {
|
|
224
|
+
color: var(--accent);
|
|
225
|
+
}
|
|
226
|
+
.tool-definition-field-value {
|
|
227
|
+
min-width: 0;
|
|
228
|
+
color: var(--text-muted);
|
|
229
|
+
overflow-wrap: anywhere;
|
|
230
|
+
}
|
|
231
|
+
.tool-definition-type {
|
|
232
|
+
display: block;
|
|
233
|
+
margin-bottom: 3px;
|
|
234
|
+
color: var(--text);
|
|
235
|
+
}
|
|
236
|
+
.tool-definition-meta {
|
|
237
|
+
margin-top: 4px;
|
|
238
|
+
color: var(--text-dim);
|
|
239
|
+
}
|
|
240
|
+
.tool-definition-meta code {
|
|
241
|
+
color: var(--text-muted);
|
|
242
|
+
}
|
|
243
|
+
.tool-definition-no-parameters {
|
|
244
|
+
padding: 2px 0 10px;
|
|
245
|
+
color: var(--text-dim);
|
|
246
|
+
font-size: 11px;
|
|
247
|
+
}
|
|
248
|
+
.tool-definition-guidelines {
|
|
249
|
+
margin: 0;
|
|
250
|
+
padding-left: 18px;
|
|
251
|
+
color: var(--text-muted);
|
|
252
|
+
font-size: 11px;
|
|
253
|
+
line-height: 1.5;
|
|
254
|
+
}
|
|
255
|
+
.tool-definitions-empty {
|
|
256
|
+
padding: 14px 12px;
|
|
257
|
+
color: var(--text-muted);
|
|
258
|
+
font-size: 12px;
|
|
259
|
+
font-style: italic;
|
|
260
|
+
overflow-wrap: anywhere;
|
|
261
|
+
}
|
|
262
|
+
@media (max-width: 640px) {
|
|
263
|
+
.tool-definitions-panel {
|
|
264
|
+
grid-template-columns: 112px minmax(0, 1fr);
|
|
265
|
+
}
|
|
266
|
+
.tool-definitions-item {
|
|
267
|
+
padding: 8px 10px;
|
|
268
|
+
}
|
|
269
|
+
.tool-definition-scroll {
|
|
270
|
+
padding: 12px;
|
|
271
|
+
}
|
|
272
|
+
.tool-definition-field {
|
|
273
|
+
grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
|
|
274
|
+
gap: 9px;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
`})]})}function wc(e){let{status:t}=e;return"queued"===t?(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M12 7v5l3 2"})]}):"running"===t||"starting"===t?(0,d.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,d.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):"failed"===t?(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"aborted"===t||"interrupted"===t?(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"m8 12 3 3 5-6"})]})}var wd=n(91822),wu=n.n(wd);async function wp(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fetch,r={};for(let i=0;i<e.length;i+=200){let s=await n("/api/sessions/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:e.slice(i,i+200)}),signal:t,cache:"no-store"});if(!s.ok)return null;let l=await s.json();if(!l.stats)return null;Object.assign(r,l.stats)}return r}function wh(e,t,n){let{tokens:r}=e;return[`${t("session.totalActive")}: ${dY(e.totalActiveMs)}`,`${t("session.input")}: ${r.input.toLocaleString(n)}`,`${t("session.output")}: ${r.output.toLocaleString(n)}`,...r.cacheRead>0?[`${t("session.cacheRead")}: ${r.cacheRead.toLocaleString(n)}`]:[],...r.cacheWrite>0?[`${t("session.cacheWrite")}: ${r.cacheWrite.toLocaleString(n)}`]:[],`${t("session.total")}: ${r.total.toLocaleString(n)}`,...e.cost>0?[`${t("session.cost")}: $${e.cost.toFixed(4)}`]:[],`${t("session.toolCalls")}: ${e.toolCalls.toLocaleString(n)}`].join("\n")}function wm(e){let{usage:t,style:n}=e,{locale:r,t:i}=(0,ns.s)(),s=dJ(t.cost);return(0,d.jsxs)("span",{title:wh(t,i,r),style:{display:"flex",alignItems:"center",gap:10,minWidth:0,color:"var(--text-dim)",fontSize:11,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",...n},children:[t.totalActiveMs>0&&(0,d.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:3},children:[(0,d.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M12 7v5l3 2"})]}),dY(t.totalActiveMs)]}),t.tokens.total>0&&(0,d.jsx)("span",{children:i("agentSwitcher.tokens",{count:dZ(t.tokens.total)})}),s&&(0,d.jsx)("span",{style:{color:"var(--text-muted)"},children:s})]})}function wf(e){let{kind:t,size:n}=e;return(0,d.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:"main"===t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,d.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):"side"===t?(0,d.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,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,d.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})}function wg(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let s=Math.round(r/60);if(60>Math.abs(s))return i.format(s,"minute");let l=Math.round(s/60);return 24>Math.abs(l)?i.format(l,"hour"):i.format(Math.round(l/24),"day")}function wx(e){let{kind:t}=e;return(0,d.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:"main"===t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,d.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):"side"===t?(0,d.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,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,d.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})})}function wv(e,t,n){return e.relation?.kind==="side"?x(e,t("agentSwitcher.sideChat"),n):e.relation?.kind==="subagent"?b(e):e.name||e.firstMessage||e.id.slice(0,12)}function wb(e){let{rootSession:t,subagents:n,selectedSessionId:r,runningSessionIds:i,onSelectSession:s,openSubagentTabIds:l,onToggleSubagentTab:a,onNewSideChat:o,onDeleteSideChat:c}=e,{t:p,locale:h}=(0,ns.s)(),m=nf(),[f,g]=(0,u.useState)(""),[x,v]=(0,u.useState)(r),[b,y]=(0,u.useState)(!1),[w,j]=(0,u.useState)(null),[k,S]=(0,u.useState)(null),[C,N]=(0,u.useState)(null),[E,M]=(0,u.useState)(null),$=(0,u.useRef)(null),I=(0,u.useRef)(null),T=(0,u.useRef)(null),R=(0,u.useMemo)(()=>[...n].sort((e,t)=>Number(i.has(t.id))-Number(i.has(e.id))||t.modified.localeCompare(e.modified)),[n,i]),A=f.trim().toLocaleLowerCase(h),L=R.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return!A||[wv(e,p,n),t?.profile,e.firstMessage,e.relation?.kind==="side"?p("agentSwitcher.sideChat"):p("agentSwitcher.subagent")].some(e=>e?.toLocaleLowerCase(h).includes(A))}),P=R.filter(e=>e.relation?.kind==="side"),z=R.filter(e=>e.relation?.kind!=="side"),O=L.filter(e=>e.relation?.kind==="side"),W=L.filter(e=>e.relation?.kind!=="side"),F=[t,...O,...W].find(e=>e.id===x)??t,D=F.id===t.id,_=F.relation?.kind==="side",B=F.relation?.kind==="subagent"?F.relation:null,H=F.id===r,U=i.has(F.id)?"running":B?.status,K=D?"main":_?"side":"subagent",q=wv(F,p,n),V=p(D?"collaboration.mainSession":_?"agentSwitcher.sideChat":"agentSwitcher.subagent"),Z=(0,u.useMemo)(()=>[t.id,...n.map(e=>e.id)],[t.id,n]),J=Z.filter(e=>i.has(e)).join(","),Y=function(e,t){let[n,r]=(0,u.useState)({}),i=e.join(",");return(0,u.useEffect)(()=>{let e=i?i.split(","):[];if(0===e.length)return;let n=new AbortController,s=!1,l=async()=>{if(!s){s=!0;try{let t=await wp(e,n.signal);!n.signal.aborted&&t&&r(t)}catch{}finally{s=!1}}};if(l(),!t)return()=>n.abort();let a=setInterval(()=>{"visible"===document.visibilityState&&l()},3e3);return()=>{clearInterval(a),n.abort()}},[i,t]),n}(Z,J),G=Y[F.id],X=(0,u.useMemo)(()=>{let e=Z.map(e=>Y[e]).filter(e=>!!e);return e.length?e.reduce((e,t)=>({tokens:{input:e.tokens.input+t.tokens.input,output:e.tokens.output+t.tokens.output,cacheRead:e.tokens.cacheRead+t.tokens.cacheRead,cacheWrite:e.tokens.cacheWrite+t.tokens.cacheWrite,total:e.tokens.total+t.tokens.total},cost:e.cost+t.cost,toolCalls:e.toolCalls+t.toolCalls,totalActiveMs:e.totalActiveMs+t.totalActiveMs}),{tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,toolCalls:0,totalActiveMs:0}):null},[Z,Y]),Q=Z.filter(e=>i.has(e)).length;(0,u.useEffect)(()=>{if(!k)return;let e=requestAnimationFrame(()=>T.current?.querySelector(".session-tree-confirm-cancel")?.focus());return()=>cancelAnimationFrame(e)},[k]);let ee=e=>{v(e),S(null),M(null)},et=async()=>{if(!b){y(!0),j(null);try{j(await o())}catch(e){j(e instanceof Error?e.message:String(e))}finally{y(!1)}}},en=()=>{S(null),$.current?.focus()},er=async e=>{if(!C){S(null),N(e),j(null);try{let n=await c(e);n?j(p("sidebar.deleteFailed",{error:n})):(v(t.id),I.current?.querySelector("[data-collaboration-session]")?.focus())}catch(e){j(p("sidebar.deleteFailed",{error:e instanceof Error?e.message:String(e)}))}finally{N(null)}}},ei=(e,s,l,a)=>(0,d.jsxs)("section",{className:wu().group,"aria-label":e,children:[(0,d.jsxs)("h2",{children:[e,(0,d.jsx)("span",{children:l})]}),s.map(e=>{var s,l;let a=e.id===t.id,o=e.relation?.kind==="side",c=e.relation?.kind==="subagent"?e.relation:null,u=i.has(e.id),m=Y[e.id]?.model,f=Y[e.id]?.thinkingLevel,g=[c?.profile,m?.modelId,f&&"off"!==f?f:null].filter(Boolean).join(" \xb7 ");return(0,d.jsxs)("button",{type:"button","data-collaboration-session":e.id,className:wu().member,"aria-pressed":F.id===e.id,"aria-controls":"collaboration-detail",onClick:()=>ee(e.id),title:[wv(e,p,n),m?`${m.provider}/${m.modelId}`:"",g].filter(Boolean).join("\n"),children:[(0,d.jsx)("span",{className:wu().memberIcon,children:(0,d.jsx)(wx,{kind:a?"main":o?"side":"subagent"})}),(0,d.jsxs)("span",{className:wu().memberCopy,children:[(0,d.jsx)("strong",{children:wv(e,p,n)}),(0,d.jsx)("span",{children:a?p(e.id===r?"collaboration.currentChat":"agentSwitcher.main"):g||wg(e.modified,h)}),!!((s=Y[e.id])&&(s.tokens.total>0||s.totalActiveMs>0))&&(0,d.jsx)(wm,{usage:Y[e.id]})]}),(u||c)&&(0,d.jsx)("span",{className:wu().memberStatus,style:{color:"running"===(l=u?"running":c.status)||"starting"===l?"var(--accent)":"completed"===l?"#16a34a":"failed"===l?"#dc2626":"aborted"===l?"#d97706":"var(--text-dim)"},title:p(`agentSwitcher.status.${u?"running":c.status}`),children:(0,d.jsx)(wc,{status:u?"running":c.status})})]},e.id)}),0===s.length&&0===l&&a&&(0,d.jsx)("p",{className:wu().empty,children:a})]},e);return(0,d.jsxs)("div",{className:wu().panel,children:[(0,d.jsxs)("div",{className:wu().toolbar,children:[(0,d.jsx)("p",{children:p("collaboration.counts",{sides:P.length,agents:z.length})}),(0,d.jsxs)("button",{type:"button",className:`${wu().action} ${wu().primary}`,disabled:b,onClick:()=>{et()},children:[(0,d.jsx)("span",{"aria-hidden":"true",children:"+"}),p("sideChat.new")]})]}),(0,d.jsxs)("div",{className:wu().summary,children:[(0,d.jsx)("span",{title:p("collaboration.totalUsageHint"),children:p("collaboration.totalUsage")}),X?(0,d.jsx)(wm,{usage:X}):(0,d.jsx)("span",{children:"—"}),Q>0&&(0,d.jsx)("span",{children:p("agentSwitcher.runningCount",{count:Q})})]}),w&&(0,d.jsx)("p",{className:wu().error,role:"alert",children:w}),(0,d.jsxs)("div",{className:wu().layout,children:[(0,d.jsxs)("nav",{className:wu().list,"aria-label":p("collaboration.sessions"),ref:I,onKeyDown:e=>{if(e.altKey||e.ctrlKey||e.metaKey||e.nativeEvent.isComposing||!["ArrowDown","ArrowUp","Home","End"].includes(e.key)||!(e.target instanceof HTMLElement)||!e.target.closest("[data-collaboration-session]"))return;let t=[...e.currentTarget.querySelectorAll("[data-collaboration-session]")],n=t.findIndex(e=>e===document.activeElement),r="Home"===e.key?0:"End"===e.key?t.length-1:Math.max(0,Math.min(t.length-1,n+("ArrowDown"===e.key?1:-1)));e.preventDefault(),t[r]?.focus();let i=t[r]?.dataset.collaborationSession;i&&ee(i)},children:[n.length>8&&(0,d.jsx)("input",{className:wu().search,type:"search",value:f,onChange:e=>g(e.target.value),placeholder:p("agentSwitcher.search"),"aria-label":p("agentSwitcher.search")}),ei(p("collaboration.mainSession"),[t],1),ei(p("collaboration.sideChats"),O,P.length,p("collaboration.noSides")),ei(p("collaboration.subagents"),W,z.length,p("collaboration.noSubagents")),A&&!L.length&&(0,d.jsx)("p",{className:wu().empty,children:p("agentSwitcher.noMatches")})]}),(0,d.jsxs)("section",{id:"collaboration-detail",className:wu().detail,"aria-label":p("collaboration.details"),children:[(0,d.jsxs)("header",{className:wu().detailHeader,children:[(0,d.jsx)(wx,{kind:K}),(0,d.jsxs)("div",{children:[(0,d.jsx)("h2",{children:q}),(0,d.jsxs)("p",{children:[V,H&&(0,d.jsx)("span",{className:wu().current,children:p("collaboration.currentChat")})]})]})]}),(0,d.jsxs)("dl",{className:wu().fields,children:[(0,d.jsx)("dt",{children:p("collaboration.status")}),(0,d.jsx)("dd",{className:wu().status,children:U?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(wc,{status:U}),(0,d.jsx)("span",{children:p(`agentSwitcher.status.${U}`)})]}):p("collaboration.idle")}),B?.profile&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("dt",{children:p("collaboration.profile")}),(0,d.jsx)("dd",{children:B.profile})]}),G?.model&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("dt",{children:p("collaboration.model")}),(0,d.jsx)("dd",{title:`${G.model.provider}/${G.model.modelId}`,children:G.model.modelId})]}),G?.thinkingLevel&&"off"!==G.thinkingLevel&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("dt",{children:p("collaboration.thinking")}),(0,d.jsx)("dd",{children:G.thinkingLevel})]}),(0,d.jsx)("dt",{children:p("collaboration.updated")}),(0,d.jsx)("dd",{children:(0,d.jsx)("time",{dateTime:F.modified,title:new Date(F.modified).toLocaleString(h),children:wg(F.modified,h)||"—"})})]}),(0,d.jsxs)("dl",{className:wu().fields,title:G?wh(G,p,h):void 0,children:[(0,d.jsx)("dt",{children:p("session.totalActive")}),(0,d.jsx)("dd",{children:G?dY(G.totalActiveMs):"—"}),(0,d.jsx)("dt",{children:p("session.total")}),(0,d.jsx)("dd",{children:G?p("agentSwitcher.tokens",{count:dZ(G.tokens.total)}):"—"}),(0,d.jsx)("dt",{children:p("session.cost")}),(0,d.jsx)("dd",{children:G?dJ(G.cost)||"$0.00":"—"}),(0,d.jsx)("dt",{children:p("session.toolCalls")}),(0,d.jsx)("dd",{children:G?G.toolCalls.toLocaleString(h):"—"})]}),(0,d.jsxs)("div",{className:wu().actions,children:[(0,d.jsx)("button",{type:"button",className:wu().action,onClick:()=>s(F),children:p(H?"collaboration.continue":"collaboration.openMain")}),!D&&(0,d.jsx)("button",{type:"button",className:wu().action,"aria-pressed":l.has(F.id),disabled:H,onClick:()=>a(F.id,_?p("sideChat.title"):q,_),title:H?p("agentSwitcher.openInMainChat"):void 0,children:p(l.has(F.id)?"collaboration.closePanel":"collaboration.openPanel")}),_&&(0,d.jsx)("button",{ref:$,type:"button",className:`${wu().action} ${wu().more}`,"aria-haspopup":"menu","aria-expanded":!!E,disabled:!!C,onClick:()=>{let e=$.current?.getBoundingClientRect();e&&M({kind:"rect",rect:e,align:"end"})},children:p("collaboration.more")})]}),k===F.id&&(0,d.jsx)("div",{ref:T,className:wu().confirm,onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),en())},children:(0,d.jsx)(im,{label:p("sidebar.deleteSession",{title:q}),deleteLabel:p("sidebar.delete"),cancelLabel:p("sidebar.cancel"),onConfirm:()=>{er(F.id)},onCancel:en})})]})]}),(0,d.jsx)(r4,{open:_&&!!E,anchor:E,sheet:m,ariaLabel:p("collaboration.more"),title:q,cancelLabel:p("sidebar.cancel"),returnFocusTo:$.current,onClose:()=>M(null),items:_?[{type:"item",id:"delete",label:p("sidebar.delete"),icon:(0,d.jsx)(nG,{size:14}),danger:!0,onSelect:()=>S(F.id)}]:[]})]})}var wy=n(5284),ww=n.n(wy);function wj(e){let{locked:t,iconSize:n=16,className:r,...i}=e;return(0,d.jsx)("button",{...i,type:"button","aria-pressed":t,className:r?`${ww().lock} ${r}`:ww().lock,children:(0,d.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),t?(0,d.jsx)("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"}):(0,d.jsx)("path",{d:"M8 11V7a4 4 0 0 1 7.9-.9"})]})})}let wk="\0lock";function wS(e){let{rootSession:t,members:n,selectedSessionId:r,runningSessionIds:i,onSelectSession:s,locked:l,onToggleLock:a}=e,{t:o}=(0,ns.s)(),c=(0,u.useRef)(null),p=hc('[aria-current="true"]',`${n.length}
|
|
278
|
+
${r}`),[h,m]=(0,u.useState)(null),f=h&&(h===t.id||h===wk||n.some(e=>e.id===h))?h:r,g=r===t.id,v=o("agentSwitcher.status.running"),y=i.has(t.id);return(0,d.jsxs)("div",{ref:c,role:"toolbar","aria-label":o("agentSwitcher.strip"),onKeyDown:e=>{let t=[...c.current?.querySelectorAll("button")??[]],n=t.indexOf(document.activeElement);if(n<0)return;let r="ArrowRight"===e.key?Math.min(n+1,t.length-1):"ArrowLeft"===e.key?Math.max(n-1,0):"Home"===e.key?0:"End"===e.key?t.length-1:-1;r<0||(e.preventDefault(),t[r].focus())},style:{display:"flex",alignItems:"center",gap:6,height:34,padding:"0 8px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,d.jsx)(wC,{label:o("agentSwitcher.main"),title:g?o("agentSwitcher.main"):o("agentSwitcher.backToMain"),current:g,tabStop:f===t.id,icon:y?(0,d.jsx)(wc,{status:"running"}):g?(0,d.jsx)(wf,{kind:"main",size:12}):(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M19 12H5M11 6l-6 6 6 6"})}),running:y,onFocus:()=>m(t.id),onClick:()=>s(t)}),(0,d.jsx)("span",{"aria-hidden":"true",style:{width:1,height:16,flexShrink:0,background:"var(--border)"}}),(0,d.jsx)("div",{ref:p,className:"tabbar-scroll",style:{flex:1,minWidth:0,height:"100%",display:"flex",alignItems:"center",gap:6,overflowX:"auto",overflowY:"hidden"},children:n.map(e=>{let t=e.relation?.kind==="side",l=e.relation?.kind==="subagent"?e.relation:null,a=t?x(e,o("agentSwitcher.sideChat"),n):b(e),c=i.has(e.id),u=t?o("agentSwitcher.sideChat"):l?.profile??o("agentSwitcher.subagent");return(0,d.jsx)(wC,{label:a,title:[a,u,c?v:null].filter(Boolean).join(" 路 "),current:e.id===r,tabStop:f===e.id,icon:c?(0,d.jsx)(wc,{status:"running"}):(0,d.jsx)(wf,{kind:t?"side":"subagent",size:12}),running:c,onFocus:()=>m(e.id),onClick:()=>s(e)},e.id)})}),(0,d.jsx)("span",{"aria-hidden":"true",style:{width:1,height:16,flexShrink:0,background:"var(--border)"}}),(0,d.jsx)(wj,{locked:l,iconSize:14,onClick:a,onFocus:()=>m(wk),"aria-label":o("agentSwitcher.lockStrip"),title:l?o("agentSwitcher.unlockStrip"):o("agentSwitcher.lockStrip"),tabIndex:f===wk?0:-1,style:{flexShrink:0,width:24,height:24,borderRadius:6}})]})}function wC(e){let{label:t,title:n,current:r,tabStop:i,icon:s,running:l,onFocus:a,onClick:o}=e;return(0,d.jsxs)("button",{type:"button",onClick:o,onFocus:a,title:n,tabIndex:i?0:-1,"aria-current":r?"true":void 0,className:r?"cursor-pointer text-text":"cursor-pointer bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",style:{display:"flex",alignItems:"center",gap:5,flexShrink:0,maxWidth:200,height:24,padding:"0 9px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:12,background:r?"var(--bg-selected)":void 0,fontSize:11,fontWeight:r?600:500,whiteSpace:"nowrap"},children:[(0,d.jsx)("span",{style:{display:"grid",placeItems:"center",flexShrink:0,color:l||r?"var(--accent)":"var(--text-dim)"},children:s}),(0,d.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}let wN={idle:"debug.stream.state.idle",connecting:"debug.stream.state.connecting",connected:"debug.stream.state.connected",retrying:"debug.stream.state.retrying"},wE={ready_timeout:"debug.stream.error.readyTimeout",startup_error:"debug.stream.error.startup",error:"debug.stream.error.error",stale:"debug.stream.error.stale"},wM={visible:"debug.stream.reattach.visible",activity:"debug.stream.reattach.activity"},w$={agent:"debug.page.source.agent","file-watch":"debug.page.source.fileWatch",terminal:"debug.page.source.terminal"},wI={connecting:"debug.page.source.connecting",open:"debug.page.source.open"},wT={reply:"debug.lease.outcome.reply",unanswered:"debug.lease.outcome.unanswered",error:"debug.lease.outcome.error"},wR={alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none"},wA={timeout:"debug.poll.timeout",http:"debug.poll.http",network:"debug.poll.network",invalid:"debug.poll.invalid"},wL={starting:"agentSwitcher.status.starting",queued:"agentSwitcher.status.queued",running:"agentSwitcher.status.running",completed:"agentSwitcher.status.completed",failed:"agentSwitcher.status.failed",aborted:"agentSwitcher.status.aborted",interrupted:"agentSwitcher.status.interrupted",unknown:"debug.unknown"},wP={released:"debug.stream.close.released",grace_end:"debug.stream.close.graceEnd",send_failed:"debug.stream.close.sendFailed",set_tools:"debug.stream.close.setTools",rebuilt:"debug.stream.close.rebuilt",deselected:"debug.stream.close.deselected",stuck:"debug.stream.close.stuck",replaced:"debug.stream.close.replaced"};function wz(e,t,n){return Object.prototype.hasOwnProperty.call(t,e)?n(t[e]):e}function wO(e){return Number.isFinite(e)?Math.max(0,e):0}function wW(e){return String(e).padStart(2,"0")}function wF(e,t){let n=wO(e);return n<1e3?t("debug.duration.ms",{count:Math.floor(n)}):n<6e4?t("debug.duration.seconds",{count:Math.floor(n/1e3)}):n<36e5?t("debug.duration.minutesSeconds",{minutes:Math.floor(n/6e4),seconds:wW(Math.floor(n%6e4/1e3))}):n<864e5?t("debug.duration.hoursMinutes",{hours:Math.floor(n/36e5),minutes:wW(Math.floor(n%36e5/6e4))}):t("debug.duration.daysHours",{days:Math.floor(n/864e5),hours:Math.floor(n%864e5/36e5)})}function wD(e,t){return t("debug.time.ago",{time:wF(e,t)})}function w_(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"floor",r=Math[n](wO(e)/1e3);return r<60?t("debug.duration.seconds",{count:r}):wF(1e3*r,t)}function wB(e,t){return e>0?t("debug.time.in",{time:w_(e,t,"ceil")}):t("debug.time.due")}function wH(e,t){return e>0?t("debug.time.in",{time:wF(e,t)}):t("debug.time.due")}function wU(e){return e.length>8?e.slice(0,8):e}function wK(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wq(e){return"number"==typeof e&&Number.isFinite(e)}function wV(e){var t;return wK(e)&&"string"==typeof e.sessionId&&"string"==typeof e.state&&wq(e.eventStreams)&&(null===(t=e.nextIdleCheckAt)||wq(t))}function wZ(e,t){try{return e()}catch{return t}}function wJ(e){if(!e)return{client:null,failed:!1};try{return{client:e()??null,failed:!1}}catch{return{client:null,failed:!0}}}function wY(e,t){return e?.sessionId??t}let wG={sessionId:null,reply:null,receivedAt:null,roundTripMs:null,failure:null,requests:0,failures:0,consecutiveFailures:0},wX=e=>e.filter(Boolean).join(" \xb7 ");function wQ(e,t,n){return null===e?n("debug.holder.none"):`${n(e===t?"debug.holder.thisPage":"debug.holder.otherPage")} ${wU(e)}`}function w0(e,t){let n=e.filter(e=>null!==e.holder&&e.holder===t);return[...n,...e.filter(e=>!n.includes(e))]}let w1={running:"debug.overlay.running",awaiting:"debug.overlay.awaiting",alive:"debug.state.alive",closing:"debug.state.closing",none:"debug.state.none",starting:"debug.server.starting"};function w2(e){return e.awaitingInput?"awaiting":e.running?"running":e.state}function w4(e,t){return null===e.label?"—":"agent"===e.kind?t?.(e.label)??wU(e.label):eW(e.label)}function w3(e,t){if(!(t>0))return null;let n=e/t;return Number.isFinite(n)?Math.min(1,Math.max(0,n)):0}function w8(e,t){if(!e||"connected"!==e.state||!e.watchdogArmed)return null;let n=e.staleAfterMs;return null!==n&&n>0&&null!==e.lastSeenAt?{ageMs:Math.max(0,t-e.lastSeenAt),staleAfterMs:n}:null}function w6(e,t){return t>0?e>=t?"error":e>=t/2?"warning":"dim":"dim"}let w5={poll:[],running:[]};function w9(e){let t=wO(e);return{ms:t,tone:t>=2e3?"warning":"dim",failed:!1}}function w7(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:30,r=[...e,t];return r.length>n?r.slice(r.length-n):r}function je(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:-1/0}function jt(e,t){return e===t?0:t>e?1:-1}class jn extends u.Component{static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e){console.error("Debug panel failed:",e)}render(){return this.state.failed?(0,d.jsx)("div",{role:"status",style:{padding:"10px 16px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",color:"var(--text-muted)",fontSize:12},children:this.props.fallback}):this.props.children}constructor(...e){super(...e),this.state={failed:!1}}}function jr(e){let{readerRef:t,selectedSessionId:n,sessions:r,onClose:i}=e,{t:s}=(0,ns.s)(),l=(0,u.useRef)(n);l.current=n;let a=(0,u.useRef)(i);a.current=i;let o=(0,u.useRef)(null),c=(0,u.useRef)(!1),p=(0,u.useRef)(null),h=(0,u.useRef)(null),m=(0,u.useRef)(null),[f,g]=(0,u.useState)(null),[x,v]=(0,u.useState)(wG),[b,y]=(0,u.useState)(w5),[w,j]=(0,u.useState)(!1),[k,S]=(0,u.useState)(null),C=(0,u.useRef)({page:f,server:x,samples:b});C.current={page:f,server:x,samples:b},(0,u.useEffect)(()=>{let e=h.current;if(!e)return;let t=null,n=n=>{if("mouse"!==n.pointerType)return;let r=n.target instanceof Element?n.target.closest("[title]"):null,i=r&&e.contains(r)?r:null;i!==t&&(t=i,S(i?C.current:null))},r=()=>{t=null,S(null)};return e.addEventListener("pointerover",n),e.addEventListener("pointerleave",r),()=>{e.removeEventListener("pointerover",n),e.removeEventListener("pointerleave",r)}},[]),(0,u.useEffect)(()=>{var e;let n,r,i,s,a,d,u,h,f;c.current=!1;let x=(r=(e={fetch:(e,t)=>fetch(e,t),sessionId:()=>wY(wJ(t.current).client,l.current),isVisible:()=>"visible"===document.visibilityState,onReading:e=>{v(e);let t=function(e){if(e.failure){let t="timeout"===e.failure.kind;return{ms:5e3*!!t,tone:t?"warning":"error",failed:!0}}return null===e.roundTripMs?null:w9(e.roundTripMs)}(e);t&&y(e=>({...e,poll:w7(e.poll,t)}))}}).now??(()=>Date.now()),i=e.setTimeout??((e,t)=>setTimeout(e,t)),s=e.clearTimeout??(e=>clearTimeout(e)),a=!1,d=null,u=wG,h=async t=>{let l=new AbortController,o={sessionId:t,controller:l,startedAt:r()};d=o,n=t;let c=!1,p=i(()=>{c=!0,l.abort()},5e3),h=null,m=null;try{var f,g;let n=await e.fetch(t?`/api/agent/debug?session=${encodeURIComponent(t)}`:"/api/agent/debug",{cache:"no-store",signal:l.signal});if(n.ok){let e=null;try{e=await n.json()}catch(e){if(l.signal.aborted)throw e}(f=e,wK(f)&&wq(f.now)&&wK(g=f.server)&&wq(g.startedAt)&&wK(g.wrappers)&&wK(g.eventStreams)&&wq(g.sseTotal)&&Array.isArray(g.pages)&&wK(g.terminals)&&Array.isArray(f.sessions)&&f.sessions.every(wV)&&(null===f.session||function(e){if(!wK(e)||"string"!=typeof e.sessionId)return!1;let t=e.wrapper,n=e.subagents,r=e.mcp;return(null===t||wK(t)&&"string"==typeof t.state&&wK(t.run)&&wK(t.idle))&&(null===e.lifecycle||wK(e.lifecycle))&&(null===e.providers||Array.isArray(e.providers))&&Array.isArray(e.eventStreams)&&wK(n)&&Array.isArray(n.runs)&&Array.isArray(n.notifications)&&(null===r||wK(r)&&Array.isArray(r.servers))}(f.session)))?h=e:m={kind:"invalid",status:n.status}}else m={kind:"http",status:n.status}}catch{m={kind:c?"timeout":"network",status:null}}finally{s(p),d===o&&(d=null)}if(a||l.signal.aborted&&!c||e.sessionId()!==t)return;let x=r(),v=u.sessionId===t;u=h?{sessionId:t,reply:h,receivedAt:x,roundTripMs:Math.max(0,x-o.startedAt),failure:null,requests:u.requests+1,failures:u.failures,consecutiveFailures:0}:{sessionId:t,reply:v?u.reply:null,receivedAt:v?u.receivedAt:null,roundTripMs:v?u.roundTripMs:null,failure:{...m??{kind:"invalid",status:null},at:x},requests:u.requests+1,failures:u.failures+1,consecutiveFailures:u.consecutiveFailures+1},e.onReading(u)},{poll:f=()=>{if(a||!e.isVisible())return;let t=e.sessionId();if(d){if(d.sessionId===t)return;d.controller.abort()}h(t)},sync(){a||(d?d.sessionId:n)!==e.sessionId()&&f()},inFlightSince:()=>d?.startedAt??null,dispose(){a=!0,d?.controller.abort(),d=null}});o.current=x;let b=()=>{let e=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Date.now(),{client:r,failed:i}=wJ(e);return{at:n,client:r,clientFailed:i,sources:wZ(tZ,[]),visibility:wZ(tG,null),protocol:wZ(t0,null),runningPoll:wZ(tQ,null),pollInFlightSince:t}}(t.current,x.inFlightSince());g(e);let n=e.runningPoll?.last??null;if(n&&n.at!==m.current){m.current=n.at;let e=n&&"aborted"!==n.outcome?"error"===n.outcome?{ms:wO(n.durationMs),tone:"error",failed:!0}:w9(n.durationMs):null;e&&y(t=>({...t,running:w7(t.running,e)}))}};b(),x.poll();let w=window.setInterval(()=>{"visible"===document.visibilityState&&(b(),x.sync())},1e3),j=window.setInterval(()=>x.poll(),2e3),k=()=>{"visible"===document.visibilityState&&(b(),x.poll())};return document.addEventListener("visibilitychange",k),()=>{c.current=!0,x.dispose(),o.current=null,window.clearInterval(w),window.clearInterval(j),document.removeEventListener("visibilitychange",k),p.current&&clearTimeout(p.current)}},[t]),(0,u.useEffect)(()=>{o.current?.sync()},[n]),(0,u.useEffect)(()=>{var e,t,n;let r=(e=document,t=()=>h.current,n=e=>a.current(e),r=>{var i;if(i=null!==e.querySelector('[aria-modal="true"]'),"Escape"!==r.key||r.defaultPrevented||r.cancelBubble||r.isComposing||229===r.keyCode||i)return;r.preventDefault();let s=e.activeElement;n(!!(s&&t()?.contains(s)))});return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[]);let N=k??{page:f,server:x,samples:b};return(0,d.jsx)(ji,{page:N.page,server:N.server,samples:N.samples,selectedSessionId:n,sessions:r,copied:w,onCopy:()=>{let e={client:f,server:x.reply};j(!1),s$(JSON.stringify(e,null,2)).then(()=>{c.current||(p.current&&clearTimeout(p.current),j(!0),p.current=setTimeout(()=>j(!1),1400))},()=>{})},t:s,sectionRef:h})}function ji(e){var t;let n,{page:r,server:i,samples:s=w5,selectedSessionId:l,sessions:a,copied:o,onCopy:c,t:p,sectionRef:h}=e,m=r?.at??i.receivedAt??0,f=r?.client??null,g=wY(f,l),x=i.reply,v=x&&null!==i.receivedAt?(t=x.now,n=Math.max(0,m-i.receivedAt),{remaining:e=>e-t-n,age:e=>t-e+n}):null,b=x?.session&&x.session.sessionId===g?x.session:null,y=f?.pageId??null,w=(0,u.useMemo)(()=>new Map(a.map(e=>[e.id,e])),[a]),j=(0,u.useMemo)(()=>e=>{let t=w.get(e);return t?io(t):null},[w]),k=(0,u.useMemo)(()=>x?function(e,t,n){let r=e=>{let n=e,r=new Set([e.id]);for(let i=0;i<32;i++){let i=n.relation;if(i?.kind!=="subagent")break;let s=t.get(i.parentSessionId);if(!s)break;if(r.has(s.id))return e;r.add(s.id),n=s}return n},i=new Map,s=[];for(let n of e){let e=t.get(n.sessionId);if(!e){s.push(n);continue}let l=r(e),a=i.get(l.id);a||(a={root:l,summary:null,subagents:[]},i.set(l.id,a)),l.id===e.id?a.summary=n:a.subagents.push({info:e,summary:n})}let l=null===n?void 0:t.get(n),a=l?r(l).id:null,o=(e,t)=>jt(je(e.root),je(t.root)),c=(e,t)=>Number(t.root.id===a)-Number(e.root.id===a),d=new Map;for(let e of i.values()){let t=et(e.root),n=d.get(t);n||(n={key:t,name:eW(e.root.projectRoot??e.root.cwd),families:[]},d.set(t,n)),n.families.push(e)}let u=e=>Math.max(...e.families.map(e=>je(e.root))),p=e=>e.families.some(e=>e.root.id===a),h=[...d.values()].sort((e,t)=>Number(p(t))-Number(p(e))||jt(u(e),u(t))).map(e=>{let t=[];for(let r of[...e.families].sort(o).sort(c))for(let{info:e,summary:i}of(t.push({id:r.root.id,depth:0,info:r.root,summary:r.summary,current:r.root.id===n,placeholder:null===r.summary}),[...r.subagents].sort((e,t)=>jt(je(e.info),je(t.info)))))t.push({id:e.id,depth:1,info:e,summary:i,current:e.id===n,placeholder:!1});return{key:e.key,name:e.name,rows:t}});if(s.length>0){let e=null!==n&&!l&&s.some(e=>e.sessionId===n),t=(e,t)=>e<t?-1:+(e>t),r={key:"\0unlisted",name:null,rows:[...s].sort((e,r)=>Number(r.sessionId===n)-Number(e.sessionId===n)||t(wU(e.sessionId),wU(r.sessionId))||t(e.sessionId,r.sessionId)).map(e=>({id:e.sessionId,depth:0,info:null,summary:e,current:e.sessionId===n,placeholder:!1}))};e?h.unshift(r):h.push(r)}return h}(x.sessions,w,g):null,[x,w,g]),S=r?function(e){let{page:t,server:n,detail:r,t:i,titleOf:s}=e,l=t.at,a=[],o=(e,t,n)=>{a.push({id:e,tone:t,text:wX(n)})},c=n.failure;c?o("poll","timeout"===c.kind?"warning":"error",[i(wA[c.kind],{status:c.status??"?"}),wD(l-c.at,i)]):null!==t.pollInFlightSince&&l-t.pollInFlightSince>=2e3&&o("poll","warning",[i("debug.poll.inFlight",{time:wF(l-t.pollInFlightSince,i)})]),t.clientFailed&&o("reader","error",[i("debug.stream.readerFailed")]);let d=t.runningPoll?.last??null;d?.outcome==="error"&&o("runningPoll","warning",[i("debug.page.runningPoll"),i("debug.page.poll.error"),null!==d.httpStatus&&`HTTP ${d.httpStatus}`,wD(l-d.at,i)]);let u=t.sources.filter(e=>"open"===e.state).length;"http/1.1"===t.protocol&&u>=5&&o("pool",u>=6?"error":"warning",[i("debug.issue.pool",{count:u})]);let p=t.client,h=p?.connection??null,m=h?.sessionId??null;for(let e of t.sources)"connecting"===e.state&&0!==e.errors&&("agent"!==e.kind||null===m||e.label!==m)&&o("source","warning",[i(w$[e.kind]),w4(e,s),i("debug.page.source.connecting"),i("debug.page.sourceCounts",{opens:e.opens,errors:e.errors})]);if(h){let e=null!==h.retryDueAt&&i("debug.stream.retryDue",{time:wH(h.retryDueAt-l,i)}),t=h.lastError;t&&"connected"!==h.state&&!(h.lastClose&&h.lastClose.at>=t.at)?o("stream","error",[wz(t.reason,wE,i),t.message,wD(l-t.at,i),e]):"retrying"===h.state&&o("stream","warning",[i(wN.retrying),e]);let n=w8(h,l),r=n?w6(n.ageMs,n.staleAfterMs):"dim";n&&"dim"!==r&&o("streamSilent",r,[`${i("debug.stream.lastData")} ${wD(n.ageMs,i)}`])}let f=p?.pageId??null,g=null!==n.receivedAt?n.receivedAt-(n.roundTripMs??0):null;for(let e of(r&&f&&h&&null!==g&&"connected"===h.state&&h.sessionId===r.sessionId&&null!==h.connectedAt&&h.connectedAt<g&&!r.eventStreams.some(e=>e.holder===f)&&o("noServerStream","warning",[i("debug.issue.noServerStream")]),r?.eventStreams??[]))e.droppedEvents>0&&o("dropped","warning",[wQ(e.holder,f,i),i("debug.server.dropped",{count:e.droppedEvents})]);let x=p?.lease??null;if(x){let e=x.last;null!==x.inFlightSince&&l-x.inFlightSince>=2e3?o("lease","warning",[i("debug.section.lease"),i("debug.lease.inFlight",{time:wF(l-x.inFlightSince,i)})]):e?.outcome==="error"?o("lease","error",[i("debug.section.lease"),i(wT.error),null!==e.httpStatus&&`HTTP ${e.httpStatus}`,wD(l-e.at,i)]):e?.outcome==="unanswered"&&o("lease","warning",[i("debug.section.lease"),i(wT.unanswered),wD(l-e.at,i)])}let v=r?.wrapper??null;for(let e of(v&&!v.stale&&"failed"===v.extensions&&o("extensions","error",[i("debug.server.extensions"),i("debug.server.extensions.failed")]),r?.providers??[]))"error"===e.active&&o("provider","error",[e.name,i("debug.server.providerError")]);for(let e of r?.mcp?.servers??[])(e.hasError||"failed"===e.state||"conflict"===e.state)&&o("mcp","error",[`MCP ${e.name}`,wz(e.state,gu,i)]);return a.sort((e,t)=>Number("error"===t.tone)-Number("error"===e.tone))}({page:r,server:i,detail:b,t:p,titleOf:j}):[],C=null===r?{kind:"reading",tone:"dim",count:0}:r.visibility?.state==="hidden"?{kind:"hidden",tone:"dim",count:0}:S.length>0?{kind:"issues",tone:S.some(e=>"error"===e.tone)?"error":"warning",count:S.length}:null===i.receivedAt?{kind:"waiting",tone:"dim",count:0}:{kind:"ok",tone:"ok",count:0},N={t:p,now:m,clock:v,myHolder:y,titleOf:j};return(0,d.jsxs)("section",{ref:h,className:"debug-panel","aria-label":p("debug.panelLabel"),children:[(0,d.jsxs)("div",{className:"debug-panel-header",children:[(0,d.jsx)("span",{className:"debug-panel-heading",title:p("debug.readOnly"),children:p("debug.title")}),(0,d.jsx)(jg,{verdict:C,t:p}),(0,d.jsx)("button",{type:"button",className:"debug-panel-copy",onClick:c,title:p("debug.copyTitle"),children:p(o?"debug.copied":"debug.copyJson")})]}),null!==r&&(0,d.jsxs)("div",{className:"debug-panel-scroll",children:[S.length>0&&(0,d.jsx)(jx,{issues:S}),(0,d.jsxs)("div",{className:"debug-cols",children:[(0,d.jsx)(jy,{page:r,samples:s,reply:x,ctx:N}),(0,d.jsxs)("div",{className:"debug-col debug-col-server",children:[(0,d.jsx)(jM,{reply:x,ctx:N}),(0,d.jsx)(j$,{reply:x,ctx:N})]}),(0,d.jsx)("div",{className:"debug-col debug-col-sessions",children:(0,d.jsx)(jI,{reply:x,detail:b,groups:k,targetSessionId:g,sources:r.sources,ctx:N})})]})]}),(0,d.jsx)("style",{children:jH})]})}function js(e){let{kind:t,size:n=12}=e;return(0,d.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:["server"===t&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"3",y:"3",width:"18",height:"8",rx:"2"}),(0,d.jsx)("rect",{x:"3",y:"13",width:"18",height:"8",rx:"2"}),(0,d.jsx)("path",{d:"M7 7h.01M7 17h.01"})]}),"warning"===t&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"}),(0,d.jsx)("path",{d:"M12 9v4"}),(0,d.jsx)("path",{d:"M12 17h.01"})]}),"error"===t&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,d.jsx)("path",{d:"M15 9l-6 6M9 9l6 6"})]})]})}function jl(e,t){return["debug-badge",t,`is-${e.tone}`,e.filled&&"is-filled",e.dashed&&"is-dashed",e.faded&&"is-faded"].filter(Boolean).join(" ")}function ja(e){let{text:t,items:n,cap:r,label:i,plain:s=!1}=e;return 0===n.length?null:(0,d.jsxs)("span",{className:"debug-run",title:i,...s?{}:{role:"img","aria-label":i},children:[n.slice(0,r).map((e,n)=>(0,d.jsx)("span",{className:jl(e,void 0!==e.text?"is-name":void 0),title:e.title,children:e.text??t},n)),n.length>r&&(0,d.jsx)("span",{className:"debug-run-more",children:`+${n.length-r}`})]})}let jo={Chrome:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,d.jsx)("path",{d:"M21.17 8H12M3.95 6.06 8.54 14M10.88 21.94 15.46 14"})]}),Safari:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,d.jsx)("path",{d:"M16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88z"})]}),Firefox:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,d.jsx)("path",{d:"M12 17a3.5 3.5 0 0 0 3.5-3.5c0-2.5-2-3.5-2.5-6-1.5 1.5-1 3-2 3.5-.5-.5-1-1-1-2-1.5 1-1.5 2.5-1.5 4.5A3.5 3.5 0 0 0 12 17z"})]}),Edge:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("path",{d:"M21 12a9 9 0 1 0-4.5 7.8"}),(0,d.jsx)("path",{d:"M7 13.5c0-3 2.5-5 5.5-5 2.5 0 4.5 1.5 4.5 3.5 0 1.3-1 2-2.5 2H10"})]}),Opera:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,d.jsx)("ellipse",{cx:"12",cy:"12",rx:"4",ry:"7"})]}),macOS:(0,d.jsx)(jc,{}),iOS:(0,d.jsx)(jc,{}),Windows:(0,d.jsx)("path",{fill:"currentColor",stroke:"none",d:"M0 0h11.377v11.372H0zm12.623 0H24v11.372H12.623zM0 12.623h11.377V24H0zm12.623 0H24V24H12.623z"}),Android:(0,d.jsx)("path",{d:"M4.5 18a7.5 7.5 0 0 1 15 0zM8 12 6.5 9.5M16 12l1.5-2.5M9.5 15h.01M14.5 15h.01"}),Linux:(0,d.jsx)("path",{d:"m4 17 6-5-6-5M12 19h8"}),ChromeOS:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"12",rx:"2"}),(0,d.jsx)("path",{d:"M2 20h20"})]})};function jc(){return(0,d.jsx)("path",{fill:"currentColor",stroke:"none",d:"M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"})}function jd(e){let{client:t}=e,n=t?t.split(" \xb7 ").filter(e=>e in jo):[];return 0===n.length?null:(0,d.jsx)("span",{className:"debug-client","aria-hidden":"true",children:n.map(e=>(0,d.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.2,strokeLinecap:"round",strokeLinejoin:"round",children:jo[e]},e))})}function ju(e){let{tone:t,ring:n=!1}=e;return(0,d.jsx)("span",{className:`debug-dot is-${t}${n?" is-ring":""}`,"aria-hidden":"true"})}function jp(e){let{tone:t,children:n,title:r}=e;return(0,d.jsx)("span",{className:`debug-chip is-${t}`,title:r,children:n})}function jh(e){let{fraction:t,tone:n,width:r,height:i=4,notches:s,title:l,className:a}=e;return(0,d.jsxs)("span",{className:`debug-bar is-${n}${a?` ${a}`:""}`,style:{width:r,height:i},title:l,"aria-hidden":"true",children:[(0,d.jsx)("span",{className:"debug-bar-fill",style:{width:`${100*t}%`}}),s?.map(e=>(0,d.jsx)("span",{className:"debug-bar-notch",style:{left:`${100*e}%`}},e))]})}function jm(e){let{samples:t,label:n}=e,r=t.slice(-30);return(0,d.jsx)("span",{className:"debug-spark",role:"img","aria-label":n,title:n,children:(0,d.jsxs)("svg",{width:"120",height:"15",viewBox:"0 0 120 15","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"0",y:"14",width:"120",height:"1",style:{fill:"var(--border)"}}),r.map((e,t)=>{let n=e.failed?14:Math.max(1,Math.round(14*Math.min(1,Math.max(.08,Math.sqrt(wO(e.ms)/5e3)))));return(0,d.jsx)("rect",{className:`is-${e.tone}`,x:120-(r.length-t)*4+1,y:14-n,width:"3",height:n,fill:"currentColor"},t)})]})})}function jf(e){let{state:t,label:n}=e;return"awaiting"===t?(0,d.jsx)("span",{className:"debug-status",children:(0,d.jsx)("span",{className:"session-tree-awaiting",role:"img","aria-label":n,title:n})}):"running"===t?(0,d.jsx)("span",{className:"debug-status is-accent",title:n,children:(0,d.jsx)(ri,{size:12,label:n})}):(0,d.jsx)("span",{className:"debug-status",role:"img","aria-label":n,title:n,children:(0,d.jsx)("span",{className:`debug-status-ring is-${t}`})})}function jg(e){let{verdict:t,t:n}=e,r=({reading:()=>n("debug.reading"),hidden:()=>n("debug.poll.hidden"),issues:()=>n("debug.health.issues",{count:t.count}),waiting:()=>n("debug.poll.waiting"),ok:()=>n("debug.health.ok")})[t.kind]();return(0,d.jsxs)("span",{className:`debug-panel-status is-${"ok"===t.kind?"muted":t.tone}`,children:["issues"===t.kind&&(0,d.jsx)(js,{kind:"error"===t.tone?"error":"warning"}),"ok"===t.kind&&(0,d.jsx)(ju,{tone:"ok"}),("hidden"===t.kind||"waiting"===t.kind)&&(0,d.jsx)(ju,{tone:"dim",ring:!0}),(0,d.jsx)("span",{className:"debug-panel-status-text",children:r})]})}function jx(e){let{issues:t}=e;return(0,d.jsx)("ul",{className:"debug-issues",children:t.map((e,t)=>(0,d.jsxs)("li",{className:`debug-issue is-${e.tone}`,children:[(0,d.jsx)(js,{kind:e.tone}),(0,d.jsx)("span",{className:"debug-issue-text",children:e.text})]},`${e.id}:${t}`))})}function jv(e,t){let n=function(e){let t=e.filter(e=>!e.failed).map(e=>e.ms).sort((e,t)=>e-t);if(0===t.length)return{count:0,median:0,max:0};let n=Math.floor(t.length/2),r=t.length%2==1?t[n]:(t[n-1]+t[n])/2;return{count:t.length,median:r,max:t[t.length-1]}}(e);return 0===n.count?t("debug.notYet"):t("debug.spark.title",{count:n.count,median:wF(n.median,t),max:wF(n.max,t)})}function jb(e){let{samples:t,t:n}=e,r=t[t.length-1];return r?(0,d.jsx)("span",{className:`debug-value is-${r.tone}`,children:r.failed?"—":wF(r.ms,n)}):(0,d.jsx)("span",{className:"debug-value is-dim",children:"—"})}function jy(e){let{page:t,samples:n,reply:r,ctx:i}=e,{t:s}=i,l=function(e,t,n){let r=[...e].sort((e,t)=>e.createdAt-t.createdAt).map(e=>({id:e.id,kind:e.kind,label:e.label,chat:"agent"===e.kind&&null!==n&&e.label===n,connecting:"connecting"===e.state,opens:e.opens,errors:e.errors,createdAt:e.createdAt})),i="http/1.1"===t?6:null,s=r.length,l=r.filter(e=>!e.connecting).length,a={agent:0,"file-watch":0,terminal:0};for(let e of r)a[e.kind]=(a[e.kind]??0)+1;return{protocol:t,cap:i,slots:null===i?r:r.slice(0,i),mine:s,overflow:null===i?0:Math.max(0,s-i),kinds:a,tone:null===i?"dim":l>=i?"error":l>=i-1?"warning":"dim"}}(t.sources,t.protocol,t.client?.connection?.sessionId??null),a=t.runningPoll;return(0,d.jsxs)("div",{className:"debug-col debug-col-page",children:[(0,d.jsx)("div",{className:"debug-col-head",children:(0,d.jsx)("span",{className:"debug-section-title",children:s("debug.section.page")})}),(0,d.jsx)(jw,{pool:l,ctx:i}),(0,d.jsxs)("div",{className:"debug-measures",children:[(0,d.jsx)("span",{className:"debug-measure-name",children:(0,d.jsx)("span",{className:"debug-label",children:s("debug.page.debugPoll")})}),(0,d.jsx)(jm,{samples:n.poll,label:jv(n.poll,s)}),(0,d.jsx)(jb,{samples:n.poll,t:s}),(0,d.jsx)("span",{className:"debug-measure-name",children:(0,d.jsx)("span",{className:"debug-label",children:s("debug.page.runningPoll")})}),(0,d.jsx)(jm,{samples:n.running,label:wX([a&&s("debug.page.pollCounts",{count:a.count,failures:a.failures}),jv(n.running,s)])}),(0,d.jsx)(jb,{samples:n.running,t:s}),(0,d.jsx)(jC,{page:t,reply:r,ctx:i}),(0,d.jsx)(jE,{page:t,ctx:i})]})]})}function jw(e){let{pool:t,ctx:n}=e,{t:r,now:i,titleOf:s}=n,l=Object.keys(w$).filter(e=>t.kinds[e]>0).map(e=>`${r(w$[e])} ${t.kinds[e]}`),a=null!==t.cap?wX([`${r("debug.page.http1",{protocol:t.protocol??""})} \xb7 ${t.mine}/${t.cap}`,...l]):wX([r("debug.section.page"),...l,t.protocol??r("debug.unknown")]),o=null!==t.cap?Array.from({length:t.cap},(e,n)=>t.slots[n]??null):t.slots;return(0,d.jsxs)("div",{className:"debug-meter-row",children:[(0,d.jsxs)("span",{className:`debug-meter${null===t.cap?" is-inline":""}`,role:"img","aria-label":a,title:a,children:[o.map((e,t)=>e?(0,d.jsx)("span",{className:jl({tone:e.connecting?"warning":e.chat?"accent":"muted",filled:e.chat,dashed:e.connecting},"debug-slot"),title:wX([r(w$[e.kind]),w4(e,s),r(wI[e.connecting?"connecting":"open"]),r("debug.page.sourceCounts",{opens:e.opens,errors:e.errors}),wD(i-e.createdAt,r)]),children:"agent"===e.kind?"SSE":r(jj[e.kind])},e.id):(0,d.jsx)("span",{className:"debug-slot is-empty"},`empty:${t}`)),t.overflow>0&&(0,d.jsx)("span",{className:"debug-meter-overflow is-error",children:`+${t.overflow}`})]}),null===t.cap&&null!==t.protocol&&(0,d.jsx)(jp,{tone:"dim",children:t.protocol})]})}let jj={"file-watch":"debug.box.file",terminal:"debug.box.terminal"},jk={connected:{tone:"ok",ring:!1},connecting:{tone:"warning",ring:!0},retrying:{tone:"warning",ring:!1},idle:{tone:"dim",ring:!0}};function jS(e,t,n,r){let i=n.at,s=[null!==t.readyState&&r("debug.stream.readyState",{value:t.readyState}),null!==t.openedAt&&`${r("debug.stream.opened")} ${wD(i-t.openedAt,r)}`,null!==t.connectedAt&&`${r("debug.stream.connected")} ${wD(i-t.connectedAt,r)}`,`${r("debug.stream.opens")} ${r("debug.stream.opensRetries",{opens:t.opens,retries:t.retries})}`,null!==t.lastError&&`${r("debug.stream.lastError")} ${wX([wz(t.lastError.reason,wE,r),t.lastError.message,wD(i-t.lastError.at,r)])}`,null!==t.lastClose&&`${r("debug.stream.lastClose")} ${wX([t.lastClose.reason?wz(t.lastClose.reason,wP,r):"—",wD(i-t.lastClose.at,r)])}`,`${r("debug.stream.wanted")} ${r(e.wantsStream?"debug.yes":"debug.no")}`],l=n.visibility;return l&&l.hiddenCount>0&&s.push(wX([r("debug.page.hiddenCount",{count:l.hiddenCount}),null!==l.lastHiddenAt&&r("debug.page.lastHidden",{time:wD(i-l.lastHiddenAt,r)})])),e.released.count>0&&s.push(`${r("debug.stream.released")} ${wX([r("debug.times",{count:e.released.count}),null!==e.released.lastAt&&wD(i-e.released.lastAt,r)])}`),e.reattached.count>0&&s.push(`${r("debug.stream.reattached")} ${wX([r("debug.times",{count:e.reattached.count}),null!==e.reattached.lastAt&&wD(i-e.reattached.lastAt,r),e.reattached.lastReason&&r(wM[e.reattached.lastReason])])}`),s.filter(Boolean).join("\n")}function jC(e){let{page:t,reply:n,ctx:r}=e,{t:i,now:s}=r,l=t.client,a=l?.connection??null,o=(0,d.jsx)("span",{className:"debug-measure-name",title:l&&a?jS(l,a,t,i):void 0,children:(0,d.jsx)("span",{className:"debug-label",children:i("debug.section.stream")})});if(!l||!a)return(0,d.jsxs)(d.Fragment,{children:[o,(0,d.jsx)("span",{className:"debug-measure-empty",children:l?i("debug.stream.noConnection"):t.clientFailed?"—":i("debug.stream.noChat")})]});let c=w8(a,s),u=jk[a.state];return(0,d.jsxs)(d.Fragment,{children:[o,c?(0,d.jsx)(jN,{connection:a,freshness:c,heartbeatMs:n?.server.heartbeatMs??0,ctx:r}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{}),(0,d.jsx)("span",{className:"debug-value is-dim",children:"—"})]}),(0,d.jsxs)("span",{className:"debug-measure-sub",title:jS(l,a,t,i),children:[(0,d.jsx)(ju,{tone:u?.tone??"dim",ring:u?.ring??!0}),wX([i(wN[a.state]??"debug.unknown"),`${i("debug.stream.events")} ${a.events}`,a.retries>0&&`${i("debug.stream.opens")} ${i("debug.stream.opensRetries",{opens:a.opens,retries:a.retries})}`])]}),(l.released.active||null!==l.graceDueAt)&&(0,d.jsxs)("span",{className:"debug-measure-sub debug-chips",children:[l.released.active&&(0,d.jsx)(jp,{tone:"accent",children:i("debug.stream.close.released")}),null!==l.graceDueAt&&(0,d.jsx)(jp,{tone:"accent",children:`${i("debug.stream.grace")} ${wB(l.graceDueAt-s,i)}`})]})]})}function jN(e){let{connection:t,freshness:n,heartbeatMs:r,ctx:i}=e,{t:s,now:l}=i,{ageMs:a,staleAfterMs:o}=n,c=w6(a,o),u=[];if(r>0)for(let e=r;e<o&&u.length<12;e+=r)u.push(e/o);let p=wX([`${s("debug.stream.lastData")} ${wD(a,s)}`,null!==t.lastHeartbeatAt&&s("debug.stream.heartbeat",{time:wD(l-t.lastHeartbeatAt,s)}),s("debug.stream.watchdogArmed",{time:wF(o,s)})]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(jh,{fraction:w3(a,o)??0,tone:c,width:120,notches:u,title:p}),(0,d.jsx)("span",{className:`debug-value is-${c}`,title:p,children:s("debug.stream.dataAgo",{time:w_(a,s)})})]})}function jE(e){let{page:t,ctx:n}=e,{t:r,now:i}=n,s=t.client?.lease??null,l=t.client?.pageId??null,a=(0,d.jsx)("span",{className:"debug-measure-name",children:(0,d.jsx)("span",{className:"debug-label",children:r("debug.section.lease")})});if(!s||0===s.requests)return(0,d.jsxs)(d.Fragment,{children:[a,(0,d.jsx)("span",{className:"debug-measure-empty",children:s?r("debug.lease.noHolder"):t.clientFailed?"—":r("debug.stream.noChat")})]});let o=s.last,c=function(e,t,n){if(null===e||!(t>0))return null;let r=Math.max(0,n-e);return e+(Math.floor(r/t)+1)*t}(s.renewStartedAt,s.renewIntervalMs,i),u=null!==s.inFlightSince&&i-s.inFlightSince>=2e3,p=u||o?.outcome==="unanswered"?"warning":o?.outcome==="error"?"error":"dim",h=r("debug.lease.countsValue",{requests:s.requests,unanswered:s.unanswered,errors:s.errors}),m=wX([null!==c&&`${r("debug.lease.next")} ${wB(c-i,r)}`,r("debug.lease.every",{time:wF(s.renewIntervalMs,r)}),h,null!==l&&`${r("debug.holder.thisPage")} ${wU(l)}`]);return(0,d.jsxs)(d.Fragment,{children:[a,null===c?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{}),(0,d.jsx)("span",{className:"debug-value is-dim",children:"—"})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(jh,{fraction:u?1:1-(w3(c-i,s.renewIntervalMs)??1),tone:p,width:120,title:m}),(0,d.jsx)("span",{className:"debug-value is-muted",title:m,children:c-i>0?r("debug.lease.renewsIn",{time:w_(c-i,r,"ceil")}):r("debug.lease.renewing")})]}),(0,d.jsx)("span",{className:"debug-measure-sub",children:`${r("debug.lease.last")} ${o?wX([r(wT[o.outcome]??"debug.unknown"),wF(o.durationMs,r),"error"===o.outcome&&null!==o.httpStatus&&`HTTP ${o.httpStatus}`,r("debug.time.ago",{time:w_(i-o.at,r)})]):r("debug.notYet")}`}),(s.unanswered>0||s.errors>0)&&(0,d.jsx)("span",{className:"debug-measure-sub",children:h})]})}function jM(e){let{reply:t,ctx:n}=e,{t:r,clock:i}=n,s=(0,d.jsx)("span",{className:"debug-section-title",children:r("debug.section.server")});if(!t||!i)return(0,d.jsxs)("div",{className:"debug-col-head debug-server-head",children:[s,(0,d.jsx)("span",{children:r("debug.poll.waiting")})]});let l=t.server,a=r("debug.global.wrappersValue",{...l.wrappers}),o=`${r("debug.global.timers")}: ${r("debug.global.timersValue",{idle:l.idleTimeoutMs>0?wF(l.idleTimeoutMs,r):r("debug.server.idleDisabled"),heartbeat:wF(l.heartbeatMs,r)})}
|
|
279
|
+
${a}`,c=l.terminals,u=wX([`${r("debug.global.terminals")}: ${r("debug.global.terminalsValue",{count:c.count,listeners:c.listeners,detached:c.detached,exited:c.exited})}`,null!==c.nextCleanupAt&&r("debug.global.cleanup",{time:wH(i.remaining(c.nextCleanupAt),r)})]),p=Array.from({length:c.count},(e,t)=>t<c.detached?{tone:"dim",dashed:!0,title:u}:t<c.detached+c.exited?{tone:"muted",faded:!0,title:u}:{tone:"muted",title:u}),h=`${r("debug.global.fileWatches")}: ${l.fileWatches}`,m=l.wrappers.starting;return(0,d.jsxs)("div",{className:"debug-col-head debug-server-head",children:[s,(0,d.jsxs)("span",{className:"debug-server-item",title:o,children:[(0,d.jsx)(js,{kind:"server"}),(0,d.jsx)("span",{children:`${r("debug.global.uptime")} ${wF(i.age(l.startedAt),r)}`})]}),m>0&&(0,d.jsxs)("span",{className:"debug-run",role:"img","aria-label":a,title:a,children:[Array.from({length:Math.min(m,4)},(e,t)=>(0,d.jsx)("span",{className:"debug-status",children:(0,d.jsx)("span",{className:"debug-status-ring is-starting"})},t)),m>4&&(0,d.jsx)("span",{className:"debug-run-more",children:`+${m-4}`})]}),(0,d.jsx)(ja,{text:r("debug.box.file"),items:Array.from({length:l.fileWatches},()=>({tone:"muted",title:h})),cap:4,label:h}),(0,d.jsx)(ja,{text:r("debug.box.terminal"),items:p,cap:4,label:u})]})}function j$(e){let{reply:t,ctx:n}=e,{t:r,myHolder:i}=n;if(!t)return null;let{pages:s,sseTotal:l}=t.server;if(0===l&&0===s.length)return null;let a=w0(s,i);return(0,d.jsxs)("div",{className:"debug-pages",children:[(0,d.jsxs)("div",{className:"debug-page-row debug-list-head",children:[(0,d.jsx)("span",{className:"debug-pages-title",children:`${r("debug.pages.title")} ${a.length}`}),(0,d.jsx)("span",{className:"debug-page-count",children:`SSE ${r("debug.global.streamTotal",{count:l})}`})]}),a.map((e,t)=>{let n=null!==e.holder&&e.holder===i,s=wQ(e.holder,i,r),l=e.agent+e.terminal+e.fileWatch,a=wX([e.agent>0&&`${r(w$.agent)} ${e.agent}`,e.terminal>0&&`${r(w$.terminal)} ${e.terminal}`,e.fileWatch>0&&`${r(w$["file-watch"])} ${e.fileWatch}`]);return(0,d.jsxs)("div",{className:`debug-page-row${n?" is-current":""}`,title:wX([s,e.client,e.address,`SSE ${l}`,a]),children:[(0,d.jsx)("span",{className:"debug-page-icons",children:(0,d.jsx)(jd,{client:e.client})}),(0,d.jsx)("span",{className:`debug-page-client${e.client?"":" is-dim"}`,children:e.client??r("debug.pages.unknownClient")}),(0,d.jsx)("span",{className:"debug-page-address",children:e.address??"—"}),(0,d.jsx)("span",{className:"debug-page-holder",children:n?r("debug.holder.thisPage"):null!==e.holder?wU(e.holder):r("debug.holder.none")}),(0,d.jsx)("span",{className:"debug-page-count",children:l})]},`${e.holder??""}:${t}`)})]})}function jI(e){let{reply:t,detail:n,groups:r,targetSessionId:i,sources:s,ctx:l}=e,{t:a,clock:o}=l;if(!t||!o||!r)return(0,d.jsx)("div",{className:"debug-empty",children:a("debug.poll.waiting")});let c=null!==n&&r.some(e=>e.rows.some(e=>e.current&&e.id===n.sessionId)),p=null;return i?n?c||(p=(0,d.jsx)(jR,{detail:n,clock:o,ctx:l})):p=(0,d.jsx)("div",{className:"debug-empty",children:a("debug.poll.waiting")}):p=(0,d.jsx)("div",{className:"debug-empty",children:a("debug.server.noSession")}),(0,d.jsxs)("div",{className:"debug-list",children:[p,0===r.length&&!(n&&!c)&&(0,d.jsx)("div",{className:"debug-empty",children:a("debug.none")}),r.length>0&&(0,d.jsxs)("div",{className:"debug-row debug-list-head","aria-hidden":"true",children:[(0,d.jsx)("span",{}),(0,d.jsx)("span",{children:a("debug.sessions.head.session")}),(0,d.jsx)("span",{className:"debug-list-head-holders",children:a("debug.sessions.head.holders")}),(0,d.jsx)("span",{className:"debug-list-head-idle",children:a("debug.server.idle")})]}),r.map(e=>(0,d.jsxs)("div",{className:"debug-group",children:[(0,d.jsxs)("div",{className:"debug-group-head",children:[null!==e.name&&(0,d.jsx)(n3,{size:11}),(0,d.jsx)("span",{className:"debug-group-name",children:e.name??a("debug.sessions.unlisted")}),(0,d.jsx)("span",{className:"debug-group-count",children:e.rows.filter(e=>null!==e.summary).length})]}),e.rows.map(e=>{let r=e.current&&n?.sessionId===e.id?n:null;return(0,d.jsxs)(u.Fragment,{children:[(0,d.jsx)(j_,{row:e,sources:s,idleTimeoutMs:t.server.idleTimeoutMs,clock:o,ctx:l,current:r?function(e,t,n){let{t:r}=n,i=e=>wD(t.age(e),r),s=e.wrapper?.idle??null,l=e.lifecycle;return{badges:(0,d.jsx)(jP,{detail:e,clock:t,ctx:n}),idleTitle:s&&null!==s.nextCheckAt?wX([`${r("debug.server.idle")} ${wF(t.remaining(s.nextCheckAt),r)}`,s.timeoutMs>0&&r("debug.server.idleTimeout",{time:wF(s.timeoutMs,r)}),null!==s.lastResetAt&&r("debug.server.idleReset",{time:i(s.lastResetAt)}),r(s.forcedByStop?"debug.server.idleForced":"debug.server.idleHint")]):void 0,startsTitle:l&&l.starts>1?jT(l,i,r):void 0}}(r,o,l):void 0}),r&&(0,d.jsx)(jA,{detail:r,clock:o,ctx:l})]},e.id)})]},e.key))]})}function jT(e,t,n){return wX([n("debug.overlay.starts",{count:e.starts}),n("debug.server.lastStart",{time:t(e.lastStartedAt)}),null!==e.lastClosedAt&&n("debug.server.lastClosed",{time:t(e.lastClosedAt)})])}function jR(e){var t;let n,{detail:r,clock:i,ctx:s}=e,{t:l,titleOf:a}=s,o=a(r.sessionId)??wU(r.sessionId),c=(n=(t=r).wrapper)?w2({awaitingInput:n.awaitingInput,running:n.run.running,state:n.state}):t.starting?"starting":"none";return(0,d.jsxs)("div",{className:"debug-group",children:[(0,d.jsxs)("div",{className:"debug-row is-current has-detail is-placeholder",title:l("debug.sessions.current"),children:[(0,d.jsx)("span",{className:"debug-row-status",children:(0,d.jsx)(jf,{state:c,label:l(w1[c])})}),(0,d.jsx)("span",{className:"debug-row-title",children:(0,d.jsx)("span",{className:"debug-row-name",children:o})})]}),(0,d.jsx)(jA,{detail:r,clock:i,ctx:s,unlisted:!0})]})}function jA(e){let{detail:t,clock:n,ctx:r,unlisted:i=!1}=e,{t:s,titleOf:l}=r,a=t.wrapper,o=t.lifecycle,c=e=>wD(n.age(e),s),u=null!==a&&!a.stale,p=a?.state==="closing"?null!==a.closingAt?s("debug.server.closingSince",{time:c(a.closingAt)}):s("debug.state.closing"):null,h=a&&wX([null!=a.startedAt&&`${s("debug.server.started")} ${c(a.startedAt)}`,u&&a.lastEvent&&`${s("debug.server.lastEvent")} ${a.lastEvent.type} ${c(a.lastEvent.at)}`,u&&a.lastCommand&&`${s("debug.server.lastCommand")} ${a.lastCommand.type} ${c(a.lastCommand.at)}`]);return(0,d.jsxs)("div",{className:"debug-detail",children:[(0,d.jsxs)("div",{className:"debug-detail-line",children:[null!==l(t.sessionId)&&(0,d.jsx)("span",{className:"debug-detail-id",children:wU(t.sessionId)}),!a&&(0,d.jsx)("span",{className:"debug-note",children:s(t.starting?"debug.server.starting":"debug.server.noWrapper")}),i&&o&&o.starts>1&&(0,d.jsx)("span",{className:"debug-starts",title:jT(o,c,s),children:`↻${o.starts}`}),p&&(0,d.jsx)(jp,{tone:"warning",children:p}),a?.chatOnly&&(0,d.jsx)(jp,{tone:"dim",children:s("debug.server.chatOnly")}),a?.subagent&&(0,d.jsx)(jp,{tone:"dim",children:s("debug.server.subagent")}),a?.stale&&(0,d.jsx)(jp,{tone:"warning",children:s("debug.server.stale")}),(0,d.jsx)(jL,{detail:t,t:s}),u&&(0,d.jsx)(jz,{detail:t,t:s}),h&&(0,d.jsx)("span",{className:"debug-line",children:h})]}),u&&(0,d.jsx)(jF,{detail:t,clock:n,ctx:r}),u&&(0,d.jsx)(jD,{detail:t,clock:n,ctx:r})]})}function jL(e){let{detail:t,t:n}=e,r=t.wrapper;return null!==r&&!r.stale&&t.eventStreams.every(e=>null!==e.connectedAt)&&r.eventListeners!==t.eventStreams.length&&r?(0,d.jsx)(jp,{tone:"warning",children:`${n("debug.server.listeners")} ${r.eventListeners}`}):null}function jP(e){var t;let n,{detail:r,clock:i,ctx:s}=e,{t:l,myHolder:a}=s,o=e=>wD(i.age(e),l),c=w0([...r.eventStreams].sort((e,t)=>e.openedAt-t.openedAt),a),u=c.map(e=>{var t;let n,r=null===e.connectedAt;return{tone:r||e.droppedEvents>0?"warning":(t=e.holder,null===t?"dim":t===a?"accent":"muted"),filled:null!==e.holder&&e.holder===a,dashed:r,title:wX([wQ(e.holder,a,l),e.client,e.address,null!==e.connectedAt?l("debug.server.streamConnected",{time:o(e.connectedAt)}):l("debug.server.streamStarting"),null!==e.lastWriteAt&&l("debug.server.lastWrite",{time:o(e.lastWriteAt)}),e.droppedEvents>0&&l("debug.server.dropped",{count:e.droppedEvents}),e.queuedBytes>0&&l("debug.server.queued",{size:(n=wO(e.queuedBytes))<1024?`${Math.floor(n)} B`:n<1048576?`${(n/1024).toFixed(1)} KB`:`${(n/1048576).toFixed(1)} MB`})])}}),p=r.providers,h=null===p?[{tone:"dim",title:l("debug.server.providersUnknown")}]:p.map(e=>({tone:"error"===e.active?"error":e.active?"muted":"dim",faded:!1===e.active,text:e.name,title:wX([e.name,l("error"===e.active?"debug.server.providerError":e.active?"debug.server.providerActive":"debug.server.providerInactive"),e.byFile&&l("debug.server.byFile")])}));return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ja,{text:"SSE",items:u,cap:3,label:(t=c.map(e=>e.holder),n=t.filter(e=>null!==e&&e===a).length,`SSE: ${t.length} (${l("debug.holder.thisPage")} ${n}, ${l("debug.holder.otherPage")} ${t.length-n})`)}),(0,d.jsx)(ja,{text:l("debug.box.provider"),items:h,cap:1,label:`${l("debug.server.providers")}: ${null===p?l("debug.server.providersUnknown"):p.length}`})]})}function jz(e){let{detail:t,t:n}=e,r=t.wrapper;if(!r)return null;let i=r.run,s=[i.streaming&&n("debug.run.streaming"),i.promptRunning&&n("debug.run.prompt"),i.bashRunning&&n("debug.run.bash"),i.compacting&&n("debug.run.compacting"),i.queuedMessages>0&&n("debug.run.queued",{count:i.queuedMessages}),i.runningTools>0&&n("debug.run.tools",{count:i.runningTools}),i.mutatingCommands>0&&n("debug.run.mutating",{count:i.mutatingCommands}),i.replacement&&n("debug.run.replacement",{kind:i.replacement}),"binding"===r.extensions&&`${n("debug.server.extensions")} ${n("debug.server.extensions.binding")}`].filter(e=>!!e),l=[i.pendingPrompts>0&&n("debug.run.pending",{count:i.pendingPrompts}),i.retrying&&n("debug.run.retrying"),i.waitingForMcp&&n("debug.run.waitingForMcp"),r.awaitingInput&&r.pendingUiRequests>0&&n("debug.server.uiRequests",{count:r.pendingUiRequests}),r.awaitingInput&&r.customUis>0&&n("debug.server.customUis",{count:r.customUis})].filter(e=>!!e);return(0,d.jsxs)(d.Fragment,{children:[s.map(e=>(0,d.jsx)(jp,{tone:"dim",children:e},e)),l.map(e=>(0,d.jsx)(jp,{tone:"warning",children:e},e))]})}let jO={completed:"ok",failed:"error",aborted:"warning",interrupted:"warning"};function jW(e){let{status:t}=e;if("running"===t||"starting"===t)return(0,d.jsx)("span",{className:"debug-run-icon is-accent",children:(0,d.jsx)(ri,{size:12})});let n=jO[t];return n?(0,d.jsx)("span",{className:`debug-run-icon is-${n}`,children:(0,d.jsx)(wc,{status:t})}):(0,d.jsx)("span",{className:"debug-run-icon",children:(0,d.jsx)("span",{className:"debug-status-ring is-alive"})})}function jF(e){let{detail:t,clock:n,ctx:r}=e,{t:i,titleOf:s}=r,l=t.subagents;if(!l.active&&0===l.runs.length&&0===l.notifications.length)return null;let a=e=>wD(n.age(e),i);return(0,d.jsxs)("div",{className:"debug-block",children:[(0,d.jsxs)("div",{className:"debug-subhead",children:[(0,d.jsx)("span",{children:i("debug.server.subagents")}),l.active&&(0,d.jsx)(jp,{tone:"accent",children:i("debug.server.subagentsActive")})]}),l.runs.map((e,t)=>(0,d.jsxs)("div",{className:"debug-run-line",children:[(0,d.jsx)(jW,{status:e.status}),(0,d.jsx)("span",{className:"debug-run-name",children:s(e.sessionId)??e.profile??wU(e.sessionId)}),(0,d.jsx)("span",{className:"debug-line",children:wX([wz(e.status,wL,i),e.background&&i("debug.server.background"),e.resumed&&i("debug.server.resumed"),null!==e.dispatchedAt&&a(e.dispatchedAt)])}),e.abortRequested&&(0,d.jsx)(jp,{tone:"warning",children:i("debug.server.abortRequested")}),e.mcpWaiting&&(0,d.jsx)(jp,{tone:"warning",children:i("debug.run.waitingForMcp")})]},`${e.sessionId}:${t}`)),l.notifications.map((e,t)=>(0,d.jsx)("div",{className:"debug-line is-warning",children:wX([i("debug.server.notifying",{parent:wU(e.parentSessionId)}),null!==e.since&&a(e.since)])},`${e.sessionId}:${t}`))]})}function jD(e){let{detail:t,clock:n,ctx:r}=e,{t:i}=r,s=t.mcp;if(!s||0===s.servers.length&&0===s.problems)return null;let l=null!==s.idleReleaseAt&&s.idleMs>0?n.remaining(s.idleReleaseAt):null;return(0,d.jsxs)("div",{className:"debug-block",children:[(0,d.jsxs)("div",{className:"debug-pills",children:[(0,d.jsx)("span",{className:`debug-subhead${s.active?"":" is-dim"}`,children:"MCP"}),s.servers.map((e,t)=>{let{tone:n,filled:r}=e.hasError||"failed"===e.state||"conflict"===e.state?{tone:"error",filled:!0}:e.released?{tone:"dim",filled:!1}:"connected"===e.state?{tone:"ok",filled:!0}:"connecting"===e.state?{tone:"warning",filled:!1}:"needs-auth"===e.state||"not-trusted"===e.state||"disconnected"===e.state?{tone:"warning",filled:!0}:{tone:"muted",filled:!1},s=wz(e.state,gu,i),l=wX([`${e.name} (${e.scope})`,s,e.released&&i("debug.server.mcpReleased"),e.hasError&&i("debug.server.mcpError")]),a="connected"!==e.state?s:e.hasError?i("debug.server.mcpError"):null;return(0,d.jsxs)("span",{className:"debug-pill",role:"img","aria-label":l,title:l,children:[(0,d.jsx)(ju,{tone:n,ring:!r}),(0,d.jsx)("span",{className:e.released?"is-dim":void 0,children:e.name}),a&&(0,d.jsx)("span",{className:"debug-pill-state",children:`\xb7 ${a}`})]},`${e.scope}:${e.name}:${t}`)}),s.problems>0&&(0,d.jsx)(jp,{tone:"warning",children:i("debug.server.mcpProblems",{count:s.problems})}),s.disposed&&(0,d.jsx)(jp,{tone:"dim",children:i("debug.server.mcpDisposed")})]}),null!==l&&(0,d.jsxs)("div",{className:"debug-idle-row",children:[(0,d.jsx)(jh,{fraction:w3(l,s.idleMs)??0,tone:"dim",width:80}),(0,d.jsx)("span",{className:"debug-value is-muted",children:i("debug.server.mcpRelease",{time:wH(l,i)})})]})]})}function j_(e){var t;let n,r,{row:i,sources:s,idleTimeoutMs:l,clock:a,ctx:o,current:c}=e,{t:u}=o,p=i.summary,h=i.info?io(i.info):wU(i.id),m=p&&null!==p.nextIdleCheckAt?a.remaining(p.nextIdleCheckAt):null,f=p?w2(p):null,g=["debug-row",1===i.depth&&"is-sub",i.current&&"is-current",c&&"has-detail",i.placeholder&&"is-placeholder"].filter(Boolean).join(" ");return(0,d.jsxs)("div",{className:g,title:wX([i.current&&u("debug.sessions.current"),p?(n=[p.subagent?u("debug.overlay.subagentId",{id:wU(p.sessionId)}):wU(p.sessionId),u(wR[p.state]??wR.none)],p.running&&n.push(u("debug.overlay.running")),p.awaitingInput&&n.push(u("debug.overlay.awaiting")),p.eventStreams>0&&n.push(u("debug.overlay.streams",{count:p.eventStreams})),p.providers>0&&n.push(u("debug.overlay.providers",{count:p.providers})),null!==m&&n.push(u(p.forcedByStop?"debug.overlay.closesIn":"debug.overlay.idle",{time:(r=wO(m))<6e4?u("debug.duration.seconds",{count:Math.floor(r/1e3)}):r<36e5?u("debug.duration.minutes",{count:Math.floor(r/6e4)}):r<864e5?u("debug.duration.hours",{count:Math.floor(r/36e5)}):u("debug.duration.days",{count:Math.floor(r/864e5)})})),p.starts>1&&n.push(u("debug.overlay.starts",{count:p.starts})),n.join(" \xb7 ")):h]),children:[(0,d.jsx)("span",{className:"debug-row-status",children:f&&(0,d.jsx)(jf,{state:f,label:u(w1[f])})}),(0,d.jsxs)("span",{className:"debug-row-title",children:[1===i.depth&&(0,d.jsx)("span",{className:"debug-row-branch","aria-hidden":"true"}),(0,d.jsx)("span",{className:"debug-row-name",children:h}),p&&p.starts>1&&(0,d.jsx)("span",{className:"debug-row-starts",title:c?.startsTitle,children:`↻${p.starts}`})]}),p&&(0,d.jsx)(jB,{summary:p,mine:(t=i.id,s.filter(e=>"agent"===e.kind&&e.label===t).length),remaining:m,idleTimeoutMs:l,t:u,badges:c?.badges,idleTitle:c?.idleTitle})]})}function jB(e){let{summary:t,mine:n,remaining:r,idleTimeoutMs:i,t:s,badges:l,idleTitle:a}=e,o=s("debug.overlay.streams",{count:t.eventStreams}),c=Math.min(t.eventStreams,n),u=Array.from({length:t.eventStreams},(e,t)=>t<c?{tone:"accent",filled:!0,title:o}:{tone:"muted",title:o}),p=s("debug.overlay.providers",{count:t.providers}),h=Array.from({length:t.providers},()=>({tone:"muted",title:p})),m=null!==r&&(i>0||t.forcedByStop),f=t.forcedByStop?"warning":"dim",g=null!==r?s("debug.overlay.closesIn",{time:w_(r,s)}):void 0;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"debug-row-badges",children:l??(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ja,{text:"SSE",items:u,cap:3,label:o}),(0,d.jsx)(ja,{text:s("debug.box.provider"),items:h,cap:1,label:p})]})}),(0,d.jsx)("span",{className:`debug-row-idle is-${f}`,title:a,children:m&&null!==r&&(0,d.jsxs)(d.Fragment,{children:[i>0&&(0,d.jsx)(jh,{fraction:w3(r,i)??0,tone:f,width:36,height:3,className:"debug-row-idle-bar"}),t.forcedByStop&&(0,d.jsx)("span",{className:"debug-row-forced",role:"img","aria-label":g,title:g}),(0,d.jsx)("span",{className:"debug-row-idle-text",children:w_(r,s)})]})})]})}let jH=`
|
|
280
|
+
.debug-panel {
|
|
281
|
+
--dbg-ok: #16a34a;
|
|
282
|
+
--dbg-warn: #d97706;
|
|
283
|
+
--dbg-err: #ef4444;
|
|
284
|
+
container-type: inline-size;
|
|
285
|
+
container-name: debug-panel;
|
|
286
|
+
display: flex;
|
|
287
|
+
max-height: min(720px, 80dvh);
|
|
288
|
+
flex-direction: column;
|
|
289
|
+
background: var(--bg-panel);
|
|
290
|
+
border-bottom: 1px solid var(--border);
|
|
291
|
+
box-shadow: 0 10px 28px rgba(0,0,0,0.10);
|
|
292
|
+
color: var(--text);
|
|
293
|
+
}
|
|
294
|
+
.debug-panel .is-ok { color: var(--dbg-ok); }
|
|
295
|
+
.debug-panel .is-warning { color: var(--dbg-warn); }
|
|
296
|
+
.debug-panel .is-error { color: var(--dbg-err); }
|
|
297
|
+
.debug-panel .is-accent { color: var(--accent); }
|
|
298
|
+
.debug-panel .is-muted { color: var(--text-muted); }
|
|
299
|
+
.debug-panel .is-dim { color: var(--text-dim); }
|
|
300
|
+
.debug-panel-header {
|
|
301
|
+
display: flex;
|
|
302
|
+
flex-shrink: 0;
|
|
303
|
+
align-items: center;
|
|
304
|
+
gap: 12px;
|
|
305
|
+
min-width: 0;
|
|
306
|
+
padding: 8px 16px;
|
|
307
|
+
border-bottom: 1px solid var(--border);
|
|
308
|
+
font-size: 12px;
|
|
309
|
+
}
|
|
310
|
+
.debug-panel-heading {
|
|
311
|
+
flex-shrink: 0;
|
|
312
|
+
color: var(--text);
|
|
313
|
+
cursor: help;
|
|
314
|
+
font-weight: 700;
|
|
315
|
+
}
|
|
316
|
+
.debug-panel-status {
|
|
317
|
+
display: inline-flex;
|
|
318
|
+
min-width: 0;
|
|
319
|
+
align-items: center;
|
|
320
|
+
gap: 6px;
|
|
321
|
+
font-variant-numeric: tabular-nums;
|
|
322
|
+
}
|
|
323
|
+
.debug-panel-status svg {
|
|
324
|
+
flex-shrink: 0;
|
|
325
|
+
}
|
|
326
|
+
.debug-panel-status-text {
|
|
327
|
+
min-width: 0;
|
|
328
|
+
overflow: hidden;
|
|
329
|
+
text-overflow: ellipsis;
|
|
330
|
+
white-space: nowrap;
|
|
331
|
+
}
|
|
332
|
+
.debug-panel-copy {
|
|
333
|
+
flex-shrink: 0;
|
|
334
|
+
margin-left: auto;
|
|
335
|
+
padding: 2px 8px;
|
|
336
|
+
border: 1px solid var(--border);
|
|
337
|
+
border-radius: 4px;
|
|
338
|
+
background: transparent;
|
|
339
|
+
color: var(--text-muted);
|
|
340
|
+
cursor: pointer;
|
|
341
|
+
font-size: 11px;
|
|
342
|
+
}
|
|
343
|
+
.debug-panel-copy:hover {
|
|
344
|
+
background: var(--bg-hover);
|
|
345
|
+
color: var(--text);
|
|
346
|
+
}
|
|
347
|
+
.debug-panel-scroll {
|
|
348
|
+
display: flex;
|
|
349
|
+
min-height: 0;
|
|
350
|
+
flex: 1;
|
|
351
|
+
flex-direction: column;
|
|
352
|
+
gap: 12px;
|
|
353
|
+
overflow: auto;
|
|
354
|
+
padding: 10px 16px 12px;
|
|
355
|
+
font-size: 12px;
|
|
356
|
+
line-height: 1.5;
|
|
357
|
+
}
|
|
358
|
+
.debug-section-title {
|
|
359
|
+
color: var(--text);
|
|
360
|
+
font-size: 11px;
|
|
361
|
+
font-weight: 700;
|
|
362
|
+
}
|
|
363
|
+
.debug-empty,
|
|
364
|
+
.debug-note {
|
|
365
|
+
color: var(--text-dim);
|
|
366
|
+
font-size: 12px;
|
|
367
|
+
}
|
|
368
|
+
.debug-label {
|
|
369
|
+
color: var(--text-dim);
|
|
370
|
+
font-size: 11px;
|
|
371
|
+
white-space: nowrap;
|
|
372
|
+
}
|
|
373
|
+
.debug-value {
|
|
374
|
+
font-family: var(--font-mono);
|
|
375
|
+
font-size: 11px;
|
|
376
|
+
font-variant-numeric: tabular-nums;
|
|
377
|
+
white-space: nowrap;
|
|
378
|
+
}
|
|
379
|
+
.debug-line {
|
|
380
|
+
color: var(--text-dim);
|
|
381
|
+
font-family: var(--font-mono);
|
|
382
|
+
font-size: 11px;
|
|
383
|
+
font-variant-numeric: tabular-nums;
|
|
384
|
+
overflow-wrap: anywhere;
|
|
385
|
+
}
|
|
386
|
+
.debug-panel .debug-line.is-warning {
|
|
387
|
+
color: var(--dbg-warn);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
.debug-issues {
|
|
391
|
+
display: flex;
|
|
392
|
+
flex-direction: column;
|
|
393
|
+
gap: 4px;
|
|
394
|
+
margin: 0;
|
|
395
|
+
padding: 0;
|
|
396
|
+
list-style: none;
|
|
397
|
+
}
|
|
398
|
+
.debug-issue {
|
|
399
|
+
display: flex;
|
|
400
|
+
align-items: flex-start;
|
|
401
|
+
gap: 6px;
|
|
402
|
+
padding: 4px 8px;
|
|
403
|
+
border-left: 2px solid currentColor;
|
|
404
|
+
border-radius: 4px;
|
|
405
|
+
background: color-mix(in srgb, currentColor 8%, var(--bg-panel));
|
|
406
|
+
}
|
|
407
|
+
.debug-issue > svg {
|
|
408
|
+
flex-shrink: 0;
|
|
409
|
+
margin-top: 3px;
|
|
410
|
+
}
|
|
411
|
+
.debug-issue-text {
|
|
412
|
+
min-width: 0;
|
|
413
|
+
color: var(--text);
|
|
414
|
+
font-size: 12px;
|
|
415
|
+
overflow-wrap: anywhere;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/* Three columns when the panel is wide: the page's as wide as its table, the server's and the
|
|
419
|
+
sessions' each capped, so names never stretch and push the badges to the far edge. */
|
|
420
|
+
.debug-cols {
|
|
421
|
+
display: grid;
|
|
422
|
+
grid-template-areas: "page server sessions";
|
|
423
|
+
grid-template-columns: minmax(320px, max-content) minmax(340px, 480px) minmax(360px, 560px);
|
|
424
|
+
gap: 0;
|
|
425
|
+
}
|
|
426
|
+
.debug-col {
|
|
427
|
+
display: flex;
|
|
428
|
+
min-width: 0;
|
|
429
|
+
flex-direction: column;
|
|
430
|
+
gap: 8px;
|
|
431
|
+
}
|
|
432
|
+
.debug-col-page {
|
|
433
|
+
grid-area: page;
|
|
434
|
+
}
|
|
435
|
+
.debug-col-server {
|
|
436
|
+
grid-area: server;
|
|
437
|
+
}
|
|
438
|
+
.debug-col-sessions {
|
|
439
|
+
grid-area: sessions;
|
|
440
|
+
}
|
|
441
|
+
.debug-col-server,
|
|
442
|
+
.debug-col-sessions {
|
|
443
|
+
margin-left: 20px;
|
|
444
|
+
padding-left: 20px;
|
|
445
|
+
border-left: 1px solid var(--border);
|
|
446
|
+
}
|
|
447
|
+
.debug-list,
|
|
448
|
+
.debug-block {
|
|
449
|
+
display: flex;
|
|
450
|
+
min-width: 0;
|
|
451
|
+
flex-direction: column;
|
|
452
|
+
gap: 6px;
|
|
453
|
+
}
|
|
454
|
+
.debug-block {
|
|
455
|
+
gap: 4px;
|
|
456
|
+
}
|
|
457
|
+
.debug-col-head {
|
|
458
|
+
display: flex;
|
|
459
|
+
min-height: 18px;
|
|
460
|
+
align-items: center;
|
|
461
|
+
gap: 8px;
|
|
462
|
+
}
|
|
463
|
+
/* Name, scale, value; a measure's details span the row below it. */
|
|
464
|
+
/* As wide as the column (the details get the room), never so wide a value drifts off its bar. */
|
|
465
|
+
.debug-measures {
|
|
466
|
+
display: grid;
|
|
467
|
+
max-width: 400px;
|
|
468
|
+
grid-template-columns: max-content minmax(max-content, 1fr) max-content;
|
|
469
|
+
align-items: center;
|
|
470
|
+
gap: 4px 10px;
|
|
471
|
+
}
|
|
472
|
+
/* Numbers line up on the right, as the count in the column's head does. */
|
|
473
|
+
.debug-measures > .debug-value {
|
|
474
|
+
justify-self: end;
|
|
475
|
+
text-align: right;
|
|
476
|
+
}
|
|
477
|
+
.debug-measure-name {
|
|
478
|
+
display: inline-flex;
|
|
479
|
+
align-items: center;
|
|
480
|
+
gap: 6px;
|
|
481
|
+
}
|
|
482
|
+
.debug-measure-name[title] {
|
|
483
|
+
cursor: help;
|
|
484
|
+
}
|
|
485
|
+
/* Wrapped to the table's width rather than widening it (a percentage min-width adds nothing to
|
|
486
|
+
the columns' sizes). */
|
|
487
|
+
.debug-measure-sub,
|
|
488
|
+
.debug-measure-empty {
|
|
489
|
+
grid-column: 2 / -1;
|
|
490
|
+
width: 0;
|
|
491
|
+
min-width: 100%;
|
|
492
|
+
color: var(--text-dim);
|
|
493
|
+
font-family: var(--font-mono);
|
|
494
|
+
font-size: 11px;
|
|
495
|
+
font-variant-numeric: tabular-nums;
|
|
496
|
+
overflow-wrap: anywhere;
|
|
497
|
+
}
|
|
498
|
+
.debug-measure-sub {
|
|
499
|
+
margin-top: -4px;
|
|
500
|
+
}
|
|
501
|
+
.debug-measure-sub > .debug-dot {
|
|
502
|
+
margin-right: 6px;
|
|
503
|
+
vertical-align: 0;
|
|
504
|
+
}
|
|
505
|
+
.debug-measure-empty {
|
|
506
|
+
font-family: inherit;
|
|
507
|
+
font-size: 12px;
|
|
508
|
+
}
|
|
509
|
+
.debug-chips {
|
|
510
|
+
display: flex;
|
|
511
|
+
flex-wrap: wrap;
|
|
512
|
+
gap: 4px;
|
|
513
|
+
}
|
|
514
|
+
.debug-chip {
|
|
515
|
+
display: inline-flex;
|
|
516
|
+
align-items: center;
|
|
517
|
+
padding: 0 6px;
|
|
518
|
+
border: 1px solid color-mix(in srgb, currentColor 35%, transparent);
|
|
519
|
+
border-radius: 9px;
|
|
520
|
+
font-family: var(--font-mono);
|
|
521
|
+
font-size: 11px;
|
|
522
|
+
line-height: 16px;
|
|
523
|
+
white-space: nowrap;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/* A boxed word: "SSE", a provider's name, File, Term. Filled is this page's own. */
|
|
527
|
+
.debug-badge {
|
|
528
|
+
display: inline-flex;
|
|
529
|
+
height: 16px;
|
|
530
|
+
box-sizing: border-box;
|
|
531
|
+
flex-shrink: 0;
|
|
532
|
+
align-items: center;
|
|
533
|
+
padding: 0 4px;
|
|
534
|
+
border: 1px solid currentColor;
|
|
535
|
+
border-radius: 3px;
|
|
536
|
+
background-clip: padding-box;
|
|
537
|
+
font: 600 10px/14px var(--font-mono);
|
|
538
|
+
white-space: nowrap;
|
|
539
|
+
}
|
|
540
|
+
.debug-panel .debug-badge.is-filled {
|
|
541
|
+
border-color: var(--accent);
|
|
542
|
+
background-color: var(--accent);
|
|
543
|
+
color: var(--accent-contrast);
|
|
544
|
+
}
|
|
545
|
+
/* This page's, amber: a stream of its own still starting or dropping events. */
|
|
546
|
+
.debug-panel .debug-badge.is-filled.is-warning {
|
|
547
|
+
border-color: var(--dbg-warn);
|
|
548
|
+
background-color: var(--dbg-warn);
|
|
549
|
+
color: var(--bg-panel);
|
|
550
|
+
}
|
|
551
|
+
.debug-badge.is-dashed {
|
|
552
|
+
border-style: dashed;
|
|
553
|
+
}
|
|
554
|
+
.debug-badge.is-faded {
|
|
555
|
+
opacity: 0.45;
|
|
556
|
+
}
|
|
557
|
+
/* A provider's name: twelve characters, then an ellipsis (a block, so the ellipsis applies). */
|
|
558
|
+
.debug-badge.is-name {
|
|
559
|
+
display: inline-block;
|
|
560
|
+
max-width: calc(12ch + 10px);
|
|
561
|
+
overflow: hidden;
|
|
562
|
+
text-overflow: ellipsis;
|
|
563
|
+
}
|
|
564
|
+
/* A page's browser and system marks. */
|
|
565
|
+
.debug-client {
|
|
566
|
+
display: inline-flex;
|
|
567
|
+
align-items: center;
|
|
568
|
+
gap: 3px;
|
|
569
|
+
}
|
|
570
|
+
.debug-client svg {
|
|
571
|
+
display: block;
|
|
572
|
+
flex-shrink: 0;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/* The connected pages: marks, browser and system, address, page, its stream count. */
|
|
576
|
+
.debug-pages {
|
|
577
|
+
display: flex;
|
|
578
|
+
flex-direction: column;
|
|
579
|
+
}
|
|
580
|
+
.debug-page-row {
|
|
581
|
+
position: relative;
|
|
582
|
+
display: grid;
|
|
583
|
+
min-height: 22px;
|
|
584
|
+
grid-template-columns: 30px minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr) 32px;
|
|
585
|
+
align-items: center;
|
|
586
|
+
column-gap: 8px;
|
|
587
|
+
padding: 0 4px;
|
|
588
|
+
border-radius: 4px;
|
|
589
|
+
font-size: 11px;
|
|
590
|
+
}
|
|
591
|
+
.debug-page-row.debug-list-head {
|
|
592
|
+
min-height: 18px;
|
|
593
|
+
grid-template-columns: minmax(0, 1fr) auto;
|
|
594
|
+
color: var(--text-dim);
|
|
595
|
+
font-size: 10px;
|
|
596
|
+
}
|
|
597
|
+
.debug-page-row.is-current {
|
|
598
|
+
background: var(--bg-selected);
|
|
599
|
+
}
|
|
600
|
+
.debug-page-row.is-current::before {
|
|
601
|
+
content: "";
|
|
602
|
+
position: absolute;
|
|
603
|
+
top: 4px;
|
|
604
|
+
left: 0;
|
|
605
|
+
width: 3px;
|
|
606
|
+
height: 14px;
|
|
607
|
+
border-radius: 0 2px 2px 0;
|
|
608
|
+
background: var(--accent);
|
|
609
|
+
}
|
|
610
|
+
.debug-page-icons {
|
|
611
|
+
display: inline-flex;
|
|
612
|
+
padding-left: 4px;
|
|
613
|
+
color: var(--text-muted);
|
|
614
|
+
}
|
|
615
|
+
.debug-page-icons svg {
|
|
616
|
+
width: 12px;
|
|
617
|
+
height: 12px;
|
|
618
|
+
}
|
|
619
|
+
.debug-page-client,
|
|
620
|
+
.debug-page-address,
|
|
621
|
+
.debug-page-holder {
|
|
622
|
+
min-width: 0;
|
|
623
|
+
overflow: hidden;
|
|
624
|
+
text-overflow: ellipsis;
|
|
625
|
+
white-space: nowrap;
|
|
626
|
+
}
|
|
627
|
+
.debug-page-client {
|
|
628
|
+
color: var(--text);
|
|
629
|
+
}
|
|
630
|
+
.debug-page-address {
|
|
631
|
+
color: var(--text-muted);
|
|
632
|
+
font-family: var(--font-mono);
|
|
633
|
+
}
|
|
634
|
+
.debug-page-holder {
|
|
635
|
+
color: var(--text-dim);
|
|
636
|
+
}
|
|
637
|
+
.debug-page-count {
|
|
638
|
+
justify-self: end;
|
|
639
|
+
color: var(--text-muted);
|
|
640
|
+
font-family: var(--font-mono);
|
|
641
|
+
font-variant-numeric: tabular-nums;
|
|
642
|
+
white-space: nowrap;
|
|
643
|
+
}
|
|
644
|
+
.debug-list-head .debug-page-count {
|
|
645
|
+
color: var(--text-dim);
|
|
646
|
+
}
|
|
647
|
+
.debug-run {
|
|
648
|
+
display: inline-flex;
|
|
649
|
+
flex-wrap: wrap;
|
|
650
|
+
align-items: flex-start;
|
|
651
|
+
gap: 3px;
|
|
652
|
+
vertical-align: middle;
|
|
653
|
+
}
|
|
654
|
+
.debug-run-more {
|
|
655
|
+
color: var(--text-dim);
|
|
656
|
+
font-family: var(--font-mono);
|
|
657
|
+
font-size: 10px;
|
|
658
|
+
line-height: 16px;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
.debug-meter-row {
|
|
662
|
+
display: flex;
|
|
663
|
+
flex-wrap: wrap;
|
|
664
|
+
align-items: center;
|
|
665
|
+
gap: 8px;
|
|
666
|
+
}
|
|
667
|
+
.debug-meter {
|
|
668
|
+
display: flex;
|
|
669
|
+
min-height: 18px;
|
|
670
|
+
flex-wrap: wrap;
|
|
671
|
+
align-items: center;
|
|
672
|
+
gap: 3px;
|
|
673
|
+
}
|
|
674
|
+
.debug-slot {
|
|
675
|
+
display: inline-flex;
|
|
676
|
+
min-width: 32px;
|
|
677
|
+
height: 18px;
|
|
678
|
+
box-sizing: border-box;
|
|
679
|
+
align-items: center;
|
|
680
|
+
justify-content: center;
|
|
681
|
+
border-radius: 3px;
|
|
682
|
+
}
|
|
683
|
+
.debug-slot.is-empty {
|
|
684
|
+
border: 1px dotted var(--border);
|
|
685
|
+
}
|
|
686
|
+
.debug-meter.is-inline .debug-slot {
|
|
687
|
+
min-width: 0;
|
|
688
|
+
height: 16px;
|
|
689
|
+
}
|
|
690
|
+
.debug-meter-overflow {
|
|
691
|
+
margin-left: 2px;
|
|
692
|
+
font-family: var(--font-mono);
|
|
693
|
+
font-size: 11px;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
.debug-spark {
|
|
697
|
+
display: inline-flex;
|
|
698
|
+
width: 120px;
|
|
699
|
+
height: 15px;
|
|
700
|
+
}
|
|
701
|
+
.debug-spark svg {
|
|
702
|
+
display: block;
|
|
703
|
+
}
|
|
704
|
+
.debug-bar {
|
|
705
|
+
position: relative;
|
|
706
|
+
display: inline-block;
|
|
707
|
+
flex-shrink: 0;
|
|
708
|
+
overflow: hidden;
|
|
709
|
+
border-radius: 2px;
|
|
710
|
+
background: var(--border);
|
|
711
|
+
vertical-align: middle;
|
|
712
|
+
}
|
|
713
|
+
.debug-bar-fill {
|
|
714
|
+
position: absolute;
|
|
715
|
+
top: 0;
|
|
716
|
+
bottom: 0;
|
|
717
|
+
left: 0;
|
|
718
|
+
background: currentColor;
|
|
719
|
+
}
|
|
720
|
+
.debug-bar-notch {
|
|
721
|
+
position: absolute;
|
|
722
|
+
top: 0;
|
|
723
|
+
bottom: 0;
|
|
724
|
+
width: 1px;
|
|
725
|
+
background: var(--bg-panel);
|
|
726
|
+
}
|
|
727
|
+
.debug-dot {
|
|
728
|
+
display: inline-block;
|
|
729
|
+
width: 8px;
|
|
730
|
+
height: 8px;
|
|
731
|
+
flex-shrink: 0;
|
|
732
|
+
border-radius: 50%;
|
|
733
|
+
background: currentColor;
|
|
734
|
+
}
|
|
735
|
+
.debug-dot.is-ring {
|
|
736
|
+
background: transparent;
|
|
737
|
+
box-shadow: inset 0 0 0 1.5px currentColor;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
.debug-status {
|
|
741
|
+
display: inline-flex;
|
|
742
|
+
width: 14px;
|
|
743
|
+
height: 14px;
|
|
744
|
+
flex-shrink: 0;
|
|
745
|
+
align-items: center;
|
|
746
|
+
justify-content: center;
|
|
747
|
+
}
|
|
748
|
+
.debug-status-ring {
|
|
749
|
+
width: 7px;
|
|
750
|
+
height: 7px;
|
|
751
|
+
box-sizing: border-box;
|
|
752
|
+
border: 1.5px solid var(--text-dim);
|
|
753
|
+
border-radius: 50%;
|
|
754
|
+
}
|
|
755
|
+
.debug-status-ring.is-closing {
|
|
756
|
+
border-style: dashed;
|
|
757
|
+
border-color: var(--dbg-warn);
|
|
758
|
+
}
|
|
759
|
+
.debug-status-ring.is-none {
|
|
760
|
+
border-style: dotted;
|
|
761
|
+
border-color: var(--text-dim);
|
|
762
|
+
}
|
|
763
|
+
.debug-status-ring.is-starting {
|
|
764
|
+
border-style: dashed;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/* The chat's details under its row, from the title's edge; the row's tint carried down. */
|
|
768
|
+
.debug-detail {
|
|
769
|
+
display: flex;
|
|
770
|
+
min-width: 0;
|
|
771
|
+
flex-direction: column;
|
|
772
|
+
gap: 4px;
|
|
773
|
+
margin-bottom: 2px;
|
|
774
|
+
padding: 0 4px 5px 24px;
|
|
775
|
+
border-radius: 0 0 4px 4px;
|
|
776
|
+
background: var(--bg-selected);
|
|
777
|
+
}
|
|
778
|
+
.debug-detail-line {
|
|
779
|
+
display: flex;
|
|
780
|
+
min-width: 0;
|
|
781
|
+
flex-wrap: wrap;
|
|
782
|
+
align-items: center;
|
|
783
|
+
gap: 2px 6px;
|
|
784
|
+
}
|
|
785
|
+
.debug-detail-id,
|
|
786
|
+
.debug-starts {
|
|
787
|
+
color: var(--text-dim);
|
|
788
|
+
font-family: var(--font-mono);
|
|
789
|
+
font-size: 11px;
|
|
790
|
+
}
|
|
791
|
+
.debug-idle-row {
|
|
792
|
+
display: flex;
|
|
793
|
+
flex-wrap: wrap;
|
|
794
|
+
align-items: center;
|
|
795
|
+
gap: 4px 8px;
|
|
796
|
+
}
|
|
797
|
+
.debug-subhead {
|
|
798
|
+
display: flex;
|
|
799
|
+
align-items: center;
|
|
800
|
+
gap: 6px;
|
|
801
|
+
color: var(--text);
|
|
802
|
+
font-size: 11px;
|
|
803
|
+
font-weight: 700;
|
|
804
|
+
}
|
|
805
|
+
.debug-panel .debug-subhead.is-dim {
|
|
806
|
+
color: var(--text-dim);
|
|
807
|
+
}
|
|
808
|
+
.debug-run-line {
|
|
809
|
+
display: flex;
|
|
810
|
+
flex-wrap: wrap;
|
|
811
|
+
align-items: center;
|
|
812
|
+
gap: 2px 6px;
|
|
813
|
+
}
|
|
814
|
+
.debug-run-icon {
|
|
815
|
+
display: inline-flex;
|
|
816
|
+
width: 12px;
|
|
817
|
+
height: 12px;
|
|
818
|
+
flex-shrink: 0;
|
|
819
|
+
align-items: center;
|
|
820
|
+
justify-content: center;
|
|
821
|
+
}
|
|
822
|
+
.debug-run-icon svg {
|
|
823
|
+
width: 12px;
|
|
824
|
+
height: 12px;
|
|
825
|
+
}
|
|
826
|
+
.debug-run-name {
|
|
827
|
+
min-width: 0;
|
|
828
|
+
overflow: hidden;
|
|
829
|
+
color: var(--text);
|
|
830
|
+
font-size: 12px;
|
|
831
|
+
text-overflow: ellipsis;
|
|
832
|
+
white-space: nowrap;
|
|
833
|
+
}
|
|
834
|
+
.debug-pills {
|
|
835
|
+
display: flex;
|
|
836
|
+
flex-wrap: wrap;
|
|
837
|
+
align-items: center;
|
|
838
|
+
gap: 4px 10px;
|
|
839
|
+
}
|
|
840
|
+
.debug-pill {
|
|
841
|
+
display: inline-flex;
|
|
842
|
+
align-items: center;
|
|
843
|
+
gap: 4px;
|
|
844
|
+
font-size: 11px;
|
|
845
|
+
}
|
|
846
|
+
.debug-pill-state {
|
|
847
|
+
color: var(--text-dim);
|
|
848
|
+
white-space: nowrap;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
.debug-group {
|
|
852
|
+
display: flex;
|
|
853
|
+
flex-direction: column;
|
|
854
|
+
}
|
|
855
|
+
.debug-group-head {
|
|
856
|
+
display: flex;
|
|
857
|
+
min-height: 22px;
|
|
858
|
+
align-items: center;
|
|
859
|
+
gap: 5px;
|
|
860
|
+
color: var(--text-dim);
|
|
861
|
+
font-size: 11px;
|
|
862
|
+
}
|
|
863
|
+
.debug-group-head svg {
|
|
864
|
+
flex-shrink: 0;
|
|
865
|
+
}
|
|
866
|
+
.debug-group-name {
|
|
867
|
+
min-width: 0;
|
|
868
|
+
overflow: hidden;
|
|
869
|
+
font-weight: 600;
|
|
870
|
+
text-overflow: ellipsis;
|
|
871
|
+
white-space: nowrap;
|
|
872
|
+
}
|
|
873
|
+
.debug-group-count {
|
|
874
|
+
font-family: var(--font-mono);
|
|
875
|
+
font-size: 10px;
|
|
876
|
+
font-variant-numeric: tabular-nums;
|
|
877
|
+
}
|
|
878
|
+
.debug-row {
|
|
879
|
+
display: grid;
|
|
880
|
+
min-height: 24px;
|
|
881
|
+
/* The title keeps room for a few characters; the badges wrap before they take it all. */
|
|
882
|
+
grid-template-columns: 14px minmax(96px, 1fr) auto 104px;
|
|
883
|
+
align-items: center;
|
|
884
|
+
column-gap: 6px;
|
|
885
|
+
padding: 0 4px;
|
|
886
|
+
border-radius: 4px;
|
|
887
|
+
}
|
|
888
|
+
.debug-row.debug-list-head {
|
|
889
|
+
min-height: 18px;
|
|
890
|
+
color: var(--text-dim);
|
|
891
|
+
font-size: 10px;
|
|
892
|
+
}
|
|
893
|
+
/* At the end of their columns, spilling left rather than out of the row when wider. */
|
|
894
|
+
.debug-list-head-holders,
|
|
895
|
+
.debug-list-head-idle {
|
|
896
|
+
justify-self: end;
|
|
897
|
+
white-space: nowrap;
|
|
898
|
+
}
|
|
899
|
+
.debug-row.is-current {
|
|
900
|
+
position: relative;
|
|
901
|
+
background: var(--bg-selected);
|
|
902
|
+
}
|
|
903
|
+
.debug-row.has-detail {
|
|
904
|
+
border-radius: 4px 4px 0 0;
|
|
905
|
+
}
|
|
906
|
+
/* The sidebar's mark of the selected session (app/sidebar.css): a short bar on the left edge,
|
|
907
|
+
on the first line however many lines the row takes. */
|
|
908
|
+
.debug-row.is-current::before {
|
|
909
|
+
content: "";
|
|
910
|
+
position: absolute;
|
|
911
|
+
top: 5px;
|
|
912
|
+
left: 0;
|
|
913
|
+
width: 3px;
|
|
914
|
+
height: 14px;
|
|
915
|
+
border-radius: 0 2px 2px 0;
|
|
916
|
+
background: var(--accent);
|
|
917
|
+
}
|
|
918
|
+
.debug-row-status {
|
|
919
|
+
display: inline-flex;
|
|
920
|
+
width: 14px;
|
|
921
|
+
justify-content: center;
|
|
922
|
+
}
|
|
923
|
+
.debug-row-title {
|
|
924
|
+
position: relative;
|
|
925
|
+
display: flex;
|
|
926
|
+
min-width: 0;
|
|
927
|
+
align-items: center;
|
|
928
|
+
gap: 4px;
|
|
929
|
+
}
|
|
930
|
+
.debug-row.is-sub .debug-row-title {
|
|
931
|
+
padding-left: 16px;
|
|
932
|
+
}
|
|
933
|
+
.debug-row-branch {
|
|
934
|
+
position: absolute;
|
|
935
|
+
top: calc(50% - 8px);
|
|
936
|
+
left: 4px;
|
|
937
|
+
width: 8px;
|
|
938
|
+
height: 8px;
|
|
939
|
+
border-bottom: 1px solid var(--border);
|
|
940
|
+
border-left: 1px solid var(--border);
|
|
941
|
+
}
|
|
942
|
+
.debug-row-name {
|
|
943
|
+
min-width: 0;
|
|
944
|
+
overflow: hidden;
|
|
945
|
+
color: var(--text);
|
|
946
|
+
font-size: 12px;
|
|
947
|
+
text-overflow: ellipsis;
|
|
948
|
+
white-space: nowrap;
|
|
949
|
+
}
|
|
950
|
+
.debug-row.is-sub .debug-row-name {
|
|
951
|
+
color: var(--text-muted);
|
|
952
|
+
}
|
|
953
|
+
.debug-row.is-current .debug-row-name {
|
|
954
|
+
font-weight: 600;
|
|
955
|
+
}
|
|
956
|
+
.debug-row.is-placeholder .debug-row-name {
|
|
957
|
+
color: var(--text-dim);
|
|
958
|
+
}
|
|
959
|
+
.debug-row-starts {
|
|
960
|
+
flex-shrink: 0;
|
|
961
|
+
color: var(--text-dim);
|
|
962
|
+
font-family: var(--font-mono);
|
|
963
|
+
font-size: 10px;
|
|
964
|
+
}
|
|
965
|
+
.debug-row-badges {
|
|
966
|
+
display: flex;
|
|
967
|
+
min-width: 0;
|
|
968
|
+
flex-wrap: wrap;
|
|
969
|
+
justify-content: flex-end;
|
|
970
|
+
align-items: center;
|
|
971
|
+
gap: 3px 8px;
|
|
972
|
+
}
|
|
973
|
+
.debug-row-idle {
|
|
974
|
+
display: flex;
|
|
975
|
+
align-items: center;
|
|
976
|
+
justify-content: flex-end;
|
|
977
|
+
gap: 4px;
|
|
978
|
+
}
|
|
979
|
+
.debug-row-forced {
|
|
980
|
+
width: 6px;
|
|
981
|
+
height: 6px;
|
|
982
|
+
flex-shrink: 0;
|
|
983
|
+
border-radius: 1px;
|
|
984
|
+
background: currentColor;
|
|
985
|
+
}
|
|
986
|
+
.debug-row-idle-text {
|
|
987
|
+
min-width: 3ch;
|
|
988
|
+
font-family: var(--font-mono);
|
|
989
|
+
font-size: 11px;
|
|
990
|
+
font-variant-numeric: tabular-nums;
|
|
991
|
+
text-align: right;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
/* The server's totals beside its title. */
|
|
995
|
+
.debug-server-head {
|
|
996
|
+
flex-wrap: wrap;
|
|
997
|
+
gap: 4px 14px;
|
|
998
|
+
color: var(--text-dim);
|
|
999
|
+
font-size: 11px;
|
|
1000
|
+
}
|
|
1001
|
+
.debug-server-item {
|
|
1002
|
+
display: inline-flex;
|
|
1003
|
+
flex-wrap: wrap;
|
|
1004
|
+
align-items: center;
|
|
1005
|
+
gap: 3px 4px;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/* Narrower: the sessions under the server's pages, one border down both; the page's column
|
|
1009
|
+
beside them, its height going to the sessions' row rather than opening a gap under the pages. */
|
|
1010
|
+
@container debug-panel (max-width: 1239px) {
|
|
1011
|
+
.debug-cols {
|
|
1012
|
+
grid-template-areas: "page server" "page sessions";
|
|
1013
|
+
grid-template-columns: minmax(320px, max-content) minmax(0, 560px);
|
|
1014
|
+
grid-template-rows: auto 1fr;
|
|
1015
|
+
}
|
|
1016
|
+
.debug-col-sessions {
|
|
1017
|
+
padding-top: 10px;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
@container debug-panel (max-width: 760px) {
|
|
1021
|
+
.debug-cols {
|
|
1022
|
+
grid-template-areas: "page" "server" "sessions";
|
|
1023
|
+
grid-template-columns: minmax(0, 1fr);
|
|
1024
|
+
grid-template-rows: none;
|
|
1025
|
+
}
|
|
1026
|
+
.debug-col-server {
|
|
1027
|
+
margin-top: 10px;
|
|
1028
|
+
padding-top: 10px;
|
|
1029
|
+
border-top: 1px solid var(--border);
|
|
1030
|
+
}
|
|
1031
|
+
.debug-col-server,
|
|
1032
|
+
.debug-col-sessions {
|
|
1033
|
+
margin-left: 0;
|
|
1034
|
+
padding-left: 0;
|
|
1035
|
+
border-left: 0;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
@container debug-panel (max-width: 520px) {
|
|
1039
|
+
.debug-detail-id {
|
|
1040
|
+
display: none;
|
|
1041
|
+
}
|
|
1042
|
+
.debug-row {
|
|
1043
|
+
grid-template-columns: 14px minmax(0, 1fr) 64px;
|
|
1044
|
+
}
|
|
1045
|
+
/* The badges take a line of their own under the title, which keeps its width. */
|
|
1046
|
+
.debug-row-badges {
|
|
1047
|
+
grid-column: 2 / -1;
|
|
1048
|
+
grid-row: 2;
|
|
1049
|
+
flex-wrap: wrap;
|
|
1050
|
+
justify-content: flex-start;
|
|
1051
|
+
padding-bottom: 4px;
|
|
1052
|
+
}
|
|
1053
|
+
.debug-row.is-sub .debug-row-badges {
|
|
1054
|
+
padding-left: 16px;
|
|
1055
|
+
}
|
|
1056
|
+
.debug-row-badges:empty,
|
|
1057
|
+
.debug-list-head-holders,
|
|
1058
|
+
.debug-page-holder {
|
|
1059
|
+
display: none;
|
|
1060
|
+
}
|
|
1061
|
+
.debug-page-row {
|
|
1062
|
+
grid-template-columns: 30px minmax(0, 1fr) minmax(0, 1fr) 24px;
|
|
1063
|
+
}
|
|
1064
|
+
.debug-row-idle-bar {
|
|
1065
|
+
display: none;
|
|
1066
|
+
}
|
|
1067
|
+
.debug-server-head .debug-section-title {
|
|
1068
|
+
flex-basis: 100%;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
`;var jU=n(82190),jK=n.n(jU);let jq={data:null,loading:!0,error:!1};function jV(e){let{cwd:t,sessionId:n,leafId:r,mobile:i,covered:s,refreshKey:l,terminals:a,onOpenFile:o,onOpenTerminal:c}=e,{t:p}=(0,ns.s)(),h=(0,u.useId)(),m=(0,u.useRef)(null),f=(0,u.useRef)(null),x=(0,u.useRef)(null),v=(0,u.useRef)(!0),[b,y]=(0,u.useState)(!1),[w,j]=(0,u.useState)(0),[k,S]=(0,u.useState)(!1),[C,N]=(0,u.useState)(!1),[E,M]=(0,u.useState)(jq),[$,I]=(0,u.useState)(jq),T=a.filter(e=>{var n;let r;return!e.closing&&t&&(n=e.cwd,(r=e=>{let t=e0(e).replace(/\/+$/,"");return/^[a-z]:(?:\/|$)/i.test(t)||t.startsWith("//")?t.toLowerCase():t})(n)===r(t))}),R=n?`/api/sessions/${encodeURIComponent(n)}/sources${r?`?leafId=${encodeURIComponent(r)}`:""}`:null;(0,u.useEffect)(()=>{if(!b||!t)return;let e=new AbortController,n=(t,n)=>{n(e=>({data:e.url===t?e.data:null,url:t,loading:!0,error:!1})),fetch(t,{signal:e.signal}).then(async r=>{if(!r.ok)throw Error("read failed");let i=await r.json();e.signal.aborted||n({data:i,url:t,loading:!1,error:!1})}).catch(()=>{e.signal.aborted||n(e=>({...e,loading:!1,error:!0}))})};n(`/api/git/status?cwd=${encodeURIComponent(t)}`,M),R?n(R,I):I({data:{sources:[],total:0},loading:!1,error:!1});let r=()=>j(e=>e+1);return window.addEventListener("focus",r),()=>{e.abort(),window.removeEventListener("focus",r)}},[b,t,R,l,w]),(0,u.useLayoutEffect)(()=>{let e=f.current;if(!b||!e)return;let t=m.current;return e.showModal(),x.current?.focus({preventScroll:!0}),()=>{e.open&&e.close(),v.current&&t?.isConnected&&t.focus({preventScroll:!0})}},[b]),(0,u.useLayoutEffect)(()=>{let e=f.current,t=m.current;if(!b||!e||!t)return;let n=window.visualViewport,r=()=>{let r=n?.width??innerWidth,s=n?.height??innerHeight,l=n?.offsetLeft??0,a=n?.offsetTop??0;e.style.maxHeight=`${Math.max(120,s-(i?16:24))}px`,e.style.width=`${Math.min(i?r:370,r-16*!i)}px`;let o=e.getBoundingClientRect(),c=i?{left:l,top:a+s-o.height}:rU({kind:"rect",rect:t.getBoundingClientRect(),align:"end"},o,{left:l,top:a,width:r,height:s});e.style.left=`${c.left}px`,e.style.top=`${c.top}px`};r();let s=new ResizeObserver(r);return s.observe(e),window.addEventListener("resize",r),n?.addEventListener("resize",r),n?.addEventListener("scroll",r),()=>{s.disconnect(),window.removeEventListener("resize",r),n?.removeEventListener("resize",r),n?.removeEventListener("scroll",r)}},[b,i,k,C,E,$]);let A=function(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];v.current=e,y(!1)},L=(0,d.jsxs)("p",{role:"alert",children:[p("overview.loadFailed")," ",(0,d.jsx)("button",{className:jK().more,onClick:()=>j(e=>e+1),children:p("overview.retry")})]}),P=(e,t)=>e.loading?(0,d.jsx)("p",{role:"status",children:p("overview.loading")}):e.error?L:(0,d.jsx)("p",{children:t}),z=E.data?.files??[],O=$.data?.sources??[];return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{ref:m,type:"button",className:jK().trigger,disabled:!t||s,tabIndex:s?-1:void 0,"aria-label":p("overview.title"),title:p("overview.title"),"aria-haspopup":"dialog","aria-expanded":b,"aria-controls":b?h:void 0,onClick:()=>{v.current=!0,S(!1),N(!1),y(!0)},children:(0,d.jsxs)("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"5",cy:"6",r:"2"}),(0,d.jsx)("circle",{cx:"5",cy:"18",r:"2"}),(0,d.jsx)("path",{d:"M11 6h10M11 18h10M3 12h18"})]})}),b&&(0,g.createPortal)((0,d.jsx)("dialog",{ref:f,id:h,className:jK().panel,"data-sheet":i||void 0,"aria-label":p("overview.title"),"aria-modal":"true",onCancel:e=>{e.preventDefault(),e.stopPropagation(),A()},onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||(e.preventDefault(),A()))},onClick:e=>{e.target===e.currentTarget&&A()},children:(0,d.jsxs)("div",{className:jK().card,children:[(0,d.jsxs)("header",{className:jK().header,children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("h2",{children:p("overview.title")}),(0,d.jsx)("span",{title:t??"",children:t?e2(t)||t:""})]}),(0,d.jsx)("button",{type:"button",className:jK().icon,onClick:()=>j(e=>e+1),"aria-busy":E.loading||$.loading,"aria-label":p("overview.refresh"),title:p("overview.refresh"),children:(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M20 11a8 8 0 1 0-2 6M20 4v7h-7"})})}),(0,d.jsx)("button",{ref:x,type:"button",className:jK().icon,onClick:()=>A(),"aria-label":p("overview.close"),title:p("overview.close"),children:"\xd7"})]}),(0,d.jsxs)("section",{className:jK().section,"aria-label":p("overview.changes"),children:[(0,d.jsxs)("div",{className:jK().heading,children:[(0,d.jsx)("h3",{children:p("overview.changes")}),E.data?.isGitRepository&&(0,d.jsxs)("span",{className:jK().counts,children:[(0,d.jsxs)("span",{children:["+",E.data.additions]}),(0,d.jsxs)("span",{children:["−",E.data.deletions]})]})]}),(0,d.jsx)("p",{className:jK().hint,children:p("overview.changesHint")}),E.error&&z.length>0&&L,z.length?(0,d.jsxs)(d.Fragment,{children:[(k?z:z.slice(0,3)).map(e=>(0,d.jsxs)("button",{type:"button",className:jK().row,onClick:()=>{A(!1),o(e.filePath,!0)},title:e.filePath,children:[rm(e2(e.filePath)),(0,d.jsx)("span",{children:e3(e.filePath,t??void 0)}),(0,d.jsx)("small",{children:e.code})]},e.filePath)),z.length>3&&(0,d.jsx)("button",{className:jK().more,"aria-expanded":k,onClick:()=>S(e=>!e),children:p(k?"overview.showLess":"overview.showAll",{count:z.length})})]}):P(E,p(E.data&&!E.data.isGitRepository?"overview.notGit":"overview.noChanges"))]}),(0,d.jsxs)("section",{className:jK().section,"aria-label":p("overview.terminals"),children:[(0,d.jsxs)("div",{className:jK().heading,children:[(0,d.jsx)("h3",{children:p("overview.terminals")}),(0,d.jsx)("small",{children:T.length})]}),T.length?T.map((e,t)=>(0,d.jsxs)("button",{type:"button",className:jK().row,onClick:()=>{A(!1),c(e.id)},title:e.cwd,children:[(0,d.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"3"}),(0,d.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),(0,d.jsxs)("span",{children:[p("overview.terminal",{number:t+1}),(0,d.jsx)("small",{children:e.cwd})]})]},e.id)):(0,d.jsx)("p",{children:p("overview.noTerminals")})]}),(0,d.jsxs)("section",{className:jK().section,"aria-label":p("overview.sources"),children:[(0,d.jsxs)("div",{className:jK().heading,children:[(0,d.jsx)("h3",{children:p("overview.sources")}),$.data&&(0,d.jsx)("small",{children:$.data.total})]}),$.error&&O.length>0&&L,O.length?(0,d.jsxs)(d.Fragment,{children:[(C?O:O.slice(0,3)).map(e=>"file"===e.kind?(0,d.jsxs)("button",{type:"button",className:jK().row,title:e.path,onClick:()=>{A(!1),o(e.path)},children:[rm(e.name),(0,d.jsxs)("span",{children:[e.name,e3(e.path,t??void 0)!==e.name&&(0,d.jsx)("small",{children:e3(e.path,t??void 0)})]})]},e.id):(0,d.jsxs)(lC,{className:jK().row,style:{display:"flex"},alt:p("overview.image",{number:e.number}),src:`${R}${R?.includes("?")?"&":"?"}image=${encodeURIComponent(e.id)}`,children:[(0,d.jsx)("img",{loading:"lazy",width:"36",height:"36",src:`${R}${R?.includes("?")?"&":"?"}image=${encodeURIComponent(e.id)}`,alt:""}),(0,d.jsx)("span",{children:p("overview.image",{number:e.number})})]},e.id)),O.length>3&&(0,d.jsx)("button",{className:jK().more,"aria-expanded":C,onClick:()=>N(e=>!e),children:p(C?"overview.showLess":"overview.showAll",{count:O.length})}),$.data.total>O.length&&(0,d.jsx)("p",{children:p("overview.limited",{count:O.length,total:$.data.total})})]}):P($,p("overview.noSources"))]})]})}),document.body)]})}let jZ="panel:launcher",jJ="tool:files",jY="tool:changes";function jG(e){let{sessionId:t,running:n,...r}=e,{t:i}=(0,ns.s)(),[s,l]=(0,u.useState)(null),[a,o]=(0,u.useState)("loading"),c=(0,u.useRef)(null);return((0,u.useEffect)(()=>{let e,r=new AbortController,i=async()=>{try{let s=await fetch(`/api/sessions/${encodeURIComponent(t)}`,{signal:r.signal,cache:"no-store"});if(404===s.status){o("missing"),n&&(e=setTimeout(()=>void i(),1e3));return}let a=await s.json();a.info?l(a.info):o("error")}catch(e){e instanceof Error&&"AbortError"===e.name||o("error")}};return i(),()=>{r.abort(),clearTimeout(e)}},[t,n]),s)?(0,d.jsx)(uN,{...r,session:s,sessionRunning:n,newSessionCwd:null,newSessionDraftKey:null,chatInputRef:c,panel:!0}):(0,d.jsx)("div",{role:"error"===a?"alert":void 0,style:{padding:"24px 16px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:i("loading"===a||n?"sessionPanel.loading":"missing"===a?"sessionPanel.missing":"sessionPanel.error")})}function jX(e){let{sessionId:t}=e,{t:n}=(0,ns.s)(),[r,i]=(0,u.useState)(null),[s,l]=(0,u.useState)(null),[a,o]=(0,u.useState)(0);return((0,u.useEffect)(()=>{let e=new AbortController,n=!1,r=setTimeout(()=>e.abort(),45e3);return i(null),l(null),(async()=>{try{let r=await fetch(`/api/sessions/${encodeURIComponent(t)}/export?inline=1`,{signal:e.signal,cache:"no-store"});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(e?.error||`HTTP ${r.status}`)}if(!r.headers.get("Content-Type")?.includes("text/html"))throw Error("Expected an HTML history export");let s=await r.text();if(!s.trim())throw Error("Empty history export");let l=new URL(`/api/sessions/${encodeURIComponent(t)}/export?inline=1`,window.location.href).href.replace(/&/g,"&").replace(/"/g,"""),a=s.replace(/<head(?:\s[^>]*)?>/i,e=>`${e}<meta name="pi-share-base-url" content="${l}">`);n||i(pT(a))}catch(e){n||l(e instanceof Error?e.message:String(e))}finally{clearTimeout(r)}})(),()=>{n=!0,clearTimeout(r),e.abort()}},[t,a]),s)?(0,d.jsxs)("div",{className:"session-history-status workspace-empty",role:"alert",children:[(0,d.jsx)("p",{children:n("history.unavailable")}),(0,d.jsxs)("details",{children:[(0,d.jsx)("summary",{children:n("i18n.showDetails")}),(0,d.jsx)("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s})]}),(0,d.jsx)("button",{type:"button",className:"workspace-page-back",onClick:()=>o(e=>e+1),children:n("i18n.refresh")})]}):null===r?(0,d.jsx)("div",{className:"session-history-status workspace-empty",role:"status",children:n("history.loading")}):(0,d.jsx)("iframe",{className:"session-history-frame",title:n("history.full"),srcDoc:r,sandbox:"allow-scripts allow-downloads",referrerPolicy:"no-referrer"})}function jQ(e){let{sessionId:t}=e,{t:n}=(0,ns.s)(),[r,i]=(0,u.useState)(!1),[s,l]=(0,u.useState)(!1),a=(0,u.useRef)(null);(0,u.useEffect)(()=>()=>{a.current?.abort(),a.current=null},[]);let o=async()=>{if(a.current)return;let e=new AbortController;a.current=e;let n=setTimeout(()=>e.abort(),45e3);i(!0),l(!1);try{let n=await fetch(`/api/sessions/${encodeURIComponent(t)}/export`,{signal:e.signal,cache:"no-store"});if(!n.ok||!n.headers.get("Content-Type")?.includes("text/html"))throw Error("Export failed");let r=await n.blob();if(!r.size)throw Error("Empty export");if(a.current!==e)return;let i=n.headers.get("Content-Disposition")?.match(/filename\*=UTF-8''([^;]+)/i)?.[1],s=`pi-session-${t}.html`;if(i)try{s=decodeURIComponent(i)}catch{}s=s.replace(/[\\/\r\n]/g,"_");let l=URL.createObjectURL(r),o=document.createElement("a");o.href=l,o.download=s,document.body.appendChild(o);try{o.click()}finally{o.remove(),setTimeout(()=>URL.revokeObjectURL(l),6e4)}}catch{a.current===e&&l(!0)}finally{clearTimeout(n),a.current===e&&(a.current=null,i(!1))}};return(0,d.jsxs)("span",{className:"session-export-action",children:[(0,d.jsx)("button",{type:"button",className:"workspace-page-export",disabled:r,onClick:()=>void o(),children:n(r?"history.exporting":"navigation.exportHistory")}),s&&(0,d.jsx)("span",{className:"session-export-error",role:"alert",children:n("history.exportFailed")})]})}var j0=n(63606),j1=n(8422);let j2="dark",j4={dark:{background:"#111318",foreground:"#d7dce5",cursor:"#60a5fa",selectionBackground:"#365b8a",black:"#1d222b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e5e7eb",brightBlack:"#6b7280",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"},light:{background:"#fbfbfc",foreground:"#24292f",cursor:"#2563eb",cursorAccent:"#fbfbfc",selectionBackground:"#bfd7fb",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#7d4e00",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#633c01",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#8c959f"}},j3=nn("pi-web:terminal-theme",function(e){return"light"===e?"light":j2},j2);async function j8(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(15e3)}),r=await n.json().catch(()=>{throw Error(`Terminal request failed (HTTP ${n.status}): server returned an empty or invalid JSON response. Check the pi-web server log.`)});if(!r||"object"!=typeof r)throw Error(`Terminal request failed (HTTP ${n.status}): invalid JSON response. Check the pi-web server log.`);if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}let j6={ctrl:!1,alt:!1},j5=[["Escape","/","-","Home","ArrowUp","End","PageUp"],["Tab","ctrl","alt","ArrowLeft","ArrowDown","ArrowRight","PageDown"]],j9=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown"]),j7={ArrowUp:"A",ArrowDown:"B",ArrowRight:"C",ArrowLeft:"D",Home:"H",End:"F"},ke={PageUp:5,PageDown:6};function kt(e){let{ctrl:t,alt:n}=e;return 1+2*!!n+4*!!t}function kn(e,t){if(!t.ctrl&&!t.alt||1!=[...e].length)return e;let n=t.ctrl?function(e){if(/^[a-z]$/i.test(e))return String.fromCharCode(31&e.toUpperCase().charCodeAt(0));let t=e.charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):" "===e?"\0":"/"===e||"-"===e?"\x1f":"?"===e?"":e}(e):e;return t.alt?`\x1b${n}`:n}let kr={Escape:"ESC","/":"/","-":"-",Home:"HOME",ArrowUp:"↑",End:"END",PageUp:"PGUP",Tab:"TAB",ctrl:"CTRL",alt:"ALT",ArrowLeft:"↓",ArrowDown:"↓",ArrowRight:"↑",PageDown:"PGDN"},ki={ArrowUp:"Up",ArrowDown:"Down",ArrowLeft:"Left",ArrowRight:"Right",PageUp:"Page Up",PageDown:"Page Down"};function ks(e){let t=window.matchMedia("(pointer: coarse)");return t.addEventListener("change",e),window.screen.orientation?.addEventListener("change",e),window.addEventListener("orientationchange",e),window.addEventListener("resize",e),()=>{t.removeEventListener("change",e),window.screen.orientation?.removeEventListener("change",e),window.removeEventListener("orientationchange",e),window.removeEventListener("resize",e)}}let kl=()=>window.matchMedia("(pointer: coarse)").matches&&function(){let e=window.screen.orientation?.type;if(e)return e.startsWith("portrait");let t=window.orientation;return"number"==typeof t?t%180==0:window.innerHeight>=window.innerWidth}();function ka(e){let{modifiers:t,onKey:n,onToggleModifier:r}=e,{t:i}=(0,ns.s)(),s=(0,u.useRef)(null),l=()=>{null!==s.current&&window.clearTimeout(s.current),s.current=null};return(0,u.useEffect)(()=>l,[]),(0,d.jsx)("div",{className:"terminal-extra-keys",role:"toolbar","aria-label":i("terminal.extraKeys"),children:j5.flat().map(e=>{let i="ctrl"===e||"alt"===e;return(0,d.jsx)("button",{type:"button",tabIndex:-1,className:i&&t[e]?"is-active":void 0,"aria-pressed":i?t[e]:void 0,"aria-label":i?void 0:ki[e],onPointerDown:t=>((e,t)=>{if(e.preventDefault(),0!==e.button)return;if(l(),"ctrl"===t||"alt"===t)return void r(t);if(n(t),!j9.has(t))return;let i=()=>{n(t),s.current=window.setTimeout(i,50)};s.current=window.setTimeout(i,400)})(t,e),onPointerUp:l,onPointerCancel:l,onPointerLeave:l,onMouseDown:e=>e.preventDefault(),onContextMenu:e=>e.preventDefault(),children:"ArrowLeft"===e||"ArrowRight"===e?(0,d.jsx)("span",{className:"is-rotated",children:kr[e]}):kr[e]},e)})})}function ko(){return window.matchMedia("(pointer: fine)").matches}function kc(e){let{tab:t,active:n,onRestart:r,onClosed:i,onCloseError:s}=e,{t:l}=(0,ns.s)(),{id:a,cwd:o,restored:c}=t,p=(0,u.useRef)(null),h=(0,u.useRef)(null),m=(0,u.useRef)(Promise.resolve()),f=(0,u.useRef)(null),g=(0,u.useRef)({onClosed:i,onCloseError:s});g.current={onClosed:i,onCloseError:s};let[x,v]=(0,u.useState)("connecting"),[b,y]=(0,u.useState)(null),[w,j]=(0,u.useState)(null),[k,S]=(0,u.useState)(0),[C,N]=(0,u.useState)(j6),E=(0,u.useRef)(C),M=(0,u.useSyncExternalStore)(ks,kl,()=>!1),$=j3.use(),I=(0,u.useRef)($);I.current=$;let T=o7(ca().fontSize)-14+13,R=(0,u.useRef)(T);R.current=T;let A=(0,u.useRef)(()=>{}),L=(0,u.useCallback)(()=>{let e=E.current;return(e.ctrl||e.alt)&&(E.current=j6,N(j6)),e},[]);(0,u.useEffect)(()=>{var e;let t,n,r,i,s,l=p.current;if(!l)return;let d=!1,u=null,g=!1,x=!1,b=!1,w=!1,S=0;v("connecting"),y(null),j(null);let C=()=>{let e=getComputedStyle(l);return{fontFamily:e.getPropertyValue("--font-mono").trim()||"monospace",fontWeight:cu(e.getPropertyValue("--font-mono-weight"))}},N=new j1.B({cursorBlink:!0,...C(),fontSize:R.current,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:j4[I.current]});h.current=N;let E=new j0.Y;N.loadAddon(E),N.open(l),N.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&N.hasSelection())});let M=(e=e=>{d||(b=!0,N.options.disableStdin=!0,y(e.message),v("error"))},n=Promise.resolve(),r=!1,i=null,s=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await j8(`/api/terminal/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:s(i={type:"input",data:t})},resize(e,t){i=null,s({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});f.current=M;let $=N.onData(e=>{!g||x||b||S||M.write(kn(e,L()))}),T=()=>{l.offsetWidth&&l.offsetHeight&&E.fit()},P=N.onResize(e=>{let{cols:t,rows:n}=e;!g||x||b||M.resize(Math.max(2,t),Math.max(2,n))});A.current=T;let z=new ResizeObserver(T);z.observe(l);let O=ck(()=>{if(d)return;let e=C();N.options.fontFamily=e.fontFamily,N.options.fontWeight=e.fontWeight,T()}),W=()=>{if(d||x||!navigator.onLine)return;u?.close();let e=new URLSearchParams({holder:tH()});void 0!==t&&e.set("after",String(t)),(u=tV("terminal",new EventSource(`/api/terminal/${encodeURIComponent(a)}/events?${e}`),o)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){let e=w;if(w=!1,n.reset)N.reset();else if(void 0!==t&&n.offset<=t)return;e&&n.data?(S+=1,N.write(n.data,()=>{S-=1})):N.write(n.data),t=n.offset}else x=!0,g=!1,N.options.disableStdin=!0,u?.close(),j("exit"===n.type?n.exitCode:null),v("exited")},u.onopen=()=>{w=c||k>0||void 0!==t,g=!0,!b&&(N.options.disableStdin=!1,v("ready"),T(),M.resize(Math.max(2,N.cols),Math.max(2,N.rows)),ko()&&l.offsetWidth&&l.offsetHeight&&N.focus())},u.onerror=()=>{d||x||(g=!1,N.options.disableStdin=!0,v(u?.readyState===EventSource.CLOSED?"error":"connecting"))}};m.current=(async()=>{T(),c||k>0?await j8(`/api/terminal/${encodeURIComponent(a)}`):await j8("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:a,cwd:o,cols:N.cols,rows:N.rows})}),W()})().catch(e=>{d||(y(e.message),v("error"))});let F=()=>{g=!1,N.options.disableStdin=!0,u?.close(),x||b||v("connecting")},D=e=>{e.persisted&&W()};return window.addEventListener("pagehide",F),window.addEventListener("pageshow",D),window.addEventListener("offline",F),window.addEventListener("online",W),()=>{d=!0,u?.close(),M.stop(),z.disconnect(),O(),$.dispose(),P.dispose(),window.removeEventListener("pagehide",F),window.removeEventListener("pageshow",D),window.removeEventListener("offline",F),window.removeEventListener("online",W),N.dispose(),h.current=null,A.current=()=>{}}},[a,o,c,k,L]),(0,u.useEffect)(()=>{h.current&&(h.current.options.theme=j4[$])},[$]),(0,u.useEffect)(()=>{let e=h.current;e&&e.options.fontSize!==T&&(e.options.fontSize=T,A.current())},[T]),(0,u.useEffect)(()=>{n&&ko()&&h.current?.focus()},[n]),(0,u.useEffect)(()=>{if(!t.closing)return;let e=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await m.current,await f.current?.stop(),await j8(`/api/terminal/${encodeURIComponent(a)}`,{method:"DELETE",keepalive:!0}),e||g.current.onClosed()})().catch(t=>{e||(y(t.message),v("error"),g.current.onCloseError())}),()=>{e=!0}},[a,t.closing]);let P="dark"===$?"light":"dark",z="light"===P?"terminal.lightTheme":"terminal.darkTheme";return(0,d.jsxs)("section",{className:"terminal-panel","data-terminal-theme":$,"aria-label":l("terminal.title"),children:[(0,d.jsxs)("header",{className:"terminal-panel-header",children:[(0,d.jsxs)("div",{className:"terminal-panel-path",children:[(0,d.jsx)("span",{className:`terminal-status-dot is-${x}`,title:l(`terminal.${x}`)}),(0,d.jsx)("span",{title:o,children:o})]}),(0,d.jsxs)("div",{className:"terminal-panel-actions",children:["error"===x&&(0,d.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!t.closing,title:l("terminal.reconnect"),"aria-label":l("terminal.reconnect"),children:(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,d.jsx)("button",{type:"button",onClick:()=>{j3.set(P)},title:l(z),"aria-label":l(z),children:"light"===P?(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,d.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"})]}):(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),(0,d.jsx)("button",{type:"button",onClick:r,disabled:!!t.closing,title:l("terminal.restart"),"aria-label":l("terminal.restart"),children:(0,d.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,d.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]})]}),(0,d.jsxs)("div",{children:[b&&(0,d.jsx)("div",{className:"terminal-panel-error",role:"alert",children:b}),"exited"===x&&(0,d.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===w?l("terminal.exited"):l("terminal.exitCode",{code:w})})]}),(0,d.jsx)("div",{className:"terminal-xterm",children:(0,d.jsx)("div",{ref:p,className:"terminal-xterm-host"})}),M&&(0,d.jsx)(ka,{modifiers:C,onKey:e=>{let t=h.current;if(!t)return;let n=function(e,t,n){let r=t.ctrl||t.alt,i=j7[e];if(i)return r?`\x1b[1;${kt(t)}${i}`:n?`\x1bO${i}`:`\x1b[${i}`;let s=ke[e];return s?r?`\x1b[${s};${kt(t)}~`:`\x1b[${s}~`:"Escape"===e?t.alt?"\x1b\x1b":"\x1b":"Tab"===e?t.alt?"\x1b ":" ":kn(e,t)}(e,L(),t.modes.applicationCursorKeysMode);t.input(n,!0)},onToggleModifier:e=>{let t={...E.current,[e]:!E.current[e]};E.current=t,N(t)}})]})}let kd="pi-web:terminal-tabs";function ku(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}let kp=e=>`pi-web:side-tabs:${e}`;function kh(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let km=[48,120,240,420,720],kf="pi-web:tab-open-session";function kg(){try{return window.sessionStorage}catch{return null}}function kx(e){if("string"!=typeof e||0===e.length)return null;if(e.startsWith("{"))try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;if("session"===t.kind&&"string"==typeof t.sessionId&&t.sessionId)return{kind:"session",sessionId:t.sessionId};if("new"===t.kind&&"string"==typeof t.cwd&&t.cwd.trim())return{kind:"new",cwd:t.cwd};return null}catch{return null}return{kind:"session",sessionId:e}}function kv(e,t){t.setItem(kf,JSON.stringify(e))}let kb="pi-web:agent-strip-locked";function ky(e){return tn(kb,e)}let kw="var(--top-bar-height)",kj=new Set(dH.kU);function kk(e){let t=e.at(-1);return t?`agent:${t.sessionId}`:null}function kS(){var e;let t,n,r,i,s,l,a,o,c,g,b,y,j,k=(0,p.useRouter)(),S=(0,p.useSearchParams)(),[N,E]=(0,u.useState)(()=>(function(e){if("1"===e.get("home"))return{home:!0,requestedCwd:null,sessionId:null,sidebarCollapsed:"collapsed"===e.get("sidebar")};let t=e.get("cwd")?.trim()||null;return{requestedCwd:t,sessionId:t?null:e.get("session")||null,sidebarCollapsed:"collapsed"===e.get("sidebar")}})(S)),[M,$]=(0,u.useState)(()=>!N.sessionId&&!N.requestedCwd);lH(),cM();let{locale:I,t:T}=(0,ns.s)(),[R,A]=(0,u.useState)(!1);(0,u.useEffect)(()=>{let e,t=()=>{clearTimeout(e),A(!0),e=setTimeout(()=>A(!1),4e3)};return window.addEventListener(sM,t),()=>{window.removeEventListener(sM,t),clearTimeout(e)}},[]);let L=nf(),P=(0,u.useSyncExternalStore)(np,nh,nm),z=(0,u.useSyncExternalStore)(nx,nv,nm),[O,W]=(0,u.useState)(null);(0,u.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=new Set,i=!1,s=()=>{n=null,function(e){let{hasFocusedEditable:t,innerHeight:n,viewportHeight:r,viewportScale:i}=e;return!!t&&n/(i>0?i:1)-r>60}({hasFocusedEditable:kh(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?(t.style.setProperty("--app-viewport-height",`${e.height}px`),t.dataset.keyboardOpen="true"):(t.style.removeProperty("--app-viewport-height"),delete t.dataset.keyboardOpen);let r=0!==window.scrollX||0!==window.scrollY,i=.01>Math.abs(e.scale-1);r&&i&&window.scrollTo(0,0)},l=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(s),(()=>{if(i)return;i=!0;let e=0,t=()=>{if(e>=km.length){i=!1;return}let n=km[e++],l=window.setTimeout(()=>{r.delete(l),s(),t()},n);r.add(l)};t()})()},a=()=>{kh()&&l()};return l(),e.addEventListener("resize",l),e.addEventListener("scroll",l),window.addEventListener("resize",l),window.addEventListener("focusin",l),window.addEventListener("focusout",l),window.addEventListener("pageshow",l),document.addEventListener("compositionstart",a),document.addEventListener("compositionupdate",a),document.addEventListener("compositionend",a),document.addEventListener("input",a),document.addEventListener("keyup",a),()=>{for(let t of(e.removeEventListener("resize",l),e.removeEventListener("scroll",l),window.removeEventListener("resize",l),window.removeEventListener("focusin",l),window.removeEventListener("focusout",l),window.removeEventListener("pageshow",l),document.removeEventListener("compositionstart",a),document.removeEventListener("compositionupdate",a),document.removeEventListener("compositionend",a),document.removeEventListener("input",a),document.removeEventListener("keyup",a),null!==n&&window.cancelAnimationFrame(n),r))window.clearTimeout(t);r.clear(),t.style.removeProperty("--app-viewport-height"),delete t.dataset.keyboardOpen}},[]),(0,u.useEffect)(()=>{"Notification"in window&&"granted"===Notification.permission&&fo(I)},[I]);let{soundEnabled:F,onSoundToggle:D,playDoneSound:_,unlockAudio:H,holdAudio:K,soundEnabledRef:q}=function(){let[e,t]=(0,u.useState)(()=>{try{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}catch{return!0}}),n=(0,u.useRef)(e);(0,u.useEffect)(()=>{n.current=e},[e]);let r=(0,u.useRef)(null),i=(0,u.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),s=(0,u.useRef)(0),l=(0,u.useRef)(0),a=(0,u.useRef)(void 0),o=(0,u.useCallback)(e=>{clearTimeout(a.current),a.current=setTimeout(()=>{0===s.current&&0===l.current&&e.suspend().catch(()=>{})},1e3)},[]),c=(0,u.useCallback)((e,t)=>{s.current++,e.resume().then(t).catch(()=>{}).then(()=>{s.current--,o(e)})},[o]),d=(0,u.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&!n.current)return;let t=i();t&&"running"!==t.state&&c(t,()=>{})},[i,c]),p=(0,u.useCallback)(()=>{let e=!n.current;e?d(!0):r.current?.suspend().catch(()=>{}),n.current=e;try{localStorage.setItem("pi-sound-enabled",String(e))}catch{}t(e)},[d]),h=(0,u.useCallback)(()=>{if(l.current++,clearTimeout(a.current),n.current){let e=i();e&&"running"!==e.state&&c(e,()=>{})}let e=!1;return()=>{!e&&(e=!0,l.current--,r.current&&o(r.current))}},[i,c,o]);return{soundEnabled:e,onSoundToggle:p,playDoneSound:(0,u.useCallback)(()=>{if(!n.current)return;let e=i();if(!e)return;let t=Date.now();c(e,()=>{if(n.current&&!(Date.now()-t>3e3))try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let l=t+.18*r;s.gain.setValueAtTime(0,l),s.gain.linearRampToValueAtTime(.18,l+.02),s.gain.exponentialRampToValueAtTime(.001,l+.45),i.start(l),i.stop(l+.45)})}catch{}})},[i,c]),unlockAudio:d,holdAudio:h,soundEnabledRef:n}}(),[V,J]=(0,u.useState)(!1);(0,u.useEffect)(()=>{try{J("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let Y=(0,u.useCallback)(e=>{J(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),en=(0,u.useRef)(new Set),[er,ei]=(0,u.useState)(new Set),es=(0,u.useCallback)((e,t)=>{q.current&&uS(e,t)&&_()},[_,q]),[el,ea]=(0,u.useState)(null),eo=(0,u.useRef)(el);eo.current=el;let[ec,ed]=(0,u.useState)([]),[eu,ep]=(0,u.useState)({entries:[],loaded:!1,error:null}),[eh,em]=(0,u.useState)(null),ef=(0,u.useMemo)(()=>{let e=new Set(eu.entries.map(e=>e.session.id));return ec.filter(t=>!e.has(t.id))},[eu.entries,ec]),[eg,ex]=(0,u.useState)(!1),ev=(0,u.useCallback)(e=>{ed(e),ex(!0),ea(t=>{if(!t)return t;let n=e.find(e=>e.id===t.id);return n?{...t,...n,detailsPending:n.detailsPending,relation:n.relation,branch:n.branch,isWorktree:n.isWorktree}:t})},[]),eb=(0,u.useMemo)(()=>el?[...ec.filter(e=>e.id!==el.id),el]:ec,[el,ec]),ey=(0,u.useMemo)(()=>w(eb,el?.id),[el?.id,eb]),[ew,ej]=(0,u.useState)(()=>new Set),ek=(0,u.useCallback)(e=>{ej(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),eS=ey?(e=ey.subagents,(t=e.filter(e=>ew.has(e.id)).length)>0?{count:t,running:!0}:{count:e.length,running:!1}):null,eC=eS?.running?T("agentSwitcher.titleRunning",{count:eS.count}):T("agentSwitcher.title"),[eN,eE]=(0,u.useState)(ky),eM=(0,u.useMemo)(()=>(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!e||!t)return null;if(e.root.id===t){if(!n||0===e.subagents.length)return null}else if(!e.subagents.some(e=>e.id===t))return null;return[...e.subagents].sort((e,t)=>e.created.localeCompare(t.created)||e.id.localeCompare(t.id))})(ey,el?.id,eN),[ey,el?.id,eN]),e$=(0,u.useRef)(null),eI=(0,u.useCallback)(()=>{let e=!eN;eE(e),tr(kb,e,void 0),e||requestAnimationFrame(()=>t_(document,e$.current))},[eN]),[eT,eR]=(0,u.useState)(null),[eA,eL]=(0,u.useState)("initial"),eP=(0,u.useRef)(null),ez=(0,u.useRef)(null),[eO,eW]=(0,u.useState)(null),eF=(0,u.useRef)(null),eD=(0,u.useCallback)(e=>{e&&e.cwd===eF.current?.cwd&&(eF.current=null),eW(e)},[]),e_=(0,u.useRef)(null),eB=(0,u.useRef)(null),[eH,eU]=(0,u.useState)(null),eK=(0,u.useCallback)(e=>{eB.current=e,eU(null)},[]),[eq,eV]=(0,u.useState)(()=>N.requestedCwd?"validating":"idle"),[eZ,eJ]=(0,u.useState)(null),[eY,eG]=(0,u.useState)(0),[eX,eQ]=(0,u.useState)(0),e0=(0,u.useRef)(new Map),e1=(0,u.useCallback)((e,t)=>{e0.current.set(e,t)},[]),[e4,e3]=(0,u.useState)(null),e8=(0,u.useCallback)(e=>{e3(t=>t===e?null:t)},[]),[e6,e5]=(0,u.useState)(0),[e9,te]=(0,u.useState)(null),[tt,tn]=(0,u.useState)(!1),[ti,ts]=(0,u.useState)(0),tl=(0,u.useRef)(!1);(0,u.useEffect)(()=>{tl.current&&!e9&&ts(e=>e+1),tl.current=null!==e9},[e9]);let[ta,to]=(0,u.useState)(null),[tc,td]=(0,u.useState)(!1),[tu,tp]=(0,u.useState)(!1),[th,tm]=(0,u.useState)(null),[tf,tg]=(0,u.useState)(()=>!N.sidebarCollapsed),{phase:tx,start:tv}=f(),tb=(0,u.useRef)(tf);(0,u.useLayoutEffect)(()=>{tb.current!==tf&&(tb.current=tf,tv(tf?"in":"out"))},[tf,tv]);let ty=(0,u.useRef)(!N.sidebarCollapsed),tw=(0,u.useRef)(null),tj=(0,u.useRef)(null),[tk,tS]=(0,u.useState)(!1),[tC,tN]=(0,u.useState)(null),tE=tC===jJ,[tM,t$]=(0,u.useState)(!1),[tI,tT]=(0,u.useState)("file"),tR=tk&&tM&&z,tA=tR&&"file"===tI,tL=tR&&"conversation"===tI,tP=z&&tk,[tz,tO]=(0,u.useState)(!1),tW=z&&tz,tD=(0,u.useRef)(null),tB=(0,u.useRef)(null);(0,u.useEffect)(()=>{tE&&tO(!1)},[tE]);let tH=(0,u.useCallback)(()=>{tT("file"),tO(!tW),requestAnimationFrame(()=>{let e=tW?tD.current??document.querySelector("#file-panel .workbench-tree-resizer"):tB.current;e?.closest("[inert]")||e?.focus({preventScroll:!0})})},[tW]);(0,u.useEffect)(()=>{tk&&z||t$(!1)},[tk,z]);let[tU,tK]=(0,u.useState)(!1),tq=tU?T("chat.close"):T("chat.moreControls"),[tV,tZ]=(0,u.useState)(!1),tG=(0,u.useRef)(260),tX=(0,u.useRef)(560),tQ=(0,u.useRef)(320),t0=(0,u.useCallback)(()=>window.innerWidth>=1200?Math.round(.48*window.innerWidth):nb(.42*window.innerWidth,360,640),[]),t1=(0,u.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth-62*(window.innerWidth>640),rightPanelOpen:tk,rightPanelWidth:tX.current}),[tk]),t2=(0,u.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:n,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(n?r:0))})({viewportWidth:window.innerWidth-62*(window.innerWidth>640),sidebarOpen:tf,sidebarWidth:tG.current}),[tf]),t4=nw({ariaLabel:T("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:t1,growthDirection:"right",maxWidth:480,minWidth:180,collapseAt:120,onCollapse:(0,u.useCallback)(()=>{ty.current=!1,tg(!1)},[]),storageKey:"pi-sidebar-width",widthRef:tG}),t3=nw({ariaLabel:T("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:t0,getMaxWidth:t2,growthDirection:"left",maxWidth:1200,minWidth:z?520:300,storageKey:"pi-right-panel-width",widthRef:tX}),t8=nw({ariaLabel:T("layout.resizeFileTree"),cssVariable:"--workbench-tree-width",defaultWidth:320,minWidth:200,maxWidth:640,getMaxWidth:(0,u.useCallback)(()=>Math.max(200,Math.min(640,tX.current-280)),[]),growthDirection:"left",persistClamp:!1,collapseAt:120,onCollapse:(0,u.useCallback)(()=>{tO(!0),requestAnimationFrame(()=>tB.current?.focus({preventScroll:!0}))},[]),storageKey:"pi-workbench-file-tree-width",widthRef:tQ}),t6=t8.panelRef,t5=function(e,t,n){let[r,i]=(0,u.useState)(!1),s=(0,u.useRef)(void 0),l=(0,u.useCallback)(()=>{clearTimeout(s.current),s.current=void 0},[]),a=(0,u.useCallback)(()=>{l(),i(!1)},[l]),o=(0,u.useCallback)(()=>{l(),e&&!r&&(s.current=setTimeout(()=>i(!0),120))},[l,e,r]),c=(0,u.useCallback)(()=>{l(),e&&(s.current=setTimeout(()=>{let e=document.activeElement;document.querySelector(".sidebar-menu, .sidebar-sheet")||e&&t.current?.contains(e)&&e.matches("input, textarea, [contenteditable=true], :focus-visible")||i(!1)},280))},[l,e,t]);return(0,u.useEffect)(()=>{e||a()},[e,a]),(0,u.useEffect)(()=>l,[l]),(0,u.useEffect)(()=>{if(!e||!r)return;let i=e=>e instanceof Element&&(t.current?.contains(e)||n.current?.contains(e)||e.closest(".sidebar-menu, .sidebar-sheet, [data-sidebar-restore]")),s=e=>{i(e.target)?l():c()},o=e=>{i(e.target)||a()},d=e=>{"Escape"!==e.key||document.querySelector(".sidebar-menu, .sidebar-sheet")||(e.preventDefault(),e.stopPropagation(),a(),n.current?.focus({preventScroll:!0}))};return document.addEventListener("pointermove",s),document.addEventListener("pointerdown",o,!0),document.addEventListener("keydown",d,!0),()=>{document.removeEventListener("pointermove",s),document.removeEventListener("pointerdown",o,!0),document.removeEventListener("keydown",d,!0)}},[l,a,e,r,t,c,n]),{open:e&&r,show:o,cancel:l,scheduleHide:c,dismiss:a}}(!L&&!tf,t4.panelRef,tj),t9=t5.dismiss,t7=t3.panelRef,ne=(0,u.useCallback)(e=>{t7.current=e?.parentElement,t6.current=e},[t7,t6]),nt=(0,u.useCallback)(e=>{W(e)},[]),nn=t8.reclampWidth;(0,u.useEffect)(()=>{nn()},[t3.width,nn]);let nr=t4.reclampWidth,ni=t3.reclampWidth;(0,u.useEffect)(()=>{tg(!L&&ty.current)},[L]),(0,u.useEffect)(()=>{tZ(!0)},[]),(0,u.useEffect)(()=>{tk&&(nr(),ni())},[ni,nr,tk,t8.width]);let nl=(0,u.useRef)(null),[na,no]=(0,u.useState)({}),nc=(0,u.useRef)(null),nd=(0,u.useRef)(null),[nu,ng]=(0,u.useState)([]),[ny,nj]=(0,u.useState)(null),[nk,nS]=(0,u.useState)(!1),nC=(0,u.useRef)(null),nN=wn(nu),nM=(0,u.useCallback)((e,t,n,r)=>{ng(e),nj(t),nS(r),nC.current=n},[]),n$=(0,u.useCallback)(e=>{!nk&&nC.current&&(nC.current(e),n5(null))},[nk]),[nI,nT]=(0,u.useState)(null),[nR,nA]=(0,u.useState)(null),[nL,nP]=(0,u.useState)(!1),nz=(0,u.useRef)(null),nO=(0,u.useRef)(0),nW=(0,u.useRef)(null),nF=(0,u.useCallback)(e=>{nT(e),nP(!1)},[]),nD=(0,u.useCallback)(e=>{nA(e)},[]),n_=(0,u.useCallback)(e=>{nO.current+=1,nz.current=e,nP(!1)},[]),nB=(0,u.useRef)(null),nH=(0,u.useCallback)(e=>{nB.current=e},[]);(0,u.useEffect)(()=>{null===tJ.trackingSince&&"u">typeof document&&(tJ.trackingSince=Date.now(),document.addEventListener("visibilitychange",tY))},[]);let[nU,nK]=(0,u.useState)(null),[nq,nV]=(0,u.useState)({kind:"idle"}),nZ=(0,u.useRef)(null),nJ=(0,u.useRef)(el?.id??null);nJ.current=el?.id??null;let nY=(0,u.useCallback)(e=>{nK(e)},[]),[nG,nX]=(0,u.useState)(null),nQ=(0,u.useRef)(null),n0=(0,u.useCallback)((e,t)=>{nX(null),s$(t).then(()=>{nQ.current&&clearTimeout(nQ.current),nX(e),nQ.current=setTimeout(()=>nX(null),1400)},()=>{})},[]);(0,u.useEffect)(()=>()=>{nQ.current&&clearTimeout(nQ.current),nZ.current&&clearTimeout(nZ.current)},[]);let[n1,n2]=(0,u.useState)(null),n3=(0,u.useCallback)(e=>{n2(e)},[]),[n6,n5]=(0,u.useState)(null),[n9,n7]=(0,u.useState)(0),re=(0,u.useRef)(null),rt=(0,u.useRef)(null),rn=(0,u.useRef)(null),rr=(0,u.useRef)(null);m(rn,e9?"settings":n6??(M?"home":"chat")),m(rr,tC||null),(0,u.useLayoutEffect)(()=>{n6&&!e9&&rt.current?.focus({preventScroll:!0})},[n6,e9]),(0,u.useEffect)(()=>{if(n6&&!e9)return tF(document,()=>n5(null))},[n6,e9]),(0,u.useEffect)(()=>{e9&&(n5(null),tK(!1),L&&tg(!1))},[e9,L]);let ri=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];tT("conversation"),L&&tg(!1),te(null),n5(t=>t===e?null:e),t||tK(!1)},[L]),rs=(0,u.useRef)(null),rl=(0,u.useCallback)(e=>{n5(e=>"debug"===e?null:e),e&&requestAnimationFrame(()=>t_(document,rs.current))},[]),ra=(0,u.useCallback)(e=>{let t=n6!==e;if(ri(e),!t||nL)return;let n=nz.current;if(!n)return;let r=++nO.current;nP(!0),n().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{nO.current===r&&nP(!1)})},[n6,nL,ri]),ro=(0,u.useCallback)(()=>{tT("conversation"),L&&tg(!1),tK(!1),n5("session")},[L]),rc=(0,u.useCallback)(e=>{tT("conversation"),t9(),tn(!1),te(e)},[t9]),rd=(0,u.useCallback)(()=>{t9(),L&&tK(!1),tg(e=>{let t=!e;return L||(ty.current=t),t})},[t9,L]),ru=(0,u.useCallback)(()=>{tg(!1),n5(null),tK(e=>!e)},[]),rp=(0,u.useCallback)(()=>{tS(!1),nc.current?.querySelector(".workspace-files-toggle:not([aria-hidden='true'])")?.focus({preventScroll:!0})},[]),rh=(0,u.useCallback)(()=>{n5(null),tT("file"),t$(e=>!e)},[]);(0,u.useEffect)(()=>{if(!tU)return;let e=e=>{let t=nd.current;t&&e.composedPath().includes(t)||tK(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),tK(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[tU]),(0,u.useEffect)(()=>{tK(!1)},[L,P,el?.id,eA]);let[rm,rf]=(0,u.useState)([]),rg=(0,u.useRef)(new Map),[rx,rv]=(0,u.useState)(0),ry=(0,u.useRef)(0),[rw,rj]=(0,u.useState)([]),[rk,rS]=(0,u.useState)(!1),[rC,rN]=(0,u.useState)([]),rE=(0,u.useRef)(null),rM=(0,u.useRef)(!1),r$=(0,u.useRef)(!1),[rI,rT]=(0,u.useState)(null),rR=(0,u.useRef)(null),[rA,rL]=(0,u.useState)([]),rP=function(e,t){if(!t.length)return e;let n=new Map(e.map(e=>[e.id,e])),r=[];for(let e of t){let t=n.get(e);t&&(r.push(t),n.delete(e))}return[...r,...n.values()]}([...rm.map(e=>"files"===e.kind?{...e,label:T("workbench.openFile")}:"changes"===e.kind?{...e,label:T("panel.changes")}:e),...rw.map(e=>({id:e.id,label:e2(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing})),...rC.map(e=>{let t=e.side?ec.find(t=>t.id===e.sessionId):void 0,n=t?x(t,T("agentSwitcher.sideChat"),ey?.subagents??[]):e.label;return{id:`agent:${e.sessionId}`,label:n,filePath:n,kind:e.side?"side":"agent"}})],rA);(0,u.useEffect)(()=>{L&&n6&&tS(!1)},[L,n6]);let rz=rP.map(e=>e.id).join("\n");(0,u.useEffect)(()=>{let e=new Set(rz.split("\n"));rL(t=>t.every(t=>e.has(t))?t:t.filter(t=>e.has(t)))},[rz]),(0,u.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(kd));rj(e.tabs),e.activeId&&(tN(e.activeId),tS(e.open))}catch{}rS(!0)},[]),(0,u.useEffect)(()=>{if(rk)try{window.sessionStorage.setItem(kd,JSON.stringify({tabs:rw.map(e=>{let{id:t,cwd:n}=e;return{id:t,cwd:n}}),activeId:tC,open:tk}))}catch{}},[rw,tC,tk,rk]);let rO=(0,u.useCallback)(e=>{try{let t=rC.filter(e=>e.side);if(!t.length)return void window.sessionStorage.removeItem(kp(e));window.sessionStorage.setItem(kp(e),JSON.stringify({tabs:t,activeId:t.some(e=>`agent:${e.sessionId}`===tC)?tC:null,open:tk}))}catch{}},[rC,tC,tk]),rW=(0,u.useCallback)((e,t,n,r)=>{e!==ry.current?function(e,t,n,r,i){for(let[s,l]of e)if(l.generation===t)return void e.set(s,{...l,tabs:hg(l.tabs,n,r,i)})}(rg.current,e,t,n,r):rf(e=>hg(e,t,n,r))},[]),rF=(0,u.useCallback)((e,t)=>{if(e===t)return;let n=tC?.startsWith("file:")||tC===jJ||tC===jY?tC:null,r=function(e,t,n,r,i){if(t===n)return r;t&&e.set(t,{...r,generation:i});let s=e.get(n);return s?(e.delete(n),{tabs:s.tabs,activeTabId:s.activeTabId,open:s.open}):{tabs:[],activeTabId:null,open:!1}}(rg.current,e,t,{tabs:rm,activeTabId:n,open:tk&&!!n},ry.current);ry.current+=1,rv(ry.current),rf(r.tabs),rN(e=>e.filter(e=>e.side)),rM.current&&rE.current&&(rO(rE.current),r$.current=!0),(!tC||n||tC===jZ||tC.startsWith("agent:"))&&(tN(r.activeTabId),tS(r.open))},[tC,rm,rO,tk]),rD=(0,u.useCallback)((e,t)=>{nl.current?.insertText(rb(e,t)),L&&(tS(!1),tg(!1))},[L]),r_=(0,u.useCallback)(e=>{let t=e.map(e=>rb(e,!1)).join("");t&&nl.current?.insertText(t),L&&(tS(!1),tg(!1))},[L]),rB=(0,u.useCallback)((e,t,n)=>{let r,i,s,l;nl.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,l=r===i?`:${r}`:`:${r}-${i}`,`${s}${l} `)),L&&(tS(!1),tg(!1))},[L]),rH=N.sessionId,rU=N.sessionFromTab?null:N.sessionId,[rK,rq]=(0,u.useState)(()=>!rH),rV=ey?.root.id??null;(0,u.useEffect)(()=>{if(!eg||!rK)return;let e=rE.current;if(!rM.current||e!==rV){rM.current&&e&&!r$.current&&rO(e),r$.current=!1,rM.current=!0,rE.current=rV;let t={tabs:[],activeId:null,open:!1};if(rV)try{t=function(e,t,n){try{let r=JSON.parse(e??"null"),i=[];for(let e of Array.isArray(r?.tabs)?r.tabs:[]){if("string"!=typeof e?.sessionId||"string"!=typeof e.label)continue;let r=n.find(t=>t.id===e.sessionId);r?.relation?.kind!=="side"||r.relation.parentSessionId!==t||i.some(t=>t.sessionId===e.sessionId)||i.push({sessionId:e.sessionId,label:e.label,side:!0})}let s=i.some(e=>`agent:${e.sessionId}`===r?.activeId)?r.activeId:null;return{tabs:i,activeId:s,open:r?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(kp(rV)),rV,ec)}catch{}rN(e=>[...e.filter(e=>!e.side),...t.tabs]);let n=t.activeId===`agent:${el?.id}`?null:t.activeId;(n||tC?.startsWith("agent:")||!tC)&&(tN(n??rm.at(-1)?.id??rw.at(-1)?.id??null),tS(n?t.open:!!(rm.length||rw.length)&&tk));return}rV&&rO(rV),r$.current=!1},[tC,eg,rm,rK,rO,tk,el?.id,ec,rV,rw]),(0,u.useLayoutEffect)(()=>{var e;let t=(e=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:kg();if(!e)return null;try{return kx(e.getItem(kf))}catch{return null}}(),N.home||N.requestedCwd||N.sessionId||!e?N:"session"===e.kind?{...N,sessionId:e.sessionId,sessionFromTab:!0}:{...N,requestedCwd:e.cwd});t!==N&&(E(t),t.sessionId&&rq(!1))},[N]);let rZ=(0,u.useRef)(!1),rJ=(0,u.useRef)(!1),rY=(0,u.useRef)(0),rG=(0,u.useCallback)(()=>{rY.current+=1},[]);(0,u.useEffect)(()=>{if(el){!function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:X();if(n)try{let r=Q(n);r[e]=t,n.setItem(G,JSON.stringify(r))}catch{}}(el.projectKey??rR.current??et(el),el.id),function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:kg();if(t&&e)try{kv({kind:"session",sessionId:e},t)}catch{}}(el.id);return}eT&&function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:kg(),n=e.trim();if(t&&n)try{kv({kind:"new",cwd:n},t)}catch{}}(eT)},[eT,el]),(0,u.useEffect)(()=>{let e=N.requestedCwd;if(!e)return;let t=new AbortController,n=rY.current;return eV("validating"),eJ(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async r=>{let i=await r.json().catch(()=>({}));if(!r.ok||!i.cwd)throw Error(i.error??`HTTP ${r.status}`);if(t.signal.aborted||n!==rY.current)return;rZ.current=!0;let s=`initial:${e}`;eL(s),eP.current=`new:${s}:${i.cwd}`,eR(i.cwd),$(!1),eV("ready"),new URLSearchParams(window.location.search).get("cwd")||k.replace(`?cwd=${encodeURIComponent(i.cwd)}`,{scroll:!1})}).catch(e=>{t.signal.aborted||n!==rY.current||(eJ(e instanceof Error?e.message:String(e)),eV("error"))}),()=>t.abort()},[N,k]);let rX=(0,u.useCallback)((e,t)=>{let n=++rY.current,r=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:X();if(!t)return null;try{let n=Q(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);if(!r)return;let i=i=>{if(n!==rY.current)return;let s=i?.sessions.find(e=>e.id===r);if(!s){i&&ee(e);return}if(et(s)!==e)return void ee(e);let l=eP.current;l&&Z(l,C(t)),eP.current=null,ea(s),eQ(e=>e+1),new URLSearchParams(window.location.search).get("session")!==s.id&&k.replace(`?session=${encodeURIComponent(s.id)}`,{scroll:!1})};ec.length>0?i({sessions:ec}):fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i).catch(()=>{})},[k,ec]),rQ=(0,u.useCallback)((e,t,n)=>{rG();let r=eT??el?.cwd??rI;if(rT(e),!e)return;let i=rJ.current;rJ.current=!1;let s=n??t??e,l=rR.current??(el?et(el):null);if(rR.current=s,rZ.current){rZ.current=!1;return}if(r===e&&l!==s||l===s&&(null!==el||r===e))return;let a=eP.current;a&&r&&Z(a,C(r));let o="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,c=`new:${o}:${e}`;Z(C(e),c),eL(o),eP.current=c,ea(null),eR(t=>t&&t!==e?null:t),eQ(e=>e+1),ng([]),nj(null),nS(!1),nT(null),nA(null),nP(!1),n5(e=>"debug"===e?e:null),l!==s&&(rF(l,s),M||i||rX(s,e)),M||k.replace(window.location.pathname,{scroll:!1})},[rI,rF,M,rG,eT,k,el,rX]),r0=(0,u.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;t||tT("conversation"),t||t9(),$(!1),n5(e=>"debug"===e?e:null),te(null),e3(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),rG();let s=eP.current,l=eT??(null===el?rI:null);s&&l&&Z(s,C(l)),eP.current=null;let a=et(e);if(rR.current!==a&&(rF(rR.current,a),n5(e=>"debug"===e?e:null)),rR.current=a,!t&&!M&&el){let t=et(el)===et(e);if(el.id===e.id&&t){L&&tg(!1);return}}eR(null),ea(e),eQ(e=>e+1),ng([]),nj(null),nS(!1),nC.current=null,nT(null),nA(null),nP(!1),rq(!0),!L||t||i?.keepSidebarOpen||tg(!1),t&&(rZ.current=!0),t&&new URLSearchParams(window.location.search).get("session")===e.id||k.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rI,rF,t9,M,rG,k,L,eT,el]),r1=(0,u.useCallback)((e,t,n,r)=>{tT("conversation"),t9(),$(!1),te(null),rG();let i=`new:${e}:${t}`,s=eP.current,l=eT??(null===el?rI:null);if(r?.carryComposer&&null===el&&s){let e=nl.current;e?e.rekeyDraft(s,i):Z(s,i),eU(eB.current)}else s&&l&&l!==t&&Z(s,C(l));let a=n??(t===rI?rR.current:null)??t;rR.current!==a&&rF(rR.current,a),rR.current=a,B(i)||Z(C(t),i),eP.current=i,eL(e),ea(null),eR(t),eQ(e=>e+1),ng([]),nj(null),nS(!1),nT(null),nA(null),nP(!1),n5(e=>"debug"===e?e:null),L&&tg(!1),k.replace(`?cwd=${encodeURIComponent(t)}`,{scroll:!1}),L||e_.current||requestAnimationFrame(()=>{document.activeElement?.closest("[aria-modal='true']")||nl.current?.focus()})},[rI,rF,t9,rG,L,eT,k,el]);!function(e){let{onNewSession:t,activeCwd:n}=e;(0,u.useEffect)(()=>{let e=e=>{if("Escape"===e.key)return void function(e){if("Escape"!==e.key||e.defaultPrevented||!h)return;let t=e.target?.tagName;"TEXTAREA"!==t&&"INPUT"!==t&&(e.preventDefault(),h())}(e);if(e.ctrlKey&&e.altKey&&("n"===e.key.toLowerCase()||"Dead"===e.key&&"KeyN"===e.code)){if(!n||!t)return;e.preventDefault(),t(n)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[n,t])}({onNewSession:e=>r1(`kb-${Date.now()}`,e),activeCwd:rI});let r2=(0,u.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&ea(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),r4=(0,u.useCallback)((e,t)=>{eG(e=>e+1),eP.current===t&&(rG(),eP.current=null,eR(null),ea(e),r2(e.id),k.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[rG,k,r2]),r3=(0,u.useCallback)(e=>{let{targetSession:t,title:n,body:r,tag:i}=e;if(!("Notification"in window))return;let s=()=>{u5({title:n,body:r,sessionUrl:t?`/?session=${encodeURIComponent(t.id)}`:"/",tag:i,onClick:()=>{window.focus(),t&&r0(t)}})};"granted"===Notification.permission?(s(),fo(I)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(s(),fo(I))})},[r0,I]),r8=(0,u.useCallback)(e=>{eG(e=>e+1),e5(e=>e+1),e.aborted||e.failed||e.subagentsActive||v(el?.relation)||!u6()||(el&&ei(e=>{if(e.has(el.id))return e;let t=new Set(e);return t.add(el.id),t}),r3({targetSession:el,title:el?.name??T("i18n.sessionComplete"),body:T("i18n.taskFinished"),tag:el?`pi-session-complete:${el.id}`:"pi-session-complete"}))},[r3,el,T]);(0,u.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&document.hasFocus()&&ei(e=>0===e.size?e:new Set)};return e(),document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[]);let r6=(0,u.useCallback)(e=>{var t;!v(el?.relation)&&u6()&&(t=en.current,!(!dS(e)||t.has(e.id))&&(t.add(e.id),1)&&r3({targetSession:el,title:T("i18n.attentionNeeded"),body:"custom"===e.method?T("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[r3,el,T]),r5=(0,u.useCallback)(async()=>{let e=el?.id;if(e&&"naming"!==nq.kind){nZ.current&&clearTimeout(nZ.current),n5(null),nV({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(eG(e=>e+1),nJ.current!==e)return;ea(t=>t?.id===e?{...t,name:r}:t),nK(t=>t?.sessionId===e?{...t,sessionName:r}:t),nV({kind:"success"}),nZ.current=setTimeout(()=>nV({kind:"idle"}),1800)}catch(t){if(nJ.current!==e)return;nV({kind:"error",message:t instanceof Error?t.message:String(t)}),nZ.current=setTimeout(()=>nV({kind:"idle"}),5e3)}}},[nq.kind,el?.id]);(0,u.useEffect)(()=>{nZ.current&&clearTimeout(nZ.current),nV({kind:"idle"})},[el?.id]);let r9=(0,u.useCallback)(()=>{e5(e=>e+1)},[]),r7=(0,u.useRef)(null),ie=(0,u.useCallback)(e=>{kj.has(e)||r7.current||(r7.current=setTimeout(()=>{r7.current=null,e5(e=>e+1)},1e3))},[]);(0,u.useEffect)(()=>()=>{r7.current&&clearTimeout(r7.current)},[]);let it=(0,u.useCallback)((e,t)=>{if(t){eG(e=>e+1),r0(t);return}rG(),eP.current=null,eG(e=>e+1),eQ(e=>e+1),eR(null),ea(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),r2(e),k.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[r0,rG,k,r2]),ir=(0,u.useCallback)(()=>{rq(!0),rU&&(rJ.current=!0)},[rU]),ii=(0,u.useCallback)(e=>{rG(),eG(e=>e+1);let t=eo.current;if(t?.id===e){!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:kg();if(t&&e)try{let n=kx(t.getItem(kf));if(n?.kind!=="session"||n.sessionId!==e)return;t.removeItem(kf)}catch{}}(e);let n=t.cwd,r="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;eL(r),eP.current=n?`new:${r}:${n}`:null,ea(null),eR(n??null),eQ(e=>e+1),ng([]),nj(null),nS(!1),nT(null),nA(null),nP(!1),n5(e=>"archive"===e||"debug"===e?e:null),k.replace(n?`?cwd=${encodeURIComponent(n)}`:window.location.pathname,{scroll:!1})}},[rG,k]),is=(0,u.useCallback)((e,t,n)=>{var r,i;tT("file"),tE&&!tR&&(r=tX.current,i=tQ.current,Number.isFinite(r)&&Number.isFinite(i)&&r>0&&i>0&&r-i<400)&&tO(!0);let s=n?.sourceSessionId,l=n?.modeHint,a=n?.page,o=`file:${e}`;rf(n=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,page:t.page,viewerState:t.modeHint?{displayMode:t.modeHint,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=n.page!==t.page;return r||t.modeHint||i?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e},s=!1;return r&&(n.sourceSessionId=t.sourceSessionId,s=!0),i&&(n.page=t.page,s=!0),t.modeHint&&(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines,scrollTop:0,scrollLeft:0},s=!0),s&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:l,page:a,sourceSessionId:s,tabId:o})),tN(o),tS(!0),L&&tg(!1)},[tE,L,tR]),il=(0,u.useCallback)((e,t)=>{is(e,e2(e),{sourceSessionId:el?.id??null,page:t})},[is,el?.id]),ia=(0,u.useCallback)(e=>{tT("file");let t=rw.find(t=>t.cwd===e),n=t??ku(e);t||rj(e=>[...e,n]),tN(n.id),tS(!0),L&&tg(!1)},[rw,L]),io=(0,u.useCallback)((e,t,n)=>{tT("file"),rN(r=>r.some(t=>t.sessionId===e)?r:[...r,{sessionId:e,label:t,...n?{side:!0}:{}}]),tN(`agent:${e}`),tS(!0),L&&tg(!1)},[L]),ic=(0,u.useMemo)(()=>new Set(tk?rC.map(e=>e.sessionId):[]),[rC,tk]),id=(0,u.useCallback)((e,t)=>{let n=e.relation?.kind==="side"?e.relation.parentSessionId:null;if(!n||n===rE.current)return io(e.id,t,!0),!0;try{let r=kp(n);window.sessionStorage.setItem(r,function(e,t,n){let r=[];try{let t=JSON.parse(e??"null");Array.isArray(t?.tabs)&&(r=t.tabs)}catch{}return JSON.stringify({tabs:[...r,{sessionId:t,label:n,side:!0}],activeId:`agent:${t}`,open:!0})}(window.sessionStorage.getItem(r),e.id,t))}catch{}return!1},[io]),iu=(0,u.useCallback)(e=>{let t=iN(e,ec,T("agentSwitcher.sideChat")),n=t?ec.find(e=>e.id===t.parentSessionId):void 0;t&&n&&(ed(t=>t.some(t=>t.id===e.id)?t:[e,...t]),id(e,t.label)||r0(n))},[r0,id,ec,T]),ip=(0,u.useCallback)((e,t)=>{t&&no(n=>({...n,[e.id]:t})),ed(t=>[e,...t.filter(t=>t.id!==e.id)]),id(e,T("agentSwitcher.sideChat")),eG(e=>e+1)},[id,T]),ih=(0,u.useRef)(new Map),im=(0,u.useCallback)((e,t)=>{let n=ih.current.get(e);if(n)return n;let r=(async()=>{let n=await dP(e,T);return"error"in n?n.error:void 0!==t&&t!==ry.current?(eG(e=>e+1),T("panel.workspaceChanged")):(L&&n5(null),ip(n.session,null),null)})();return ih.current.set(e,r),r.finally(()=>{ih.current.get(e)===r&&ih.current.delete(e)}).catch(()=>{}),r},[ip,L,T]),ig=rC.filter(e=>e.side&&ew.has(e.sessionId)).map(e=>e.sessionId).join();(0,u.useEffect)(()=>{ig&&eG(e=>e+1)},[ig]);let ix=(0,u.useCallback)(e=>{if(rw.some(t=>t.id===e))return void rj(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));if(e.startsWith("agent:")){let t=rC.filter(t=>`agent:${t.sessionId}`!==e);rN(t),tN(n=>n!==e?n:rm.at(-1)?.id??rw.at(-1)?.id??kk(t)),tC!==jZ&&0===rm.length&&0===rw.length&&0===t.length&&tS(!1);return}rf(t=>{let n=t.filter(t=>t.id!==e);return tC!==jZ&&0===n.length&&0===rw.length&&0===rC.length&&tS(!1),n}),tN(t=>{if(t!==e)return t;let n=rm.filter(t=>t.id!==e);return n.at(-1)?.id??rw.at(-1)?.id??kk(rC)})},[rm,rw,rC,tC]),iv=(0,u.useCallback)(e=>{ii(e),ix(`agent:${e}`)},[ii,ix]),ib=(0,u.useCallback)(async(e,t)=>{let n=await dz(e);return n?n.error:(U(e),ix(`agent:${e}`),eo.current?.id===e?(r0(t),eG(e=>e+1)):ii(e),null)},[ix,r0,ii]),iy=el?.id;(0,u.useEffect)(()=>{rC.some(e=>e.sessionId===iy)&&ix(`agent:${iy}`)},[rC,ix,iy]);let iw=(0,u.useCallback)(()=>{el&&(te(null),n5("history"),tK(!1),L&&tg(!1))},[el,L]),ij=eT??(null===el&&rI?rI:null),ik=null===el&&ij?`new:${eA}:${ij}`:null;(0,u.useLayoutEffect)(()=>{eP.current=M?null:ik},[M,ik]);let iS=(0,u.useCallback)((e,t)=>{null===el&&ij&&e.cwd!==ij&&(e_.current=t,e.projectKey&&e.projectRoot&&eF.current?.cwd!==e.cwd&&(eF.current={cwd:e.cwd,project:{key:e.projectKey,root:e.projectRoot},branch:null}),ez.current?.startNewSessionIn({...e,carryComposer:!0}))},[ij,el]),iC=(0,u.useRef)(iS);iC.current=iS;let iE=(0,u.useCallback)(e=>{ez.current?.openFolderForNewSession(e=>iC.current(e,"project"),e)},[]),iM=(0,u.useCallback)(()=>{ez.current?.openDefaultDirectoryForNewSession(e=>iC.current(e,"project"))},[]),i$=(0,u.useCallback)(()=>{ez.current?.refreshWorktrees()},[]),iI=(0,u.useCallback)(async(e,t)=>{let n=ez.current;if(!n)throw Error("The session sidebar is not mounted");let r=await n.createWorktree(e,t);return"path"in r&&(eF.current={cwd:r.path,project:e,branch:t}),r},[]),iT=(0,u.useCallback)(()=>{e_.current=null},[]),iR=(0,u.useRef)(null),iA=ij?function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(e?.cwd===t)return e;if(e?.worktrees?.some(e=>e.path===t))return{...e,cwd:t,currentWorktreePath:t};let r=n?.cwd===t?n:null;if(r&&e?.worktrees&&e.project.key===r.project.key)return{...e,cwd:t,worktrees:[...e.worktrees,{path:t,branch:r.branch,isMain:!1}],currentWorktreePath:t};let i=e?.projects??[],s=r?.project??i.find(e=>e.root===t)??{key:t,root:t},l=s.alias??i.find(e=>e.key===s.key)?.alias;return{cwd:t,project:void 0===l?s:{...s,alias:l},worktrees:null,currentWorktreePath:null,projects:i}}(eO,ij,eF.current):null,iL=iA?iA.project.alias||e2(iA.project.root)||iA.project.root:void 0,iP=null===el&&iA?(0,d.jsx)(pk,{handleRef:iR,context:iA,mobile:L,initialFocus:e_.current,onInitialFocusDone:iT,onPick:iS,onUseDefaultDirectory:iM,onOpenFolder:iE,onRefreshWorktrees:i$,onCreateWorktree:iI}):null,iz=!M&&(null!==el||null!==ij),iO=el?.cwd??ij,iW=rK&&!iz;(0,u.useEffect)(()=>{iz||n5(e=>"debug"===e?null:e)},[iz]),(0,u.useEffect)(()=>{if(to(null),td(!1),tm(null),!iO)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(iO)}`,{signal:e.signal}).then(async e=>{to(await nE(e))}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[iO]);let iF=(0,u.useCallback)(async()=>{if(iO&&!tu){tp(!0),tm(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:iO})}),t=await e.json();if(!e.ok||t.error)return void tm({error:t.error??`HTTP ${e.status}`,...t.reason?{reason:t.reason}:{}});to(t),td(!1),ts(e=>e+1),eQ(e=>e+1)}catch(e){tm({error:e instanceof Error?e.message:String(e)})}finally{tp(!1)}}},[tu,iO]),i_=(0,u.useCallback)(()=>{tm(null),td(!0)},[]),iB=(0,u.useCallback)((e,t)=>{e===iO&&to(t)},[iO]),iH=rm.find(e=>e.id===tC)??null,iU=!tC||tC===jZ,iK=tE||iH?.kind==="changes"||!!iH?.filePath,iq=tW||!iK,iV=rC.find(e=>`agent:${e.sessionId}`===tC)??null,iZ=rI?e2(rI)||rI:null,iJ=iZ?`${iZ} - PI-YUN`:"PI-YUN",iY=(0,u.useCallback)(()=>{tT("file"),tN(jZ),tS(!0),L&&(tg(!1),tK(!1))},[L]),iG=(0,u.useCallback)(e=>{tT("file"),tN(e),tS(!0),L&&(tg(!1),tK(!1))},[L]),iX=!el||el.transient?T("panel.sideNeedsSession"):M||v(el.relation)?T("panel.sideNeedsMain"):null,iQ=(0,u.useCallback)(e=>{let t=el?.cwd??ij??rI;if(!t)return;if("side"===e){if(!el||el.transient||M||v(el.relation))return;let e=nl.current;return e?(te(null),n5(null),tK(!1),L&&tg(!1),e.openSideChat().then(e=>e.handled?e.error??null:T("panel.openFailed"))):Promise.resolve(T("panel.openFailed"))}if("terminal"===e)return void ia(t);let n="files"===e?jJ:jY;rf(t=>t.some(e=>e.id===n)?t:[...t,{id:n,label:T("files"===e?"workbench.openFile":"panel.changes"),filePath:"",kind:e}]),"files"===e&&tO(!1),iG(n)},[el,ij,rI,M,L,ia,iG,T]);(0,u.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.repeat||Array.from(document.querySelectorAll('dialog[open], [role="dialog"], [role="menu"]')).some(e=>e.getClientRects().length>0))return;let t=function(e){if(e.isComposing||229===e.keyCode||e.altGraph||!(e.ctrlKey||e.metaKey))return null;let t=e.key.toLowerCase();return e.altKey?"s"!==t||e.shiftKey?null:"side":"g"===t&&e.shiftKey?"changes":e.shiftKey?null:"p"===t?"files":"`"===t?"terminal":null}({key:e.key,ctrlKey:e.ctrlKey,metaKey:e.metaKey,altKey:e.altKey,shiftKey:e.shiftKey,isComposing:e.isComposing,keyCode:e.keyCode,altGraph:e.getModifierState("AltGraph")});t&&(el?.cwd??ij??rI)&&("side"!==t||!iX)&&(e.preventDefault(),iQ(t))};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[iQ,el?.cwd,ij,rI,iX]),(0,u.useEffect)(()=>{let e=()=>{document.title!==iJ&&(document.title=iJ)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[iJ]);let i0=e9?"settings":n6??(M?"home":"chat"),i1=(0,u.useCallback)(e=>{tT("conversation"),t9(),te(null),n5("archive"),em(e??null),tK(!1),L&&tg(!1)},[t9,L]),i2=e=>{if(tT("conversation"),t9(),"home"===e){rG();let e=eP.current;if(e&&ij){let t=C(ij);nl.current?nl.current.rekeyDraft(e,t):Z(e,t)}eP.current=null,$(!0),te(null),n5(null),tS(!1),L&&tg(!1),k.replace("?home=1",{scroll:!1});return}if("settings"===e){tn(L),te(hk(iO));return}te(null),"chat"===e?(!el&&ik&&ij&&!B(ik)&&Z(C(ij),ik),$(!1),n5(null),el?k.replace(`?session=${encodeURIComponent(el.id)}`,{scroll:!1}):ij&&k.replace(`?cwd=${encodeURIComponent(ij)}`,{scroll:!1})):"system"===e||"tools"===e?n6!==e&&ra(e):("archive"!==e&&($(!1),M&&el&&k.replace(`?session=${encodeURIComponent(el.id)}`,{scroll:!1})),n5(e)),tK(!1),L&&tg(!1)},i4=(0,d.jsx)(py,{activeView:i0,petSessions:eb,onPetSelectSession:r0,conversationAvailable:!!(el||ij),inspectionAvailable:iz,sessionAvailable:!!el,mobile:L,homeButtonRef:tj,onHomeHover:t5.show,onHomeLeave:t5.scheduleHide,onNavigate:i2}),i3=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(iD,{onOpenArchive:i1,archiveActive:"archive"===i0,onArchiveStateChange:ep,fileExplorerTarget:z||tE&&tk?O:null,selectedSessionId:M?null:el?.id??null,onSelectSession:r0,onSelectSideChat:iu,onNewSession:r1,onOpenSettings:()=>{tn(L),te(hk(iO))},controlRef:ez,onNewSessionContextChange:eD,initialSessionId:rH,initialSessionLinked:null!==rU,skipInitialProjectSelection:null!==N.requestedCwd,onInitialRestoreDone:ir,refreshKey:eY,onSessionDeleted:ii,selectedCwd:el?.cwd??eT??null,onCwdChange:rQ,onOpenFile:is,onOpenTerminal:ia,explorerRefreshKey:e6,onExplorerRefresh:r9,onAtMention:rD,onAtMentions:r_,onBackgroundTaskDone:es,hiddenFinishedSessionIds:er,onRunningSessionIdsChange:ek,onSessionsChange:ev}),L&&i4]}),i8=e=>iz&&ta?.requiresTrust&&!ta.trusted?(0,d.jsxs)("button",{type:"button",onClick:i_,title:T("trust.resourcesNotLoaded"),"aria-label":T("trust.resourcesNotLoaded"),style:{display:"flex",alignItems:"center",justifyContent:e?"flex-start":"center",gap:6,width:e?"100%":void 0,minHeight:e?32:void 0,height:e?void 0:"100%",padding:e?"6px 12px":"0 12px",background:e?"color-mix(in srgb, #d97706 8%, var(--bg-panel))":"none",border:"none",borderRight:e?"none":"1px solid var(--border)",borderBottom:e?"1px solid var(--border)":"none",color:"#d97706",cursor:"pointer",flexShrink:0,fontSize:11,lineHeight:1.35,textAlign:"left"},"data-mobile-trust-banner":e?"true":void 0,children:[(0,d.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,d.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,d.jsx)("path",{d:"M12 8v4"}),(0,d.jsx)("path",{d:"M12 16h.01"})]}),(0,d.jsx)("span",{children:T("trust.resourcesNotLoaded")})]}):null,i6=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return(0,d.jsxs)("button",{ref:e$,type:"button",onClick:()=>ri("agents",e&&!P),disabled:!ey,title:eC,"aria-label":eC,"aria-pressed":"agents"===n6,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e||t?kw:void 0,height:"100%",padding:e||t?0:"0 12px",background:"agents"===n6?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===n6?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===n6?"var(--text)":ey?"var(--text-muted)":"var(--text-dim)",cursor:ey?"pointer":"not-allowed",opacity:ey?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},"data-mobile-toolbar-action":e?"agents":void 0,children:[(0,d.jsxs)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,d.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),!e&&!t&&(0,d.jsx)("span",{children:T("agentSwitcher.title")}),eS&&eS.count>0&&(0,d.jsxs)("span",{"aria-hidden":"true",style:{position:"relative",minWidth:15,height:15,padding:"0 4px",display:"grid",placeItems:"center",borderRadius:7,background:eS.running?"color-mix(in srgb, var(--accent) 22%, var(--bg-panel))":"var(--bg-selected)",color:"var(--accent)",fontSize:10,lineHeight:1,fontVariantNumeric:"tabular-nums",fontWeight:eS.running?600:void 0,...e?{position:"absolute",top:3,right:3,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:[eS.running&&(0,d.jsxs)("svg",{className:"animate-spin motion-reduce:animate-none",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{position:"absolute",top:-3,left:-3,width:"calc(100% + 6px)",height:"calc(100% + 6px)",pointerEvents:"none"},children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"11",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),(0,d.jsx)("path",{d:"M23 12a11 11 0 0 0-11-11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),eS.count]})]})};function i5(e){let t,n,r,i,s,l,a=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!e&&!iz)return null;let o=e||a;return(0,d.jsxs)("div",{className:a?"workbench-session-actions":e?void 0:"workspace-toolbar-actions",role:a?"group":void 0,"aria-label":a?T("chat.moreControls"):void 0,style:{display:"flex",alignItems:a?"center":"stretch",flexDirection:a?"column":"row",height:a?"auto":"100%"},children:[(0,d.jsxs)("button",{type:"button",onClick:()=>{iw()},disabled:!el,title:el?T("history.full"):T("history.unsaved"),"aria-label":T("history.full"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:o?kw:void 0,height:"100%",padding:o?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:el?"var(--text-muted)":"var(--text-dim)",cursor:el?"pointer":"not-allowed",opacity:el?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{el&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=el?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"history":void 0,children:[(0,d.jsxs)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:el?"var(--text-muted)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,d.jsx)("path",{d:"M3 3v5h5"}),(0,d.jsx)("path",{d:"M12 7v5l3 2"})]}),!o&&(0,d.jsx)("span",{children:T("history.label")})]}),(t=!!(el&&((nU?.userMessages??0)>0||el.messageCount>0)),n=!el||el.transient||!t||"naming"===nq.kind,r="success"===nq.kind,i="error"===nq.kind,s="naming"===nq.kind?T("title.generating"):r?T("title.updated"):i?T("title.failed"):T("title.generate"),l=!el||el.transient?T("title.unsaved"):t?i?nq.message:T("title.generateSession"):T("title.noMessages"),(0,d.jsxs)("button",{type:"button",onClick:()=>{r5(),e&&P&&tK(!0)},disabled:n,title:l,"aria-label":s,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:o?kw:void 0,height:"100%",padding:o?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:i?"#dc2626":r?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",cursor:n?"not-allowed":"pointer",opacity:n&&"naming"!==nq.kind?.45:1,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{n||(e.currentTarget.style.color=i?"#dc2626":"var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=i?"#dc2626":r?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"name":void 0,children:["naming"===nq.kind?(0,d.jsxs)("svg",{className:"animate-spin",width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,d.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):r?(0,d.jsx)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("path",{d:"m15 4 5 5L7 22l-5-5Z"}),(0,d.jsx)("path",{d:"m14 5 5 5"}),(0,d.jsx)("path",{d:"M6 4V2M5 3H3M19 19v3M17.5 20.5h3"})]}),!o&&(0,d.jsx)("span",{children:s})]})),!(e&&P)&&i6(e,a),nN&&(0,d.jsx)("button",{type:"button",onClick:()=>ri("branches"),title:T("i18n.branches"),"aria-label":T("i18n.branches"),"aria-pressed":"branches"===n6,style:{display:"flex",alignItems:"center",justifyContent:"center",width:kw,height:"100%",padding:0,background:"branches"===n6?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===n6?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===n6?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},"data-mobile-toolbar-action":e?"branches":void 0,children:(0,d.jsxs)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:nu.length>0?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,d.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,d.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,d.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}),(0,d.jsxs)("button",{ref:nW,type:"button",onClick:()=>ra("system"),disabled:e&&!iz,title:T("system.prompt"),"aria-label":T("system.prompt"),"aria-pressed":"system"===n6,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:o?kw:void 0,height:"100%",padding:o?0:"0 12px",background:"system"===n6?"var(--bg-selected)":"none",border:"none",borderTop:"system"===n6?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!iz?"not-allowed":"pointer",color:"system"===n6?"var(--text)":"var(--text-muted)",opacity:e&&!iz?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||iz)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===n6?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"system":void 0,children:[(0,d.jsxs)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:nI?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,d.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,d.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,d.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),!o&&(0,d.jsx)("span",{children:T("system.label")})]}),(0,d.jsxs)("button",{type:"button",onClick:()=>ra("tools"),disabled:e&&!iz,title:T("tools.title"),"aria-label":T("tools.title"),"aria-pressed":"tools"===n6,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:o?kw:void 0,height:"100%",padding:o?0:"0 12px",background:"tools"===n6?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===n6?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!iz?"not-allowed":"pointer",color:"tools"===n6?"var(--text)":"var(--text-muted)",opacity:e&&!iz?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||iz)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===n6?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"tools":void 0,children:[(0,d.jsx)("svg",{width:e?16:12,height:e?16:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:nR?.some(e=>e.active)?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"})}),!o&&(0,d.jsx)("span",{children:T("tools.label")})]})]})}let i9=e=>{if(!e&&(!iz||!nU&&!n1))return null;let t=nU?.tokens,n=nU?.cost??0,r=dJ(n),i="var(--text-muted)",s=null;if(n1?.contextWindow){let e=n1.percent;null!==e&&e>90?i="#ef4444":null!==e&&e>70&&(i="rgba(234,179,8,0.95)"),s=null!==e?`${e.toFixed(0)}%`:null}let l=[];if(t&&(l.push(`${T("session.input")}: ${t.input.toLocaleString(I)}`),l.push(`${T("session.output")}: ${t.output.toLocaleString(I)}`),l.push(`${T("session.cacheRead")}: ${t.cacheRead.toLocaleString(I)}`),l.push(`${T("session.cacheWrite")}: ${t.cacheWrite.toLocaleString(I)}`),n>0&&l.push(`${T("session.cost")}: $${n.toFixed(4)}`)),n1?.contextWindow){let e=n1.percent;l.push(`${T("session.context")}: ${null!==e?`${e.toFixed(1)}%`:"?"} / ${n1.contextWindow.toLocaleString(I)}`)}let a=l.join(" | "),o=e&&P&&tU,c=!!(r||s);return(0,d.jsxs)("div",{style:{display:e?"contents":"flex",alignItems:"center",minWidth:0},children:[(0,d.jsx)("button",{type:"button",onClick:()=>ri("session"),ref:re,disabled:!iz||o,tabIndex:o?-1:void 0,title:a||T("session.title"),"aria-label":T("session.title"),"aria-pressed":"session"===n6,"aria-hidden":!!o||void 0,className:e?"mobile-session-stats":"composer-session-stats","aria-controls":"workspace-usage-page","aria-expanded":"session"===n6,"data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:0,display:"flex",alignItems:"center",justifyContent:"flex-end",flex:e?1:void 0,minWidth:0,gap:e?7:8,paddingLeft:6,paddingRight:6,height:e?"100%":30,overflow:"hidden",visibility:o?"hidden":"visible",pointerEvents:o?"none":"auto",background:"session"===n6?"var(--bg-selected)":"none",border:"none",borderTop:e?"session"===n6?"2px solid var(--accent)":"2px solid transparent":void 0,borderRadius:e?void 0:7,fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:iz?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{iz&&!o&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===n6?"var(--text)":"var(--text-muted)"},children:e?(0,d.jsxs)(d.Fragment,{children:[r&&(0,d.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:r}),s&&(0,d.jsx)("span",{style:{color:i,flexShrink:0},children:s}),!c&&iz&&(0,d.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:T("session.title")})]}):(0,d.jsx)(d.Fragment,{children:r&&(0,d.jsx)("span",{className:"composer-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:r})})}),!e&&n1&&n1.contextWindow>0&&(0,d.jsx)(uz,{usage:n1,onClick:()=>ri("session"),expanded:"session"===n6})]})},i7=e=>{if(!iz)return null;let t="debug"===n6;return(0,d.jsx)("button",{ref:rs,type:"button",onClick:()=>ri("debug",e),title:T("debug.title"),"aria-label":T("debug.title"),"aria-pressed":t,style:{marginLeft:e?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:kw,height:"100%",padding:0,background:t?"var(--bg-selected)":"none",border:"none",borderTop:t?"2px solid var(--accent)":"2px solid transparent",...e?{borderRight:"1px solid var(--border)"}:{borderLeft:"1px solid var(--border)"},color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=t?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"debug":void 0,children:(0,d.jsxs)("svg",{width:e?16:13,height:e?16:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:t?"var(--accent)":"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,d.jsx)("path",{d:"M8 2l1.9 1.9M16 2l-1.9 1.9M9 7.1v-1a3 3 0 0 1 6 0v1"}),(0,d.jsx)("path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6zM12 20v-9"}),(0,d.jsx)("path",{d:"M6.5 9C4.6 8.8 3 7.1 3 5M6 13H2M3 21c0-2.1 1.7-3.9 3.8-4M21 5c0 2.1-1.6 3.8-3.5 4M22 13h-4M17.2 17c2.1.1 3.8 1.9 3.8 4"})]})})},se=e=>(0,d.jsx)(jV,{cwd:el?.cwd??ij,sessionId:el?.id??null,leafId:ny,mobile:e,covered:e&&P&&tU,refreshKey:`${eY}:${e6}`,terminals:rw,onOpenFile:(e,t)=>is(e,e2(e),{sourceSessionId:el?.id??null,modeHint:t?"diff":void 0}),onOpenTerminal:e=>{tT("file"),tN(e),tS(!0),L&&tg(!1)}},`${el?.id??"new"}:${el?.cwd??ij??""}`),st=e=>{let t=e&&P&&tU;return(0,d.jsx)(hh,{tabs:rP,activeId:tC,mobile:e,covered:t,onSelect:iG,onNew:iY,onClose:ix})};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{className:"clipboard-notice-region",role:"status","aria-live":"polite",children:R&&(0,d.jsx)("div",{className:"clipboard-notice",children:T("i18n.copyFailed")})}),(0,d.jsx)("style",{children:`
|
|
1072
|
+
.mobile-session-stats {
|
|
1073
|
+
container-type: inline-size;
|
|
1074
|
+
}
|
|
1075
|
+
@container (max-width: 158px) {
|
|
1076
|
+
.mobile-session-stat-io {
|
|
1077
|
+
display: none !important;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
@container (max-width: 88px) {
|
|
1081
|
+
.mobile-session-stat-cost {
|
|
1082
|
+
display: none !important;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
@media (max-width: 640px) {
|
|
1086
|
+
.sidebar-overlay-backdrop.sidebar-mobile-pending {
|
|
1087
|
+
opacity: 0 !important;
|
|
1088
|
+
pointer-events: none !important;
|
|
1089
|
+
}
|
|
1090
|
+
.sidebar-container.sidebar-mobile-pending.sidebar-open {
|
|
1091
|
+
transform: translateX(calc(-100% - env(safe-area-inset-left)));
|
|
1092
|
+
box-shadow: none;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
`}),(0,d.jsxs)("div",{className:`workspace-shell${z?" is-files-docked":""}`,style:{display:"flex",width:"100%",height:"var(--app-viewport-height, 100dvh)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)",overflow:"hidden",background:"var(--bg)"},children:[!L&&i4,(0,d.jsxs)("div",{className:"workspace-frame",children:[(0,d.jsx)("div",{className:`sidebar-overlay-backdrop${tV?"":" sidebar-mobile-pending"}`,onClick:()=>tg(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!tf,pointerEvents:tf?"auto":"none",transition:"opacity 0.25s ease"}}),(0,d.jsx)("div",{ref:t4.panelRef,id:"session-sidebar",inert:!L&&!tf&&!t5.open,"data-sidebar-peek":t5.open?"":void 0,onPointerEnter:t5.cancel,onPointerLeave:t5.scheduleHide,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||t5.scheduleHide()},className:`sidebar-container${tf?" sidebar-open":" sidebar-closed"}${tx?" is-sidebar-toggling":""}${t5.open?" is-peeking":""}${tV?"":" sidebar-mobile-pending"}${t4.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${t4.width}px`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)",zIndex:t5.open?230:200},children:i3}),!L&&tf&&(0,d.jsx)("div",{...t4.separatorProps,onDoubleClick:rd,onKeyDown:e=>{"Enter"===e.key||" "===e.key?(e.preventDefault(),rd()):t4.separatorProps.onKeyDown(e)},"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${t4.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:T("sidebar.resizeAndCollapseHint")}),!L&&!tf&&(0,d.jsx)("button",{ref:tw,type:"button",className:"sidebar-edge-restore","data-sidebar-restore":"","aria-label":T("sidebar.show"),title:T("sidebar.show"),"aria-controls":"session-sidebar","aria-expanded":!1,onClick:rd}),(0,d.jsxs)("div",{className:`workspace-main${z?" has-unified-header":""}${tk?" is-files-open":""}${tR?" is-focused-workspace":""}${tA?" is-file-focused":""}${tL?" is-conversation-focused":""}${t3.isResizing?" is-panel-resizing":""}`,style:{"--right-panel-width":`${t3.width}px`},children:[z&&(0,d.jsx)("div",{className:"workspace-unified-bar","aria-hidden":"true"}),(0,d.jsxs)("div",{className:"workspace-conversation",style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,d.jsxs)("div",{ref:nc,className:"workspace-chat-header",style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",position:"relative",borderBottom:"1px solid var(--border)",height:"calc(var(--top-bar-height) + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)"},children:[!L&&!tf&&(0,d.jsx)("button",{type:"button",className:"workspace-new-session","data-collapsed-new-chat":"",title:T("sidebar.newChat"),"aria-label":T("sidebar.newChat"),onClick:e=>{t9(),rI?ez.current?.startNewSessionIn({cwd:rI}):ez.current?.openFolderForNewSession(e=>ez.current?.startNewSessionIn(e),e.currentTarget)},children:(0,d.jsx)(n8,{size:16})}),L?(0,d.jsx)("button",{type:"button",onClick:rd,className:"workspace-sidebar-toggle","aria-controls":"session-sidebar","aria-expanded":tf,title:tf?T("sidebar.hide"):T("sidebar.show"),"aria-label":tf?T("sidebar.hide"):T("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:kw,height:kw,padding:0,background:"none",border:"none",borderRight:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:(0,d.jsx)(n4,{size:18,open:tf})}):(0,d.jsx)("span",{className:"workspace-title-folder","aria-hidden":"true",children:(0,d.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,d.jsx)("path",{d:"M3 8V6a2 2 0 0 1 2-2h4l2 3h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8Z"}),(0,d.jsx)("path",{d:"M3 10h18"})]})}),"settings"===i0?(0,d.jsxs)("div",{className:"workspace-location workspace-settings-location","data-view":"settings",children:[(0,d.jsx)("button",{type:"button",className:"workspace-context-tab workspace-settings-heading",disabled:!tP,"aria-label":T("files.showWorkspace",{view:T("common.settings")}),"aria-controls":"workspace-conversation-content","aria-pressed":tP?tL:void 0,onClick:()=>{t$(!0),tT("conversation")},children:T("common.settings")}),(el||ij)&&(0,d.jsxs)("button",{type:"button",className:"workspace-return-session",title:el?e7(el):T("navigation.chat"),"aria-controls":"workspace-conversation-content",onClick:()=>i2("chat"),children:[(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m10 6-6 6 6 6M4 12h16"})}),(0,d.jsx)("span",{children:T("settings.backToConversation")})]})]}):(0,d.jsxs)("button",{type:"button",className:"workspace-location workspace-context-tab","data-view":i0,disabled:!tP,"aria-label":T("files.showWorkspace",{view:T(pv[i0])}),"aria-controls":"workspace-conversation-content","aria-pressed":tP?tL:void 0,onClick:()=>{t$(!0),tT("conversation")},children:[(0,d.jsx)("span",{children:T(pv[i0])}),el&&"home"!==i0&&(0,d.jsx)("strong",{title:e7(el),children:e7(el)}),!el&&"chat"===i0&&(0,d.jsx)("strong",{children:T("navigation.chat")})]}),"chat"===i0&&el?.relation?.kind==="side"&&ey&&(0,d.jsxs)("button",{type:"button",className:"workspace-return-session workspace-return-main",onClick:()=>r0(ey.root),title:T("sideChat.backToMain"),"aria-label":T("sideChat.backToMain"),children:[(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m10 6-6 6 6 6M4 12h16"})}),(0,d.jsx)("span",{children:T("sideChat.backToMain")})]}),!L&&"chat"===i0&&el&&(0,d.jsxs)("button",{type:"button",className:"workspace-title-action",onClick:()=>void r5(),disabled:el.transient||"naming"===nq.kind||!((nU?.userMessages??0)>0||el.messageCount>0),title:"error"===nq.kind?nq.message:T("title.generateSession"),children:[(0,d.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4ZM20 2v4m-2-2h4"})}),(0,d.jsx)("span",{children:T("naming"===nq.kind?"title.generating":"success"===nq.kind?"title.updated":"error"===nq.kind?"title.failed":"title.generate")})]}),L&&(0,d.jsxs)("div",{ref:nd,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:["chat"!==i0&&(0,d.jsx)("span",{className:"workspace-mobile-location",children:T(pv[i0])}),P&&"chat"===i0&&i6(!0),P&&"chat"===i0&&(0,d.jsx)("button",{type:"button",onClick:ru,title:tq,"aria-label":tq,"aria-controls":"mobile-toolbar-actions","aria-expanded":tU,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:tU?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:kw,height:kw,padding:0,background:tU?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:tU?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:tU?(0,d.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,d.jsx)("line",{x1:"5",y1:"5",x2:"19",y2:"19"}),(0,d.jsx)("line",{x1:"19",y1:"5",x2:"5",y2:"19"})]}):(0,d.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,d.jsx)("circle",{cx:"5",cy:"12",r:"1.5"}),(0,d.jsx)("circle",{cx:"12",cy:"12",r:"1.5"}),(0,d.jsx)("circle",{cx:"19",cy:"12",r:"1.5"})]})}),!P&&"chat"===i0&&i5(!0),!P&&"chat"===i0&&i7(!0),"chat"===i0&&i9(!0),"chat"===i0&&se(!0),st(!0),P&&"chat"===i0&&tU&&(0,d.jsxs)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":T("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:`calc(2 * ${kw})`,zIndex:20,display:"flex",alignItems:"stretch",overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none",background:"color-mix(in srgb, var(--bg-panel) 94%, var(--bg))",boxShadow:"4px 0 18px rgba(0,0,0,0.12)",backdropFilter:"blur(10px)"},children:[i5(!0),i7(!0)]})]}),!L&&(0,d.jsxs)(d.Fragment,{children:[i8(!1),"chat"===i0&&i7(!1),"chat"===i0&&se(!1)]}),!L&&st(!1)]}),L&&i8(!0)]}),"chat"===i0&&eM&&ey&&el&&"agents"!==n6&&(0,d.jsx)(wS,{rootSession:ey.root,members:eM,selectedSessionId:el.id,runningSessionIds:ew,onSelectSession:r0,locked:eN,onToggleLock:eI}),(0,d.jsxs)("div",{ref:rn,id:"workspace-conversation-content",className:"workspace-content",inert:tA,"aria-hidden":tA||void 0,style:{flex:1,overflow:"hidden",position:"relative"},children:[e9&&(0,d.jsx)(y0,{embedded:!0,cwd:iO,sessionId:el?.id??null,initialSection:e9,openAtHome:tt,quoteSelectionEnabled:V,onQuoteSelectionChange:Y,onClose:()=>{te(null)},onSessionReloaded:()=>eQ(e=>e+1),projectTrust:ta,onOpenTrustDialog:i_,onProjectTrustChanged:iB}),n6&&!e9&&(0,d.jsxs)("section",{className:"workspace-page",ref:rt,tabIndex:-1,id:"session"===n6?"workspace-usage-page":void 0,"data-theme":"history"===n6?"dark":void 0,"data-workspace-page":n6,"aria-label":T("agents"===n6?"collaboration.title":pv[n6]),children:[(0,d.jsxs)("header",{className:"workspace-page-header",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("h1",{children:T("agents"===n6?"collaboration.title":pv[n6])}),(0,d.jsx)("p",{children:"archive"===n6?T("archive.subtitle"):el?e7(el):iZ})]}),"history"===n6&&el&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("button",{type:"button",className:"workspace-page-back",onClick:()=>n7(e=>e+1),children:T("i18n.refresh")}),(0,d.jsx)(jQ,{sessionId:el.id},el.id)]}),(0,d.jsx)("button",{type:"button",className:"workspace-page-back",onClick:()=>n5(null),children:T(M?"navigation.backHome":"navigation.backChat")})]}),(0,d.jsxs)("div",{className:"workspace-page-content",children:["archive"===n6&&(0,d.jsx)(uW,{snapshot:eu,projectKey:eh,onProjectChange:em,onSelectSession:r0,onRestore:e=>ez.current?.restoreArchivedSession(e)??Promise.resolve(!1),onDelete:e=>ez.current?.deleteArchivedSession(e)??Promise.resolve(!1),onDeleteMany:e=>ez.current?.deleteArchivedSessions(e)??Promise.resolve(!1),onRefresh:()=>{ez.current?.refreshArchive()}}),"history"===n6&&el&&(0,d.jsx)(jX,{sessionId:el.id},`${el.id}:${n9}`),"branches"===n6&&(0,d.jsx)(wi,{embedded:!0,tree:nu,activeLeafId:ny,onLeafChange:n$,locked:nk,hasSession:!!el}),"agents"===n6&&ey&&el&&(0,d.jsx)(wb,{rootSession:ey.root,subagents:ey.subagents,selectedSessionId:el.id,runningSessionIds:ew,onSelectSession:e=>{n5(null),r0(e),requestAnimationFrame(()=>t_(document,e$.current))},openSubagentTabIds:ic,onToggleSubagentTab:(e,t,n)=>{ic.has(e)?ix(`agent:${e}`):(L&&n5(null),io(e,t,n))},onNewSideChat:()=>im(ey.root.id),onDeleteSideChat:e=>ib(e,ey.root)},ey.root.id),"system"===n6&&(0,d.jsx)(ws,{loading:nL,prompt:nI,translate:T}),"tools"===n6&&(0,d.jsx)(wo,{loading:nL,tools:nR,translate:T}),"session"===n6&&(0,d.jsx)("div",{className:"session-info-page",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",padding:"12px 16px"},children:nU?(n=nU.totalActiveMs??0,r=[...nU.sessionName?[{label:T("session.name"),value:nU.sessionName,copyField:null}]:[],{label:T("session.file"),value:nU.sessionFile??T("session.inMemory"),copyField:"file"},{label:T("session.id"),value:nU.sessionId,copyField:"id"},...n>0?[{label:T("session.totalActive"),value:dY(n),copyField:null}]:[]],i=[...el?[{label:T("session.projectDir"),value:el.projectRoot??el.cwd,copyField:"projectDir"}]:[],...el?.branch?[{label:T("session.gitBranch"),value:el.branch,copyField:"gitBranch"}]:[],...el?.isWorktree?[{label:T("session.gitWorktree"),value:el.cwd,copyField:"gitWorktree"}]:[]],s=[[T("session.user"),nU.userMessages.toLocaleString(I)],[T("session.assistant"),nU.assistantMessages.toLocaleString(I)],[T("session.toolCalls"),nU.toolCalls.toLocaleString(I)],[T("session.toolResults"),nU.toolResults.toLocaleString(I)],[T("session.total"),nU.totalMessages.toLocaleString(I)]],l=[[T("session.input"),nU.tokens.input.toLocaleString(I)],[T("session.output"),nU.tokens.output.toLocaleString(I)],...nU.tokens.cacheRead>0?[[T("session.cacheRead"),nU.tokens.cacheRead.toLocaleString(I)]]:[],...nU.tokens.cacheWrite>0?[[T("session.cacheWrite"),nU.tokens.cacheWrite.toLocaleString(I)]]:[],[T("session.total"),nU.tokens.total.toLocaleString(I)]],a=n1??nU.contextUsage,o=[...nU.cost>0?[[T("session.cost"),`${nU.cost.toFixed(4)}`]]:[],...a?.contextWindow?[[T("session.context"),`${null!==a.percent?`${a.percent.toFixed(1)}%`:"?"} / ${dZ(a.contextWindow)}`]]:[],...nU.tokens.cacheRead+nU.tokens.cacheWrite>0&&nU.tokens.cacheRead+nU.tokens.cacheWrite+nU.tokens.input>0?[[T("session.cacheHitRate"),`${(nU.tokens.cacheRead/(nU.tokens.cacheRead+nU.tokens.cacheWrite+nU.tokens.input)*100).toFixed(1)}%`]]:[]],c=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"left",r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:r?"max-content max-content":"auto minmax(0, 1fr)",columnGap:r?14:12,rowGap:4,justifyContent:r?"start":void 0},children:t.map(t=>{let[i,s]=t;return(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:i}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:r?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:s})]},`${e}:${i}`)})})]})},g={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},b=(e,t)=>{let n=nG===e;return(0,d.jsx)("button",{type:"button",title:n?T("session.copied"):T(g[e]),onClick:()=>n0(e,t),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:n?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=n?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:n?(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,d.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,d.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})},y=(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:T("session.infoSection")}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:r.map(e=>(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,d.jsx)("div",{children:e.copyField?b(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),j=i.length>0?(0,d.jsxs)("div",{style:{minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:T("session.projectSection")}),(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:i.map(e=>(0,d.jsxs)("div",{style:{display:"contents"},children:[(0,d.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,d.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,d.jsx)("div",{children:e.copyField?b(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,d.jsxs)("div",{className:"session-stats-details",style:{display:"grid",gridTemplateColumns:L?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:L?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:L?16:20},children:[y,j]}),c(T("session.messages"),s),c(T("session.tokens"),[...l,...o],"right",!0)]})):(0,d.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:T("session.load")})}),"debug"===n6&&(0,d.jsx)(jn,{fallback:T("debug.failed"),children:(0,d.jsx)(jr,{readerRef:nB,selectedSessionId:el?.id??null,sessions:eb,onClose:rl})})]})]}),(0,d.jsx)("div",{className:"workspace-chat-view"+(n6||e9?" is-covered":""),inert:!!(n6||e9),"aria-hidden":!!n6||!!e9||void 0,children:M?(0,d.jsx)(uO,{sessions:ef,runningSessionIds:ew,cwd:rI,onSelectSession:r0,onNewSession:()=>{rI?ez.current?.startNewSessionIn({cwd:rI}):ez.current?.openFolderForNewSession(e=>ez.current?.startNewSessionIn(e),null)},onOpenProject:()=>ez.current?.openFolderForNewSession(e=>ez.current?.startNewSessionIn(e),null)}):iz?(0,d.jsx)(uN,{session:el,searchTarget:e4?.sessionId===el?.id?e4:null,onSearchTargetHandled:e8,initialScrollPosition:el?e0.current.get(el.id)??null:null,onScrollPositionChange:e1,sessionRunning:!!(el&&ew.has(el.id)),newSessionCwd:ij,newSessionDraftKey:ik,newSessionContextBar:iP,newSessionProjectName:iL,onChooseNewSessionProject:e=>iR.current?.openProjectMenu(e),initialNewSessionChoices:null===el?eH:null,onNewSessionChoicesChange:eK,onAgentEnd:r8,onSessionEnded:iv,onToolEnd:ie,onAttentionNeeded:r6,onSessionCreated:r4,onSessionForked:it,onSideSession:ip,modelsRefreshKey:ti,chatInputRef:nl,onBranchDataChange:nM,onSystemPromptChange:nF,onSystemToolsChange:nD,onSystemInfoLoaderChange:n_,onDebugSnapshotReaderChange:nH,onSessionStatsChange:nY,onSessionStatsPanelOpen:ro,sessionStatsControl:L?void 0:i9(!1),onOpenSettings:rc,onContextUsageChange:n3,onOpenFile:il,onFilesUploaded:r9,onOpenSubagent:io,quoteSelectionEnabled:V,soundEnabled:F,onSoundToggle:D,playDoneSound:_,unlockAudio:H,holdAudio:K},eX):"validating"===eq?(0,d.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,d.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:T("workspace.opening")}),(0,d.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:N.requestedCwd})]}):"error"===eq?(0,d.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,d.jsx)("div",{style:{fontSize:14,color:"#dc2626"},children:T("workspace.unable")}),(0,d.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:N.requestedCwd}),(0,d.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eZ})]}):iW?rI?(0,d.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:T("workspace.selectSession")}):(0,d.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,d.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,d.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,d.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:T("workspace.getStarted")}),(0,d.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,d.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),T("workspace.selectProject"),(0,d.jsx)("br",{}),(0,d.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),T("workspace.addModels")]})]})]}):null})]})]}),(0,d.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${tk?" is-open":""}`,onClick:rp}),tk&&!tR&&(0,d.jsx)("div",{...t3.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${t3.isResizing||t8.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${T("layout.resizeFilePanel")}: ${T("layout.resizeHint")}`}),(0,d.jsxs)("div",{ref:ne,id:"file-panel",className:`right-panel-container${tk?" right-panel-open":" right-panel-closed"}${tR?" right-panel-reading-expanded":""}${iq?" is-tree-collapsed":""}${tE?" is-file-picker":""}${t3.isResizing||t8.isResizing?" right-panel-resizing":""}`,style:{"--workbench-tree-width":`${t8.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,d.jsxs)("div",{className:"file-panel-header",style:{display:"flex",alignItems:"center",flexShrink:0,height:"calc(var(--top-bar-height) + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,d.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,d.jsx)(hf,{tabs:iU?[...rP,{id:jZ,label:T("panel.newTab"),filePath:"",kind:"launcher"}]:rP,activeTabId:tL?"":tC??jZ,onSelectTab:iG,onCloseTab:e=>{e===jZ?rP.length?iG(rP.at(-1).id):rp():ix(e)},onOpenTools:iY,onReorderTab:(e,t,n)=>rL(function(e,t,n,r){if(t===n||!e.includes(t)||!e.includes(n))return e;let i=e.filter(e=>e!==t);return i.splice(i.indexOf(n)+ +!!r,0,t),i}(rP.map(e=>e.id),e,t,n))})}),z&&(0,d.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:rh,"aria-controls":"file-panel","aria-pressed":tR,title:T(tR?"files.restorePanelWidth":"files.expandPanel"),"aria-label":T(tR?"files.restorePanelWidth":"files.expandPanel"),children:(0,d.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M14 4h6v6M20 4l-6 6M10 20H4v-6M4 20l6-6"})})}),L&&rP.length>0&&(0,d.jsx)(hh,{tabs:rP,activeId:tC,mobile:!0,covered:!1,onSelect:iG,onNew:iY,onClose:ix}),(0,d.jsx)("button",{type:"button",onClick:rp,className:"file-panel-close-button","aria-controls":"file-panel","aria-expanded":tk,title:T("files.hidePanel"),"aria-label":T("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:kw,height:kw,padding:0,background:"transparent",border:"none",borderRadius:8,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:(0,d.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,d.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"3.5"}),(0,d.jsx)("path",{d:"M12 4v16"})]})})]}),(0,d.jsxs)("div",{className:"workbench-files-body",inert:tL,"aria-hidden":tL||void 0,children:[(0,d.jsxs)("div",{ref:rr,className:"workbench-file-preview",style:{flex:1,minWidth:0,minHeight:0,overflow:"hidden",paddingBottom:"env(safe-area-inset-bottom)"},children:[iU?(0,d.jsx)(hp,{cwd:el?.cwd??ij??rI,sideDisabled:iX,onOpen:iQ},`${el?.id??"new"}:${rI??""}`):iH?.kind==="changes"&&rI?(0,d.jsx)(hm,{cwd:rI,refreshKey:e6,onOpenFile:e=>is(e,e2(e),{modeHint:"diff",sourceSessionId:el?.id})}):iH?.filePath?(0,d.jsx)(ha,{filePath:iH.filePath,cwd:rI??void 0,sourceSessionId:iH.sourceSessionId,gitRefreshKey:e6,initialDisplayMode:iH.initialDisplayMode,initialPage:iH.page,initialState:iH.viewerState,watchEnabled:tk,onStateChange:e=>rW(rx,iH.id,iH.viewerRevision??0,e),onMentionLines:tk?rB:void 0,onAtMention:rD,onOpenFile:(e,t)=>is(e,e2(e),{sourceSessionId:iH.sourceSessionId,page:t})},`${rx}:${iH.id}:${iH.viewerRevision??0}`):rw.some(e=>e.id===tC)||iV?null:(0,d.jsxs)("div",{className:"workbench-file-empty",children:[(0,d.jsx)("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})}),(0,d.jsx)("strong",{children:T("workbench.openFile")}),(0,d.jsx)("span",{children:T(z?"workbench.pickFile":"files.noneOpen")})]}),rw.map(e=>(0,d.jsx)("div",{hidden:e.id!==tC,style:{width:"100%",height:"100%"},children:(0,d.jsx)(kc,{tab:e,active:tk&&!tL&&e.id===tC,onRestart:()=>rj(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?ku(e.cwd):null,n=rw.filter(t=>t.id!==e.id),void(rj(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),tN(r=>r!==e.id?r:t?.id??n.at(-1)?.id??rm.at(-1)?.id??kk(rC)),tC!==jZ&&!t&&!n.length&&!rm.length&&!rC.length&&tS(!1))},onCloseError:()=>rj(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id)),iV&&(0,d.jsx)(jG,{sessionId:iV.sessionId,onSessionEnded:iv,running:ew.has(iV.sessionId),initialPrompt:na[iV.sessionId],onInitialPromptConsumed:()=>no(e=>{if(!(iV.sessionId in e))return e;let t={...e};return delete t[iV.sessionId],t}),modelsRefreshKey:ti,quoteSelectionEnabled:V,onOpenFile:il,onOpenSubagent:io,onSessionForked:(e,t)=>{L&&tS(!1),it(e,t)},onOpenSettings:rc,onToolEnd:ie,onFilesUploaded:r9,soundEnabled:F,onSoundToggle:D,playDoneSound:_,unlockAudio:H,holdAudio:K},iV.sessionId)]}),(0,d.jsxs)("div",{className:"workbench-tree-boundary",inert:iq,"aria-hidden":iq||void 0,children:[(0,d.jsx)("div",{className:"workbench-tree-resizer",...t8.separatorProps,"aria-controls":"workbench-file-tree"}),!tE&&(0,d.jsx)("button",{ref:tD,type:"button",className:"workbench-tree-collapse",onClick:tH,"aria-controls":"workbench-file-tree","aria-expanded":!tW,title:T("files.hideDirectory"),"aria-label":T("files.hideDirectory"),children:(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m9 6 6 6-6 6"})})})]}),(0,d.jsx)("div",{ref:nt,id:"workbench-file-tree",className:"workbench-file-tree",inert:iq,"aria-hidden":iq||void 0}),z&&iK&&(0,d.jsx)("div",{className:"workbench-tree-restore-rail",inert:!tW,"aria-hidden":!tW||void 0,children:tW&&(0,d.jsxs)("button",{ref:tB,type:"button",className:"workbench-tree-restore",onClick:tH,"aria-label":T("files.showDirectory"),title:T("files.showDirectory"),"aria-controls":"workbench-file-tree","aria-expanded":!1,children:[(0,d.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,d.jsx)("path",{d:"m7.5 3-3 3 3 3"})}),(0,d.jsx)("span",{className:"workbench-tree-restore-label","aria-hidden":"true",children:T("files.directoryTab")})]})})]})]})]})]})]}),tc&&iO&&(0,d.jsx)(y2,{cwd:iO,busy:tu,error:th,onCancel:()=>{tu||td(!1)},onConfirm:()=>void iF(),onStatus:to})]})}},41767:(e,t,n)=>{Promise.resolve().then(n.bind(n,16397)),Promise.resolve().then(n.bind(n,21278))},60680:e=>{e.exports={pet:"PetWidget_pet__9_QnF",small:"PetWidget_small__a2Rzg",speech:"PetWidget_speech__PXfM6",bubble:"PetWidget_bubble__cBZ22",appear:"PetWidget_appear__CUcfS",waitingCount:"PetWidget_waitingCount__aovEo",noticeCount:"PetWidget_noticeCount__nXTRT",badge:"PetWidget_badge__WPLi6",sessionLink:"PetWidget_sessionLink__QJsIZ",linkHint:"PetWidget_linkHint__Rc7eh",character:"PetWidget_character__hqkOo",ground:"PetWidget_ground__oWdv_",portrait:"PetWidget_portrait__B5Met",more:"PetWidget_more__cxDnE",actions:"PetWidget_actions__iaBlw",actionHeading:"PetWidget_actionHeading__EWHSZ",actionGrid:"PetWidget_actionGrid__zMRnr",actionFooter:"PetWidget_actionFooter__xKrTO",patIcon:"PetWidget_patIcon__2pVj1",menuTabs:"PetWidget_menuTabs__qo2Ye",notices:"PetWidget_notices__scr9W",preferences:"PetWidget_preferences__xKfAN",noticeRow:"PetWidget_noticeRow__eIHqt",quietSwitch:"PetWidget_quietSwitch__w9Oqh",careHabits:"PetWidget_careHabits__kDx4q",careHabit:"PetWidget_careHabit__ehGD1",careHabitName:"PetWidget_careHabitName__z3aH1",careCountdown:"PetWidget_careCountdown__6Lew6",careTimingSummary:"PetWidget_careTimingSummary__OloX_",careInterval:"PetWidget_careInterval__AId_8",careToggle:"PetWidget_careToggle__Gwfkn",careRestore:"PetWidget_careRestore__6aBnB",careFocus:"PetWidget_careFocus__acXFE",careFocusHeader:"PetWidget_careFocusHeader__GwvYs",careFocusStart:"PetWidget_careFocusStart__azJ14",careClock:"PetWidget_careClock__fO9nO",careButtons:"PetWidget_careButtons__pklMi",careHelp:"PetWidget_careHelp__LJRat",careNoticeTitle:"PetWidget_careNoticeTitle__s20ek",hearts:"PetWidget_hearts__CZkmg","heart-rise":"PetWidget_heart-rise__4KF7P"}},65954:e=>{e.exports={trigger:"ContextUsageIndicator_trigger__lY_Lq",tooltip:"ContextUsageIndicator_tooltip__F8l0T",counts:"ContextUsageIndicator_counts__nqC8l"}},77476:e=>{e.exports={backdrop:"CreateProjectDialog_backdrop__tiFcs",dialog:"CreateProjectDialog_dialog__fsNEp",header:"CreateProjectDialog_header__2piIO",close:"CreateProjectDialog_close__Vl9Hu",nameField:"CreateProjectDialog_nameField__03vpH",nameIcon:"CreateProjectDialog_nameIcon__eYBVG",sources:"CreateProjectDialog_sources__t4b19",sourceCard:"CreateProjectDialog_sourceCard__flGNA",add:"CreateProjectDialog_add__wOO50",hasFolder:"CreateProjectDialog_hasFolder__kxevb",folderRow:"CreateProjectDialog_folderRow__w8vpD",folderText:"CreateProjectDialog_folderText__HK4Zh",sourceOptions:"CreateProjectDialog_sourceOptions__EyQMP",recent:"CreateProjectDialog_recent__zX_4A",hint:"CreateProjectDialog_hint___jLU5",error:"CreateProjectDialog_error__tvB_c",footer:"CreateProjectDialog_footer__bEVEz",cancel:"CreateProjectDialog_cancel__VxOsN",submit:"CreateProjectDialog_submit__VFoxI"}},82190:e=>{e.exports={trigger:"SessionOverview_trigger__g9kwg",panel:"SessionOverview_panel__9BhtZ",card:"SessionOverview_card___MB9q",header:"SessionOverview_header__eRjtZ",icon:"SessionOverview_icon__h_zVb",section:"SessionOverview_section__cQDPv",heading:"SessionOverview_heading__p_LA5",hint:"SessionOverview_hint__RFC7p",counts:"SessionOverview_counts__2nTqx",row:"SessionOverview_row__iLGAq",more:"SessionOverview_more__d2Jw1","overview-enter":"SessionOverview_overview-enter__APglQ","overview-sheet-enter":"SessionOverview_overview-sheet-enter__HmXkO","overview-backdrop-enter":"SessionOverview_overview-backdrop-enter__DJEfp","overview-refresh":"SessionOverview_overview-refresh__YR_US"}},84123:e=>{e.exports={trigger:"AppUpdateButton_trigger__9_G7T",available:"AppUpdateButton_available__nSLjT",panel:"AppUpdateButton_panel__aGx5C",check:"AppUpdateButton_check__yhMl_",versions:"AppUpdateButton_versions__m0oQD",command:"AppUpdateButton_command__sOGem"}},88576:e=>{e.exports={rail:"ChatMinimap_rail__wdMpw",node:"ChatMinimap_node__H6R9H",marker:"ChatMinimap_marker__NEjJc",earlierMarker:"ChatMinimap_earlierMarker__fzRxp",preview:"ChatMinimap_preview__laAya",earlier:"ChatMinimap_earlier__IxOXN",turn:"ChatMinimap_turn__fZuce",number:"ChatMinimap_number__3C_cY",toolBadge:"ChatMinimap_toolBadge__fzFQn",content:"ChatMinimap_content__C7_ju",user:"ChatMinimap_user__WHJHv",userText:"ChatMinimap_userText__Nj9jo",assistant:"ChatMinimap_assistant__s6JLb",assistantJump:"ChatMinimap_assistantJump__3CM2M",outline:"ChatMinimap_outline__aleIF",list:"ChatMinimap_list__g9HUb",paragraph:"ChatMinimap_paragraph__EqWlO",heading:"ChatMinimap_heading__djZbv"}},91822:e=>{e.exports={panel:"AgentSessionPanel_panel__fEVid",toolbar:"AgentSessionPanel_toolbar__CNQSu",action:"AgentSessionPanel_action__t6BxJ",primary:"AgentSessionPanel_primary__M0MLl",summary:"AgentSessionPanel_summary__fQJxv",layout:"AgentSessionPanel_layout__chIMw",list:"AgentSessionPanel_list__oTc1S",group:"AgentSessionPanel_group__PPh_L",member:"AgentSessionPanel_member__j19gc",memberIcon:"AgentSessionPanel_memberIcon__ivqdA",memberCopy:"AgentSessionPanel_memberCopy__5ZTQ_",memberStatus:"AgentSessionPanel_memberStatus__j_Thv",empty:"AgentSessionPanel_empty__Eluxe",detail:"AgentSessionPanel_detail___Dc_q",detailHeader:"AgentSessionPanel_detailHeader__SoBjE",current:"AgentSessionPanel_current__bEOGn",fields:"AgentSessionPanel_fields__MqbbG",status:"AgentSessionPanel_status__AW_Bs",actions:"AgentSessionPanel_actions__9zhc6",more:"AgentSessionPanel_more__kSwfw",confirm:"AgentSessionPanel_confirm__DZloo",error:"AgentSessionPanel_error__jmBDR",search:"AgentSessionPanel_search__c0b9_"}}},e=>{e.O(0,[6766,7330,3888,4908,1278,8441,3794,7358],()=>e(e.s=41767)),_N_E=e.O()}]);
|